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