suppress 'bad table' warnings for filtered tables, preserve case of MSSQL table names
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI.pm
1 package DBIx::Class::Schema::Loader::DBI;
2
3 use strict;
4 use warnings;
5 use base qw/DBIx::Class::Schema::Loader::Base/;
6 use Class::C3;
7 use Carp::Clan qw/^DBIx::Class/;
8
9 our $VERSION = '0.05003';
10
11 =head1 NAME
12
13 DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
14
15 =head1 SYNOPSIS
16
17 See L<DBIx::Class::Schema::Loader::Base>
18
19 =head1 DESCRIPTION
20
21 This is the base class for L<DBIx::Class::Schema::Loader::Base> classes for
22 DBI-based storage backends, and implements the common functionality between them.
23
24 See L<DBIx::Class::Schema::Loader::Base> for the available options.
25
26 =head1 METHODS
27
28 =head2 new
29
30 Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
31 things.
32
33 =cut
34
35 sub new {
36     my $self = shift->next::method(@_);
37
38     # rebless to vendor-specific class if it exists and loads
39     my $dbh = $self->schema->storage->dbh;
40     my $driver = $dbh->{Driver}->{Name};
41
42     my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
43     if ($self->load_optional_class($subclass)) {
44         bless $self, $subclass unless $self->isa($subclass);
45         $self->_rebless;
46     }
47
48     # Set up the default quoting character and name seperators
49     $self->{_quoter}  = $self->_build_quoter;
50     $self->{_namesep} = $self->_build_namesep;
51
52     # For our usage as regex matches, concatenating multiple quoter
53     # values works fine (e.g. s/\Q<>\E// if quoter was [ '<', '>' ])
54     if( ref $self->{_quoter} eq 'ARRAY') {
55         $self->{_quoter} = join(q{}, @{$self->{_quoter}});
56     }
57
58     $self->_setup;
59
60     $self;
61 }
62
63 sub _build_quoter {
64     my $self = shift;
65     my $dbh = $self->schema->storage->dbh;
66     return $dbh->get_info(29)
67            || $self->schema->storage->sql_maker->quote_char
68            || q{"};
69 }
70
71 sub _build_namesep {
72     my $self = shift;
73     my $dbh = $self->schema->storage->dbh;
74     return $dbh->get_info(41)
75            || $self->schema->storage->sql_maker->name_sep
76            || q{.};
77 }
78
79 # Override this in vendor modules to do things at the end of ->new()
80 sub _setup { }
81
82 # Override this in vendor module to load a subclass if necessary
83 sub _rebless { }
84
85 # Returns an array of table names
86 sub _tables_list { 
87     my ($self, $opts) = (shift, shift);
88
89     my ($table, $type) = @_ ? @_ : ('%', '%');
90
91     my $dbh = $self->schema->storage->dbh;
92     my @tables = $dbh->tables(undef, $self->db_schema, $table, $type);
93
94     my $qt = qr/[\Q$self->{_quoter}\E"'`\[\]]/;
95
96     my $all_tables_quoted = (grep /$qt/, @tables) == @tables;
97
98     if ($self->{_quoter} && $all_tables_quoted) {
99         s/.* $qt (?= .* $qt)//xg for @tables;
100     } else {
101         s/^.*\Q$self->{_namesep}\E// for @tables;
102     }
103     s/$qt//g for @tables;
104
105     return $self->_filter_tables(\@tables, $opts);
106 }
107
108 # apply constraint/exclude and ignore bad tables and views
109 sub _filter_tables {
110     my ($self, $tables, $opts) = @_;
111
112     my @tables = @$tables;
113     my @filtered_tables;
114
115     $opts ||= {};
116     my $constraint   = $opts->{constraint};
117     my $exclude      = $opts->{exclude};
118
119     @tables = grep { /$constraint/ } @$tables if defined $constraint;
120     @tables = grep { ! /$exclude/  } @$tables if defined $exclude;
121
122     for my $table (@tables) {
123         eval {
124             my $sth = $self->_sth_for($table, undef, \'1 = 0');
125             $sth->execute;
126         };
127         if (not $@) {
128             push @filtered_tables, $table;
129         }
130         else {
131             warn "Bad table or view '$table', ignoring: $@\n";
132             local $@;
133             eval {
134                 my $schema = $self->schema;
135                 # in older DBIC it's a private method
136                 my $unregister = $schema->can('unregister_source')
137                     || $schema->can('_unregister_source');
138                 $schema->$unregister($self->_table2moniker($table));
139             };
140         }
141     }
142
143     return @filtered_tables;
144 }
145
146 =head2 load
147
148 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
149
150 =cut
151
152 sub load {
153     my $self = shift;
154
155     local $self->schema->storage->dbh->{RaiseError} = 1;
156     local $self->schema->storage->dbh->{PrintError} = 0;
157     $self->next::method(@_);
158 }
159
160 sub _table_as_sql {
161     my ($self, $table) = @_;
162
163     if($self->{db_schema}) {
164         $table = $self->{db_schema} . $self->{_namesep} .
165             $self->_quote_table_name($table);
166     } else {
167         $table = $self->_quote_table_name($table);
168     }
169
170     return $table;
171 }
172
173 sub _sth_for {
174     my ($self, $table, $fields, $where) = @_;
175
176     my $dbh = $self->schema->storage->dbh;
177
178     my $sth = $dbh->prepare($self->schema->storage->sql_maker
179         ->select(\$self->_table_as_sql($table), $fields, $where));
180
181     return $sth;
182 }
183
184 # Returns an arrayref of column names
185 sub _table_columns {
186     my ($self, $table) = @_;
187
188     my $sth = $self->_sth_for($table, undef, \'1 = 0');
189     $sth->execute;
190     my $retval = $self->_is_case_sensitive ? \@{$sth->{NAME}} : \@{$sth->{NAME_lc}};
191     $sth->finish;
192
193     $retval;
194 }
195
196 # Returns arrayref of pk col names
197 sub _table_pk_info { 
198     my ($self, $table) = @_;
199
200     my $dbh = $self->schema->storage->dbh;
201
202     my @primary = map { lc } $dbh->primary_key('', $self->db_schema, $table);
203     s/\Q$self->{_quoter}\E//g for @primary;
204
205     return \@primary;
206 }
207
208 # Override this for vendor-specific uniq info
209 sub _table_uniq_info {
210     my ($self, $table) = @_;
211
212     my $dbh = $self->schema->storage->dbh;
213     if(!$dbh->can('statistics_info')) {
214         warn "No UNIQUE constraint information can be gathered for this vendor";
215         return [];
216     }
217
218     my %indices;
219     my $sth = $dbh->statistics_info(undef, $self->db_schema, $table, 1, 1);
220     while(my $row = $sth->fetchrow_hashref) {
221         # skip table-level stats, conditional indexes, and any index missing
222         #  critical fields
223         next if $row->{TYPE} eq 'table'
224             || defined $row->{FILTER_CONDITION}
225             || !$row->{INDEX_NAME}
226             || !defined $row->{ORDINAL_POSITION}
227             || !$row->{COLUMN_NAME};
228
229         $indices{$row->{INDEX_NAME}}->{$row->{ORDINAL_POSITION}} = $row->{COLUMN_NAME};
230     }
231     $sth->finish;
232
233     my @retval;
234     foreach my $index_name (keys %indices) {
235         my $index = $indices{$index_name};
236         push(@retval, [ $index_name => [
237             map { $index->{$_} }
238                 sort keys %$index
239         ]]);
240     }
241
242     return \@retval;
243 }
244
245 # Find relationships
246 sub _table_fk_info {
247     my ($self, $table) = @_;
248
249     my $dbh = $self->schema->storage->dbh;
250     my $sth = $dbh->foreign_key_info( '', $self->db_schema, '',
251                                       '', $self->db_schema, $table );
252     return [] if !$sth;
253
254     my %rels;
255
256     my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
257     while(my $raw_rel = $sth->fetchrow_arrayref) {
258         my $uk_tbl  = $raw_rel->[2];
259         my $uk_col  = lc $raw_rel->[3];
260         my $fk_col  = lc $raw_rel->[7];
261         my $relid   = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
262         $uk_tbl =~ s/\Q$self->{_quoter}\E//g;
263         $uk_col =~ s/\Q$self->{_quoter}\E//g;
264         $fk_col =~ s/\Q$self->{_quoter}\E//g;
265         $relid  =~ s/\Q$self->{_quoter}\E//g;
266         $rels{$relid}->{tbl} = $uk_tbl;
267         $rels{$relid}->{cols}->{$uk_col} = $fk_col;
268     }
269     $sth->finish;
270
271     my @rels;
272     foreach my $relid (keys %rels) {
273         push(@rels, {
274             remote_columns => [ keys   %{$rels{$relid}->{cols}} ],
275             local_columns  => [ values %{$rels{$relid}->{cols}} ],
276             remote_table   => $rels{$relid}->{tbl},
277         });
278     }
279
280     return \@rels;
281 }
282
283 # ported in from DBIx::Class::Storage::DBI:
284 sub _columns_info_for {
285     my ($self, $table) = @_;
286
287     my $dbh = $self->schema->storage->dbh;
288
289     if ($dbh->can('column_info')) {
290         my %result;
291         eval {
292             my $sth = $dbh->column_info( undef, $self->db_schema, $table, '%' );
293             while ( my $info = $sth->fetchrow_hashref() ){
294                 my $column_info = {};
295                 $column_info->{data_type}     = $info->{TYPE_NAME};
296                 $column_info->{size}          = $info->{COLUMN_SIZE} if defined $info->{COLUMN_SIZE};
297                 $column_info->{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
298                 $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
299                 my $col_name = $info->{COLUMN_NAME};
300                 $col_name =~ s/^\"(.*)\"$/$1/;
301
302                 my $extra_info = $self->_extra_column_info(
303                     $table, $col_name, $column_info, $info
304                 ) || {};
305                 $column_info = { %$column_info, %$extra_info };
306
307                 $result{$col_name} = $column_info;
308             }
309             $sth->finish;
310         };
311       return \%result if !$@ && scalar keys %result;
312     }
313
314     my %result;
315     my $sth = $self->_sth_for($table, undef, \'1 = 0');
316     $sth->execute;
317     my @columns = @{ $self->_is_case_sensitive ? $sth->{NAME} : $sth->{NAME_lc} };
318     for my $i ( 0 .. $#columns ){
319         my $column_info = {};
320         $column_info->{data_type} = $sth->{TYPE}->[$i];
321         $column_info->{size} = $sth->{PRECISION}->[$i] if $sth->{PRECISION}->[$i];
322         $column_info->{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
323
324         if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
325             $column_info->{data_type} = $1;
326             $column_info->{size}    = $2;
327         }
328
329         my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info) || {};
330         $column_info = { %$column_info, %$extra_info };
331
332         $result{$columns[$i]} = $column_info;
333     }
334     $sth->finish;
335
336     foreach my $col (keys %result) {
337         my $colinfo = $result{$col};
338         my $type_num = $colinfo->{data_type};
339         my $type_name;
340         if(defined $type_num && $type_num =~ /^\d+\z/ && $dbh->can('type_info')) {
341             my $type_info = $dbh->type_info($type_num);
342             $type_name = $type_info->{TYPE_NAME} if $type_info;
343             $colinfo->{data_type} = $type_name if $type_name;
344         }
345     }
346
347     return \%result;
348 }
349
350 # Override this in vendor class to return any additional column
351 # attributes
352 sub _extra_column_info {}
353
354 =head1 SEE ALSO
355
356 L<DBIx::Class::Schema::Loader>
357
358 =head1 AUTHOR
359
360 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
361
362 =head1 LICENSE
363
364 This library is free software; you can redistribute it and/or modify it under
365 the same terms as Perl itself.
366
367 =cut
368
369 1;