Release 0.07037
[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 Try::Tiny;
8 use List::MoreUtils 'any';
9 use Carp::Clan qw/^DBIx::Class/;
10 use namespace::clean;
11 use DBIx::Class::Schema::Loader::Table ();
12
13 our $VERSION = '0.07037';
14
15 __PACKAGE__->mk_group_accessors('simple', qw/
16     _disable_pk_detection
17     _disable_uniq_detection
18     _disable_fk_detection
19     _passwords
20     quote_char
21     name_sep
22 /);
23
24 =head1 NAME
25
26 DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
27
28 =head1 SYNOPSIS
29
30 See L<DBIx::Class::Schema::Loader::Base>
31
32 =head1 DESCRIPTION
33
34 This is the base class for L<DBIx::Class::Schema::Loader::Base> classes for
35 DBI-based storage backends, and implements the common functionality between them.
36
37 See L<DBIx::Class::Schema::Loader::Base> for the available options.
38
39 =head1 METHODS
40
41 =head2 new
42
43 Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
44 things.
45
46 =cut
47
48 sub new {
49     my $self = shift->next::method(@_);
50
51     # rebless to vendor-specific class if it exists and loads and we're not in a
52     # custom class.
53     if (not $self->loader_class) {
54         my $driver = $self->dbh->{Driver}->{Name};
55
56         my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
57         if ((not $self->isa($subclass)) && $self->load_optional_class($subclass)) {
58             bless $self, $subclass;
59             $self->_rebless;
60             Class::C3::reinitialize() if $] < 5.009005;
61         }
62     }
63
64     # Set up the default quoting character and name separators
65     $self->quote_char($self->_build_quote_char);
66     $self->name_sep($self->_build_name_sep);
67
68     $self->_setup;
69
70     return $self;
71 }
72
73 sub _build_quote_char {
74     my $self = shift;
75
76     my $quote_char = $self->dbh->get_info(29)
77            || $self->schema->storage->sql_maker->quote_char
78            || q{"};
79
80     # For our usage as regex matches, concatenating multiple quote_char
81     # values works fine (e.g. s/[\Q<>\E]// if quote_char was [ '<', '>' ])
82     if (ref $quote_char eq 'ARRAY') {
83         $quote_char = join '', @$quote_char;
84     }
85
86     return $quote_char;
87 }
88
89 sub _build_name_sep {
90     my $self = shift;
91     return $self->dbh->get_info(41)
92            || $self->schema->storage->sql_maker->name_sep
93            || '.';
94 }
95
96 # Override this in vendor modules to do things at the end of ->new()
97 sub _setup { }
98
99 # Override this in vendor module to load a subclass if necessary
100 sub _rebless { }
101
102 sub _system_schemas {
103     return ('information_schema');
104 }
105
106 sub _system_tables {
107     return ();
108 }
109
110 sub _dbh_tables {
111     my ($self, $schema) = (shift, shift);
112
113     my ($table_pattern, $table_type_pattern) = @_ ? @_ : ('%', '%');
114
115     return $self->dbh->tables(undef, $schema, $table_pattern, $table_type_pattern);
116 }
117
118 # default to be overridden in subclasses if necessary
119 sub _supports_db_schema { 1 }
120
121 # Returns an array of table objects
122 sub _tables_list {
123     my ($self, $opts) = (shift, shift);
124
125     my @tables;
126
127     my $qt  = qr/[\Q$self->{quote_char}\E"'`\[\]]/;
128     my $nqt = qr/[^\Q$self->{quote_char}\E"'`\[\]]/;
129     my $ns  = qr/[\Q$self->{name_sep}\E]/;
130     my $nns = qr/[^\Q$self->{name_sep}\E]/;
131
132     foreach my $schema (@{ $self->db_schema || [undef] }) {
133         my @raw_table_names = $self->_dbh_tables($schema, @_);
134
135         TABLE: foreach my $raw_table_name (@raw_table_names) {
136             my $quoted = $raw_table_name =~ /^$qt/;
137
138             # These regexes are not entirely correct, but hopefully they will work
139             # in most cases. RT reports welcome.
140             my ($schema_name, $table_name1, $table_name2) = $quoted ?
141                 $raw_table_name =~ /^(?:${qt}(${nqt}+?)${qt}${ns})?(?:${qt}(.+?)${qt}|(${nns}+))\z/
142                 :
143                 $raw_table_name =~ /^(?:(${nns}+?)${ns})?(?:${qt}(.+?)${qt}|(${nns}+))\z/;
144
145             my $table_name = $table_name1 || $table_name2;
146
147             foreach my $system_schema ($self->_system_schemas) {
148                 if ($schema_name) {
149                     my $matches = 0;
150
151                     if (ref $system_schema) {
152                         $matches = 1
153                             if $schema_name =~ $system_schema
154                                  && $schema !~ $system_schema;
155                     }
156                     else {
157                         $matches = 1
158                             if $schema_name eq $system_schema
159                                 && $schema  ne $system_schema;
160                     }
161
162                     next TABLE if $matches;
163                 }
164             }
165
166             foreach my $system_table ($self->_system_tables) {
167                 my $matches = 0;
168
169                 if (ref $system_table) {
170                     $matches = 1 if $table_name =~ $system_table;
171                 }
172                 else {
173                     $matches = 1 if $table_name eq $system_table
174                 }
175
176                 next TABLE if $matches;
177             }
178
179             $schema_name ||= $schema;
180
181             my $table = DBIx::Class::Schema::Loader::Table->new(
182                 loader => $self,
183                 name   => $table_name,
184                 schema => $schema_name,
185                 ($self->_supports_db_schema ? () : (
186                     ignore_schema => 1
187                 )),
188             );
189
190             push @tables, $table;
191         }
192     }
193
194     return $self->_filter_tables(\@tables, $opts);
195 }
196
197 sub _recurse_constraint {
198     my ($constraint, @parts) = @_;
199
200     my $name = shift @parts;
201
202     # If there are any parts left, the constraint must be an arrayref
203     croak "depth of constraint/exclude array does not match length of moniker_parts"
204         unless !!@parts == !!(ref $constraint eq 'ARRAY');
205
206     # if ths is the last part, use the constraint directly
207     return $name =~ $constraint unless @parts;
208
209     # recurse into the first matching subconstraint
210     foreach (@{$constraint}) {
211         my ($re, $sub) = @{$_};
212         return _recurse_constraint($sub, @parts)
213             if $name =~ $re;
214     }
215     return 0;
216 }
217
218 sub _check_constraint {
219     my ($include, $constraint, @tables) = @_;
220
221     return @tables unless defined $constraint;
222
223     return grep { !$include xor _recurse_constraint($constraint, @{$_}) } @tables
224         if ref $constraint eq 'ARRAY';
225
226     return grep { !$include xor /$constraint/ } @tables;
227 }
228
229
230
231 # apply constraint/exclude and ignore bad tables and views
232 sub _filter_tables {
233     my ($self, $tables, $opts) = @_;
234
235     my @tables = @$tables;
236     my @filtered_tables;
237
238     $opts ||= {};
239     @tables = _check_constraint(1, $opts->{constraint}, @tables);
240     @tables = _check_constraint(0, $opts->{exclude}, @tables);
241
242     TABLE: for my $table (@tables) {
243         try {
244             local $^W = 0; # for ADO
245             my $sth = $self->_sth_for($table, undef, \'1 = 0');
246             $sth->execute;
247             1;
248         }
249         catch {
250             warn "Bad table or view '$table', ignoring: $_\n";
251             0;
252         } or next TABLE;
253
254         push @filtered_tables, $table;
255     }
256
257     return @filtered_tables;
258 }
259
260 =head2 load
261
262 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
263
264 =cut
265
266 sub load {
267     my $self = shift;
268
269     local $self->dbh->{RaiseError} = 1;
270     local $self->dbh->{PrintError} = 0;
271
272     $self->next::method(@_);
273
274     $self->schema->storage->disconnect unless $self->dynamic;
275 }
276
277 sub _sth_for {
278     my ($self, $table, $fields, $where) = @_;
279
280     my $sth = $self->dbh->prepare($self->schema->storage->sql_maker
281         ->select(\$table->sql_name, $fields, $where));
282
283     return $sth;
284 }
285
286 # Returns an arrayref of column names
287 sub _table_columns {
288     my ($self, $table) = @_;
289
290     my $sth = $self->_sth_for($table, undef, \'1 = 0');
291     $sth->execute;
292
293     my $retval = [ map $self->_lc($_), @{$sth->{NAME}} ];
294
295     $sth->finish;
296
297     return $retval;
298 }
299
300 # Returns arrayref of pk col names
301 sub _table_pk_info {
302     my ($self, $table) = @_;
303
304     return [] if $self->_disable_pk_detection;
305
306     my @primary = try {
307         $self->dbh->primary_key('', $table->schema, $table->name);
308     }
309     catch {
310         warn "Cannot find primary keys for this driver: $_";
311         $self->_disable_pk_detection(1);
312         return ();
313     };
314
315     return [] if not @primary;
316
317     @primary = map { $self->_lc($_) } @primary;
318     s/[\Q$self->{quote_char}\E]//g for @primary;
319
320     return \@primary;
321 }
322
323 # Override this for vendor-specific uniq info
324 sub _table_uniq_info {
325     my ($self, $table) = @_;
326
327     return [] if $self->_disable_uniq_detection;
328
329     if (not $self->dbh->can('statistics_info')) {
330         warn "No UNIQUE constraint information can be gathered for this driver";
331         $self->_disable_uniq_detection(1);
332         return [];
333     }
334
335     my %indices;
336     my $sth = $self->dbh->statistics_info(undef, $table->schema, $table->name, 1, 1);
337     while(my $row = $sth->fetchrow_hashref) {
338         # skip table-level stats, conditional indexes, and any index missing
339         #  critical fields
340         next if $row->{TYPE} eq 'table'
341             || defined $row->{FILTER_CONDITION}
342             || !$row->{INDEX_NAME}
343             || !defined $row->{ORDINAL_POSITION}
344             || !$row->{COLUMN_NAME};
345
346         $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME});
347     }
348     $sth->finish;
349
350     my @retval;
351     foreach my $index_name (keys %indices) {
352         my $index = $indices{$index_name};
353         push(@retval, [ $index_name => [ @$index[1..$#$index] ] ]);
354     }
355
356     return \@retval;
357 }
358
359 sub _table_comment {
360     my ($self, $table) = @_;
361     my $dbh = $self->dbh;
362
363     my $comments_table = $table->clone;
364     $comments_table->name($self->table_comments_table);
365
366     my ($comment) =
367         (exists $self->_tables->{$comments_table->sql_name} || undef)
368         && try { $dbh->selectrow_array(<<"EOF") };
369 SELECT comment_text
370 FROM @{[ $comments_table->sql_name ]}
371 WHERE table_name = @{[ $dbh->quote($table->name) ]}
372 EOF
373
374     # Failback: try the REMARKS column on table_info
375     if (!$comment) {
376         my $info = $self->_dbh_table_info( $dbh, $table );
377         $comment = $info->{REMARKS} if $info;
378     }
379
380     return $comment;
381 }
382
383 sub _column_comment {
384     my ($self, $table, $column_number, $column_name) = @_;
385     my $dbh = $self->dbh;
386
387     my $comments_table = $table->clone;
388     $comments_table->name($self->column_comments_table);
389
390     my ($comment) =
391         (exists $self->_tables->{$comments_table->sql_name} || undef)
392         && try { $dbh->selectrow_array(<<"EOF") };
393 SELECT comment_text
394 FROM @{[ $comments_table->sql_name ]}
395 WHERE table_name = @{[ $dbh->quote($table->name) ]}
396 AND column_name = @{[ $dbh->quote($column_name) ]}
397 EOF
398
399     # Failback: try the REMARKS column on column_info
400     if (!$comment && $dbh->can('column_info')) {
401         if (my $sth = try { $self->_dbh_column_info( $dbh, undef, $table->schema, $table->name, $column_name ) }) {
402             my $info = $sth->fetchrow_hashref();
403             $comment = $info->{REMARKS};
404         }
405     }
406
407     return $comment;
408 }
409
410 # Find relationships
411 sub _table_fk_info {
412     my ($self, $table) = @_;
413
414     return [] if $self->_disable_fk_detection;
415
416     my $sth = try {
417         $self->dbh->foreign_key_info( '', '', '',
418                                 '', ($table->schema || ''), $table->name );
419     }
420     catch {
421         warn "Cannot introspect relationships for this driver: $_";
422         $self->_disable_fk_detection(1);
423         return undef;
424     };
425
426     return [] if !$sth;
427
428     my %rels;
429
430     my @rules = (
431         'CASCADE',
432         'RESTRICT',
433         'SET NULL',
434         'NO ACTION',
435         'SET DEFAULT',
436     );
437
438     my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
439     REL: while(my $raw_rel = $sth->fetchrow_arrayref) {
440         my $uk_scm  = $raw_rel->[1];
441         my $uk_tbl  = $raw_rel->[2];
442         my $uk_col  = $self->_lc($raw_rel->[3]);
443         my $fk_scm  = $raw_rel->[5];
444         my $fk_col  = $self->_lc($raw_rel->[7]);
445         my $key_seq = $raw_rel->[8] - 1;
446         my $relid   = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
447
448         my $update_rule = $raw_rel->[9];
449         my $delete_rule = $raw_rel->[10];
450
451         $update_rule = $rules[$update_rule] if defined $update_rule;
452         $delete_rule = $rules[$delete_rule] if defined $delete_rule;
453
454         my $is_deferrable = $raw_rel->[13];
455
456         ($is_deferrable = $is_deferrable == 7 ? 0 : 1)
457             if defined $is_deferrable;
458
459         foreach my $var ($uk_scm, $uk_tbl, $uk_col, $fk_scm, $fk_col, $relid) {
460             $var =~ s/[\Q$self->{quote_char}\E]//g if defined $var;
461         }
462
463         if ($self->db_schema && $self->db_schema->[0] ne '%'
464             && (not any { $_ eq $uk_scm } @{ $self->db_schema })) {
465
466             next REL;
467         }
468
469         $rels{$relid}{tbl} ||= DBIx::Class::Schema::Loader::Table->new(
470             loader => $self,
471             name   => $uk_tbl,
472             schema => $uk_scm,
473             ($self->_supports_db_schema ? () : (
474                 ignore_schema => 1
475             )),
476         );
477
478         $rels{$relid}{attrs}{on_delete}     = $delete_rule if $delete_rule;
479         $rels{$relid}{attrs}{on_update}     = $update_rule if $update_rule;
480         $rels{$relid}{attrs}{is_deferrable} = $is_deferrable if defined $is_deferrable;
481
482         # Add this data IN ORDER
483         $rels{$relid}{rcols}[$key_seq] = $uk_col;
484         $rels{$relid}{lcols}[$key_seq] = $fk_col;
485     }
486     $sth->finish;
487
488     my @rels;
489     foreach my $relid (keys %rels) {
490         push(@rels, {
491             remote_columns => [ grep defined, @{ $rels{$relid}{rcols} } ],
492             local_columns  => [ grep defined, @{ $rels{$relid}{lcols} } ],
493             remote_table   => $rels{$relid}->{tbl},
494             (exists $rels{$relid}{attrs} ?
495                 (attrs => $rels{$relid}{attrs})
496                 :
497                 ()
498             ),
499             _constraint_name => $relid,
500         });
501     }
502
503     return \@rels;
504 }
505
506 # ported in from DBIx::Class::Storage::DBI:
507 sub _columns_info_for {
508     my ($self, $table) = @_;
509
510     my $dbh = $self->schema->storage->dbh;
511
512     my %result;
513
514     if (my $sth = try { $self->_dbh_column_info($dbh, undef, $table->schema, $table->name, '%' ) }) {
515         COL_INFO: while (my $info = try { $sth->fetchrow_hashref } catch { +{} }) {
516             next COL_INFO unless %$info;
517
518             my $column_info = {};
519             $column_info->{data_type}     = lc $info->{TYPE_NAME};
520
521             my $size = $info->{COLUMN_SIZE};
522
523             if (defined $size && defined $info->{DECIMAL_DIGITS}) {
524                 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
525             }
526             elsif (defined $size) {
527                 $column_info->{size} = $size;
528             }
529
530             $column_info->{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
531             $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
532             my $col_name = $info->{COLUMN_NAME};
533             $col_name =~ s/^\"(.*)\"$/$1/;
534
535             my $extra_info = $self->_extra_column_info(
536                 $table, $col_name, $column_info, $info
537             ) || {};
538             $column_info = { %$column_info, %$extra_info };
539
540             $result{$col_name} = $column_info;
541         }
542         $sth->finish;
543     }
544
545     my $sth = $self->_sth_for($table, undef, \'1 = 0');
546     $sth->execute;
547
548     my @columns = @{ $sth->{NAME} };
549
550     COL: for my $i (0 .. $#columns) {
551         next COL if %{ $result{ $columns[$i] }||{} };
552
553         my $column_info = {};
554         $column_info->{data_type} = lc $sth->{TYPE}[$i];
555
556         my $size = $sth->{PRECISION}[$i];
557
558         if (defined $size && defined $sth->{SCALE}[$i]) {
559             $column_info->{size} = [$size, $sth->{SCALE}[$i]];
560         }
561         elsif (defined $size) {
562             $column_info->{size} = $size;
563         }
564
565         $column_info->{is_nullable} = $sth->{NULLABLE}[$i] ? 1 : 0;
566
567         if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
568             $column_info->{data_type} = $1;
569             $column_info->{size}    = $2;
570         }
571
572         my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info, $sth) || {};
573         $column_info = { %$column_info, %$extra_info };
574
575         $result{ $columns[$i] } = $column_info;
576     }
577     $sth->finish;
578
579     foreach my $col (keys %result) {
580         my $colinfo = $result{$col};
581         my $type_num = $colinfo->{data_type};
582         my $type_name;
583         if (defined $type_num && $type_num =~ /^-?\d+\z/ && $dbh->can('type_info')) {
584             my $type_name = $self->_dbh_type_info_type_name($type_num);
585             $colinfo->{data_type} = lc $type_name if $type_name;
586         }
587     }
588
589     # check for instances of the same column name with different case in preserve_case=0 mode
590     if (not $self->preserve_case) {
591         my %lc_colnames;
592
593         foreach my $col (keys %result) {
594             push @{ $lc_colnames{lc $col} }, $col;
595         }
596
597         if (keys %lc_colnames != keys %result) {
598             my @offending_colnames = map @$_, grep @$_ > 1, values %lc_colnames;
599
600             my $offending_colnames = join ", ", map "'$_'", @offending_colnames;
601
602             croak "columns $offending_colnames in table @{[ $table->sql_name ]} collide in preserve_case=0 mode. preserve_case=1 mode required";
603         }
604
605         # apply lowercasing
606         my %lc_result;
607
608         while (my ($col, $info) = each %result) {
609             $lc_result{ $self->_lc($col) } = $info;
610         }
611
612         %result = %lc_result;
613     }
614
615     return \%result;
616 }
617
618 # Need to override this for the buggy Firebird ODBC driver.
619 sub _dbh_type_info_type_name {
620     my ($self, $type_num) = @_;
621
622     # We wrap it in a try block for MSSQL+DBD::Sybase, which can have issues.
623     # TODO investigate further
624     my $type_info = try { $self->dbh->type_info($type_num) };
625
626     return $type_info ? $type_info->{TYPE_NAME} : undef;
627 }
628
629 # do not use this, override _columns_info_for instead
630 sub _extra_column_info {}
631
632 # override to mask warnings if needed
633 sub _dbh_table_info {
634     my ($self, $dbh, $table) = (shift, shift, shift);
635
636     return undef if !$dbh->can('table_info');
637     my $sth = $dbh->table_info(undef, $table->schema, $table->name);
638     while (my $info = $sth->fetchrow_hashref) {
639         next if !$self->_table_info_matches($table, $info);
640         return $info;
641     }
642     return undef;
643 }
644
645 sub _table_info_matches {
646     my ($self, $table, $info) = @_;
647
648     no warnings 'uninitialized';
649     return $info->{TABLE_SCHEM} eq $table->schema
650         && $info->{TABLE_NAME}  eq $table->name;
651 }
652
653 # override to mask warnings if needed (see mysql)
654 sub _dbh_column_info {
655     my ($self, $dbh) = (shift, shift);
656
657     return $dbh->column_info(@_);
658 }
659
660 # If a coderef uses DBI->connect, this should get its connect info.
661 sub _try_infer_connect_info_from_coderef {
662     my ($self, $code) = @_;
663
664     my ($dsn, $user, $pass, $params);
665
666     no warnings 'redefine';
667
668     local *DBI::connect = sub {
669         (undef, $dsn, $user, $pass, $params) = @_;
670     };
671
672     $code->();
673
674     return ($dsn, $user, $pass, $params);
675 }
676
677 sub dbh {
678     my $self = shift;
679
680     return $self->schema->storage->dbh;
681 }
682
683 sub _table_is_view {
684     my ($self, $table) = @_;
685
686     my $info = $self->_dbh_table_info($self->dbh, $table)
687         or return 0;
688     return $info->{TABLE_TYPE} eq 'VIEW';
689 }
690
691 =head1 SEE ALSO
692
693 L<DBIx::Class::Schema::Loader>
694
695 =head1 AUTHOR
696
697 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
698
699 =head1 LICENSE
700
701 This library is free software; you can redistribute it and/or modify it under
702 the same terms as Perl itself.
703
704 =cut
705
706 1;
707 # vim:et sts=4 sw=4 tw=0: