more work on multi-db_schema
[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 mro 'c3';
7 use Carp::Clan qw/^DBIx::Class/;
8 use Try::Tiny;
9 use namespace::clean;
10
11 our $VERSION = '0.07010';
12
13 __PACKAGE__->mk_group_accessors('simple', qw/
14     _disable_pk_detection
15     _disable_uniq_detection
16     _disable_fk_detection
17     _passwords
18 /);
19
20 =head1 NAME
21
22 DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
23
24 =head1 SYNOPSIS
25
26 See L<DBIx::Class::Schema::Loader::Base>
27
28 =head1 DESCRIPTION
29
30 This is the base class for L<DBIx::Class::Schema::Loader::Base> classes for
31 DBI-based storage backends, and implements the common functionality between them.
32
33 See L<DBIx::Class::Schema::Loader::Base> for the available options.
34
35 =head1 METHODS
36
37 =head2 new
38
39 Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
40 things.
41
42 =cut
43
44 sub new {
45     my $self = shift->next::method(@_);
46
47     # rebless to vendor-specific class if it exists and loads and we're not in a
48     # custom class.
49     if (not $self->loader_class) {
50         my $dbh = $self->schema->storage->dbh;
51         my $driver = $dbh->{Driver}->{Name};
52
53         my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
54         if ($self->load_optional_class($subclass)) {
55             bless $self, $subclass unless $self->isa($subclass);
56             $self->_rebless;
57         }
58     }
59
60     # Set up the default quoting character and name seperators
61     $self->{_quoter}  = $self->_build_quoter;
62     $self->{_namesep} = $self->_build_namesep;
63
64     # For our usage as regex matches, concatenating multiple quoter
65     # values works fine (e.g. s/\Q<>\E// if quoter was [ '<', '>' ])
66     if( ref $self->{_quoter} eq 'ARRAY') {
67         $self->{_quoter} = join(q{}, @{$self->{_quoter}});
68     }
69
70     $self->_setup;
71
72     $self;
73 }
74
75 sub _build_quoter {
76     my $self = shift;
77     my $dbh = $self->schema->storage->dbh;
78     return $dbh->get_info(29)
79            || $self->schema->storage->sql_maker->quote_char
80            || q{"};
81 }
82
83 sub _build_namesep {
84     my $self = shift;
85     my $dbh = $self->schema->storage->dbh;
86     return $dbh->get_info(41)
87            || $self->schema->storage->sql_maker->name_sep
88            || q{.};
89 }
90
91 # Override this in vendor modules to do things at the end of ->new()
92 sub _setup { }
93
94 # Override this in vendor module to load a subclass if necessary
95 sub _rebless { }
96
97 # Returns an array of table names
98 sub _tables_list { 
99     my ($self, $opts) = (shift, shift);
100
101     my ($table, $type) = @_ ? @_ : ('%', '%');
102
103     my $dbh = $self->schema->storage->dbh;
104     my @tables = $dbh->tables(undef, $table->schema, $table, $type);
105
106     my $qt = qr/[\Q$self->{_quoter}\E"'`\[\]]/;
107
108     my $all_tables_quoted = (grep /$qt/, @tables) == @tables;
109
110     if ($self->{_quoter} && $all_tables_quoted) {
111         s/.* $qt (?= .* $qt\z)//xg for @tables;
112     } else {
113         s/^.*\Q$self->{_namesep}\E// for @tables;
114     }
115     s/$qt//g for @tables;
116
117     return $self->_filter_tables(\@tables, $opts);
118 }
119
120 # apply constraint/exclude and ignore bad tables and views
121 sub _filter_tables {
122     my ($self, $tables, $opts) = @_;
123
124     my @tables = @$tables;
125     my @filtered_tables;
126
127     $opts ||= {};
128     my $constraint   = $opts->{constraint};
129     my $exclude      = $opts->{exclude};
130
131     @tables = grep { /$constraint/ } @$tables if defined $constraint;
132     @tables = grep { ! /$exclude/  } @$tables if defined $exclude;
133
134     LOOP: for my $table (@tables) {
135         try {
136             local $^W = 0; # for ADO
137             my $sth = $self->_sth_for($table, undef, \'1 = 0');
138             $sth->execute;
139         }
140         catch {
141             warn "Bad table or view '$table', ignoring: $_\n";
142             $self->_unregister_source_for_table($table);
143             no warnings 'exiting';
144             next LOOP;
145         };
146
147         push @filtered_tables, $table;
148     }
149
150     return @filtered_tables;
151 }
152
153 =head2 load
154
155 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
156
157 =cut
158
159 sub load {
160     my $self = shift;
161
162     local $self->schema->storage->dbh->{RaiseError} = 1;
163     local $self->schema->storage->dbh->{PrintError} = 0;
164     $self->next::method(@_);
165 }
166
167 sub _table_as_sql {
168     my ($self, $table) = @_;
169
170     my $sql_maker = $self->schema->storage->sql_maker;
171     my $name_sep  = $sql_maker->name_sep;
172     my $schema    = $table->schema;
173
174     if ($schema) {
175         return $self->_quote($schema)
176             . $name_sep
177             . $self->_quote($table);
178     }
179
180     return $self->_quote($table);
181 }
182
183 sub _sth_for {
184     my ($self, $table, $fields, $where) = @_;
185
186     my $dbh = $self->schema->storage->dbh;
187
188     my $sth = $dbh->prepare($self->schema->storage->sql_maker
189         ->select(\$self->_table_as_sql($table), $fields, $where));
190
191     return $sth;
192 }
193
194 # Returns an arrayref of column names
195 sub _table_columns {
196     my ($self, $table) = @_;
197
198     my $sth = $self->_sth_for($table, undef, \'1 = 0');
199     $sth->execute;
200     my $retval = $self->preserve_case ? \@{$sth->{NAME}} : \@{$sth->{NAME_lc}};
201     $sth->finish;
202
203     $retval;
204 }
205
206 # Returns arrayref of pk col names
207 sub _table_pk_info { 
208     my ($self, $table) = @_;
209
210     return [] if $self->_disable_pk_detection;
211
212     my $dbh = $self->schema->storage->dbh;
213
214     my @primary = try {
215         $dbh->primary_key('', $table->schema, $table);
216     }
217     catch {
218         warn "Cannot find primary keys for this driver: $_";
219         $self->_disable_pk_detection(1);
220         return ();
221     };
222
223     return [] if not @primary;
224
225     @primary = map { $self->_lc($_) } @primary;
226     s/\Q$self->{_quoter}\E//g for @primary;
227
228     return \@primary;
229 }
230
231 # Override this for vendor-specific uniq info
232 sub _table_uniq_info {
233     my ($self, $table) = @_;
234
235     return [] if $self->_disable_uniq_detection;
236
237     my $dbh = $self->schema->storage->dbh;
238
239     if (not $dbh->can('statistics_info')) {
240         warn "No UNIQUE constraint information can be gathered for this driver";
241         $self->_disable_uniq_detection(1);
242         return [];
243     }
244
245     my %indices;
246     my $sth = $dbh->statistics_info(undef, $table->schema, $table, 1, 1);
247     while(my $row = $sth->fetchrow_hashref) {
248         # skip table-level stats, conditional indexes, and any index missing
249         #  critical fields
250         next if $row->{TYPE} eq 'table'
251             || defined $row->{FILTER_CONDITION}
252             || !$row->{INDEX_NAME}
253             || !defined $row->{ORDINAL_POSITION}
254             || !$row->{COLUMN_NAME};
255
256         $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME});
257     }
258     $sth->finish;
259
260     my @retval;
261     foreach my $index_name (keys %indices) {
262         my $index = $indices{$index_name};
263         push(@retval, [ $index_name => [ @$index[1..$#$index] ] ]);
264     }
265
266     return \@retval;
267 }
268
269 # Find relationships
270 sub _table_fk_info {
271     my ($self, $table) = @_;
272
273     return [] if $self->_disable_fk_detection;
274
275     my $dbh = $self->schema->storage->dbh;
276     my $sth = try {
277         $dbh->foreign_key_info( '', $table->schema, '',
278                                 '', $table->schema, $table );
279     }
280     catch {
281         warn "Cannot introspect relationships for this driver: $_";
282         $self->_disable_fk_detection(1);
283         return undef;
284     };
285
286     return [] if !$sth;
287
288     my %rels;
289
290     my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
291     while(my $raw_rel = $sth->fetchrow_arrayref) {
292         my $uk_tbl  = $raw_rel->[2];
293         my $uk_col  = $self->_lc($raw_rel->[3]);
294         my $fk_col  = $self->_lc($raw_rel->[7]);
295         my $relid   = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
296         $uk_tbl =~ s/\Q$self->{_quoter}\E//g;
297         $uk_col =~ s/\Q$self->{_quoter}\E//g;
298         $fk_col =~ s/\Q$self->{_quoter}\E//g;
299         $relid  =~ s/\Q$self->{_quoter}\E//g;
300         $rels{$relid}->{tbl} = $uk_tbl;
301         $rels{$relid}->{cols}{$uk_col} = $fk_col;
302     }
303     $sth->finish;
304
305     my @rels;
306     foreach my $relid (keys %rels) {
307         push(@rels, {
308             remote_columns => [ keys   %{$rels{$relid}->{cols}} ],
309             local_columns  => [ values %{$rels{$relid}->{cols}} ],
310             remote_table   => $rels{$relid}->{tbl},
311         });
312     }
313
314     return \@rels;
315 }
316
317 # ported in from DBIx::Class::Storage::DBI:
318 sub _columns_info_for {
319     my ($self, $table) = @_;
320
321     my $dbh = $self->schema->storage->dbh;
322
323     my %result;
324
325     if ($dbh->can('column_info')) {
326         my $sth = $self->_dbh_column_info($dbh, undef, $table->schema, $table, '%' );
327         while ( my $info = $sth->fetchrow_hashref() ){
328             my $column_info = {};
329             $column_info->{data_type}     = lc $info->{TYPE_NAME};
330
331             my $size = $info->{COLUMN_SIZE};
332
333             if (defined $size && defined $info->{DECIMAL_DIGITS}) {
334                 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
335             }
336             elsif (defined $size) {
337                 $column_info->{size} = $size;
338             }
339
340             $column_info->{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
341             $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
342             my $col_name = $info->{COLUMN_NAME};
343             $col_name =~ s/^\"(.*)\"$/$1/;
344
345             $col_name = $self->_lc($col_name);
346
347             my $extra_info = $self->_extra_column_info(
348                 $table, $col_name, $column_info, $info
349             ) || {};
350             $column_info = { %$column_info, %$extra_info };
351
352             $result{$col_name} = $column_info;
353         }
354         $sth->finish;
355
356         return \%result if %result;
357     }
358
359     my $sth = $self->_sth_for($table, undef, \'1 = 0');
360     $sth->execute;
361
362     my @columns = @{ $sth->{NAME} };
363
364     for my $i (0 .. $#columns) {
365         my $column_info = {};
366         $column_info->{data_type} = lc $sth->{TYPE}[$i];
367
368         my $size = $sth->{PRECISION}[$i];
369
370         if (defined $size && defined $sth->{SCALE}[$i]) {
371             $column_info->{size} = [$size, $sth->{SCALE}[$i]];
372         }
373         elsif (defined $size) {
374             $column_info->{size} = $size;
375         }
376
377         $column_info->{is_nullable} = $sth->{NULLABLE}[$i] ? 1 : 0;
378
379         if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
380             $column_info->{data_type} = $1;
381             $column_info->{size}    = $2;
382         }
383
384         my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info, $sth) || {};
385         $column_info = { %$column_info, %$extra_info };
386
387         $result{ $self->_lc($columns[$i]) } = $column_info;
388     }
389     $sth->finish;
390
391     foreach my $col (keys %result) {
392         my $colinfo = $result{$col};
393         my $type_num = $colinfo->{data_type};
394         my $type_name;
395         if (defined $type_num && $type_num =~ /^-?\d+\z/ && $dbh->can('type_info')) {
396             my $type_name = $self->_dbh_type_info_type_name($type_num);
397             $colinfo->{data_type} = lc $type_name if $type_name;
398         }
399     }
400
401     return \%result;
402 }
403
404 # Need to override this for the buggy Firebird ODBC driver.
405 sub _dbh_type_info_type_name {
406     my ($self, $type_num) = @_;
407
408     my $dbh = $self->schema->storage->dbh;
409
410     my $type_info = $dbh->type_info($type_num);
411     
412     return $type_info ? $type_info->{TYPE_NAME} : undef;
413 }
414
415 # do not use this, override _columns_info_for instead
416 sub _extra_column_info {}
417
418 # override to mask warnings if needed (see mysql)
419 sub _dbh_column_info {
420     my ($self, $dbh) = (shift, shift);
421
422     return $dbh->column_info(@_);
423 }
424
425 # If a coderef uses DBI->connect, this should get its connect info.
426 sub _try_infer_connect_info_from_coderef {
427     my ($self, $code) = @_;
428
429     my ($dsn, $user, $pass, $params);
430
431     no warnings 'redefine';
432
433     local *DBI::connect = sub {
434         (undef, $dsn, $user, $pass, $params) = @_;
435     };
436
437     $code->();
438
439     return ($dsn, $user, $pass, $params);
440 }
441
442 =head1 SEE ALSO
443
444 L<DBIx::Class::Schema::Loader>
445
446 =head1 AUTHOR
447
448 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
449
450 =head1 LICENSE
451
452 This library is free software; you can redistribute it and/or modify it under
453 the same terms as Perl itself.
454
455 =cut
456
457 1;
458 # vim:et sts=4 sw=4 tw=0: