1 package DBIx::Class::Schema::Loader::DBI;
5 use base qw/DBIx::Class::Schema::Loader::Base/;
9 use Carp::Clan qw/^DBIx::Class/;
11 use DBIx::Class::Schema::Loader::Table ();
13 our $VERSION = '0.07048_01';
15 __PACKAGE__->mk_group_accessors('simple', qw/
17 _disable_uniq_detection
26 DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
30 See L<DBIx::Class::Schema::Loader::Base>
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.
37 See L<DBIx::Class::Schema::Loader::Base> for the available options.
43 Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
49 my $self = shift->next::method(@_);
51 # rebless to vendor-specific class if it exists and loads and we're not in a
53 if (not $self->loader_class) {
54 my $driver = $self->dbh->{Driver}->{Name};
56 my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
57 if ((not $self->isa($subclass)) && $self->load_optional_class($subclass)) {
58 bless $self, $subclass;
60 Class::C3::reinitialize() if $] < 5.009005;
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);
73 sub _build_quote_char {
76 my $quote_char = $self->dbh->get_info(29)
77 || $self->schema->storage->sql_maker->quote_char
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;
91 return $self->dbh->get_info(41)
92 || $self->schema->storage->sql_maker->name_sep
96 # Override this in vendor modules to do things at the end of ->new()
99 # Override this in vendor module to load a subclass if necessary
102 sub _system_schemas {
103 return ('information_schema');
113 return $self->dbh->tables(undef, @_);
116 # default to be overridden in subclasses if necessary
117 sub _supports_db_schema { 1 }
119 # Returns an array of table objects
125 my $qt = qr/[\Q$self->{quote_char}\E"'`\[\]]/;
126 my $nqt = qr/[^\Q$self->{quote_char}\E"'`\[\]]/;
127 my $ns = qr/[\Q$self->{name_sep}\E]/;
128 my $nns = qr/[^\Q$self->{name_sep}\E]/;
130 foreach my $schema (@{ $self->db_schema || [undef] }) {
131 my @raw_table_names = $self->_dbh_tables($schema);
133 TABLE: foreach my $raw_table_name (@raw_table_names) {
134 my $quoted = $raw_table_name =~ /^$qt/;
136 # These regexes are not entirely correct, but hopefully they will work
137 # in most cases. RT reports welcome.
138 my ($schema_name, $table_name1, $table_name2) = $quoted ?
139 $raw_table_name =~ /^(?:${qt}(${nqt}+?)${qt}${ns})?(?:${qt}(.+?)${qt}|(${nns}+))\z/
141 $raw_table_name =~ /^(?:(${nns}+?)${ns})?(?:${qt}(.+?)${qt}|(${nns}+))\z/;
143 my $table_name = $table_name1 || $table_name2;
145 foreach my $system_schema ($self->_system_schemas) {
149 if (ref $system_schema) {
151 if $schema_name =~ $system_schema
152 && $schema !~ $system_schema;
156 if $schema_name eq $system_schema
157 && $schema ne $system_schema;
160 next TABLE if $matches;
164 foreach my $system_table ($self->_system_tables) {
167 if (ref $system_table) {
168 $matches = 1 if $table_name =~ $system_table;
171 $matches = 1 if $table_name eq $system_table
174 next TABLE if $matches;
177 $schema_name ||= $schema;
179 my $table = DBIx::Class::Schema::Loader::Table->new(
182 schema => $schema_name,
183 ($self->_supports_db_schema ? () : (
188 push @tables, $table;
192 return $self->_filter_tables(\@tables);
195 sub _recurse_constraint {
196 my ($constraint, @parts) = @_;
198 my $name = shift @parts;
200 # If there are any parts left, the constraint must be an arrayref
201 croak "depth of constraint/exclude array does not match length of moniker_parts"
202 unless !!@parts == !!(ref $constraint eq 'ARRAY');
204 # if ths is the last part, use the constraint directly
205 return $name =~ $constraint unless @parts;
207 # recurse into the first matching subconstraint
208 foreach (@{$constraint}) {
209 my ($re, $sub) = @{$_};
210 return _recurse_constraint($sub, @parts)
216 sub _check_constraint {
217 my ($include, $constraint, @tables) = @_;
219 return @tables unless defined $constraint;
221 return grep { !$include xor _recurse_constraint($constraint, @{$_}) } @tables
222 if ref $constraint eq 'ARRAY';
224 return grep { !$include xor /$constraint/ } @tables;
229 # apply constraint/exclude and ignore bad tables and views
231 my ($self, $tables) = @_;
233 my @tables = @$tables;
236 @tables = _check_constraint(1, $self->constraint, @tables);
237 @tables = _check_constraint(0, $self->exclude, @tables);
239 TABLE: for my $table (@tables) {
241 local $^W = 0; # for ADO
242 my $sth = $self->_sth_for($table, undef, \'1 = 0');
247 warn "Bad table or view '$table', ignoring: $_\n";
251 push @filtered_tables, $table;
254 return @filtered_tables;
259 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
266 local $self->dbh->{RaiseError} = 1;
267 local $self->dbh->{PrintError} = 0;
269 $self->next::method(@_);
273 my ($self, $table, $fields, $where) = @_;
275 my $sth = $self->dbh->prepare($self->schema->storage->sql_maker
276 ->select(\$table->sql_name, $fields || \'*', $where));
281 # Returns an arrayref of column names
283 my ($self, $table) = @_;
285 my $sth = $self->_sth_for($table, undef, \'1 = 0');
288 my $retval = [ map $self->_lc($_), @{$sth->{NAME}} ];
295 # Returns arrayref of pk col names
297 my ($self, $table) = @_;
299 return [] if $self->_disable_pk_detection;
302 $self->dbh->primary_key('', $table->schema, $table->name);
305 warn "Cannot find primary keys for this driver: $_";
306 $self->_disable_pk_detection(1);
310 return [] if not @primary;
312 @primary = map { $self->_lc($_) } @primary;
313 s/[\Q$self->{quote_char}\E]//g for @primary;
318 # Override this for vendor-specific uniq info
319 sub _table_uniq_info {
320 my ($self, $table) = @_;
322 return [] if $self->_disable_uniq_detection;
324 if (not $self->dbh->can('statistics_info')) {
325 warn "No UNIQUE constraint information can be gathered for this driver";
326 $self->_disable_uniq_detection(1);
331 my $sth = $self->dbh->statistics_info(undef, $table->schema, $table->name, 1, 1);
332 while(my $row = $sth->fetchrow_hashref) {
333 # skip table-level stats, conditional indexes, and any index missing
335 next if $row->{TYPE} eq 'table'
336 || defined $row->{FILTER_CONDITION}
337 || !$row->{INDEX_NAME}
338 || !defined $row->{ORDINAL_POSITION};
340 $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME} || '');
345 foreach my $index_name (sort keys %indices) {
346 my (undef, @cols) = @{$indices{$index_name}};
347 # skip indexes with missing column names (e.g. expression indexes)
348 next unless @cols == grep $_, @cols;
349 push(@retval, [ $index_name => \@cols ]);
356 my ($self, $table) = @_;
357 my $dbh = $self->dbh;
359 my $comments_table = $table->clone;
360 $comments_table->name($self->table_comments_table);
363 (exists $self->_tables->{$comments_table->sql_name} || undef)
364 && try { $dbh->selectrow_array(<<"EOF") };
366 FROM @{[ $comments_table->sql_name ]}
367 WHERE table_name = @{[ $dbh->quote($table->name) ]}
370 # Failback: try the REMARKS column on table_info
372 my $info = $self->_dbh_table_info( $dbh, $table );
373 $comment = $info->{REMARKS} if $info;
379 sub _column_comment {
380 my ($self, $table, $column_number, $column_name) = @_;
381 my $dbh = $self->dbh;
383 my $comments_table = $table->clone;
384 $comments_table->name($self->column_comments_table);
387 (exists $self->_tables->{$comments_table->sql_name} || undef)
388 && try { $dbh->selectrow_array(<<"EOF") };
390 FROM @{[ $comments_table->sql_name ]}
391 WHERE table_name = @{[ $dbh->quote($table->name) ]}
392 AND column_name = @{[ $dbh->quote($column_name) ]}
395 # Failback: try the REMARKS column on column_info
396 if (!$comment && $dbh->can('column_info')) {
397 if (my $sth = try { $self->_dbh_column_info( $dbh, undef, $table->schema, $table->name, $column_name ) }) {
398 my $info = $sth->fetchrow_hashref();
399 $comment = $info->{REMARKS};
408 my ($self, $table) = @_;
410 return [] if $self->_disable_fk_detection;
413 $self->dbh->foreign_key_info( '', '', '',
414 '', ($table->schema || ''), $table->name );
417 warn "Cannot introspect relationships for this driver: $_";
418 $self->_disable_fk_detection(1);
434 my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
435 REL: while(my $raw_rel = $sth->fetchrow_arrayref) {
436 my $uk_scm = $raw_rel->[1];
437 my $uk_tbl = $raw_rel->[2];
438 my $uk_col = $self->_lc($raw_rel->[3]);
439 my $fk_scm = $raw_rel->[5];
440 my $fk_col = $self->_lc($raw_rel->[7]);
441 my $key_seq = $raw_rel->[8] - 1;
442 my $relid = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
444 my $update_rule = $raw_rel->[9];
445 my $delete_rule = $raw_rel->[10];
447 $update_rule = $rules[$update_rule] if defined $update_rule;
448 $delete_rule = $rules[$delete_rule] if defined $delete_rule;
450 my $is_deferrable = $raw_rel->[13];
452 ($is_deferrable = $is_deferrable == 7 ? 0 : 1)
453 if defined $is_deferrable;
455 foreach my $var ($uk_scm, $uk_tbl, $uk_col, $fk_scm, $fk_col, $relid) {
456 $var =~ s/[\Q$self->{quote_char}\E]//g if defined $var;
459 if ($self->db_schema && $self->db_schema->[0] ne '%'
460 && (not any { $_ eq $uk_scm } @{ $self->db_schema })) {
465 $rels{$relid}{tbl} ||= DBIx::Class::Schema::Loader::Table->new(
469 ($self->_supports_db_schema ? () : (
474 $rels{$relid}{attrs}{on_delete} = $delete_rule if $delete_rule;
475 $rels{$relid}{attrs}{on_update} = $update_rule if $update_rule;
476 $rels{$relid}{attrs}{is_deferrable} = $is_deferrable if defined $is_deferrable;
478 # Add this data IN ORDER
479 $rels{$relid}{rcols}[$key_seq] = $uk_col;
480 $rels{$relid}{lcols}[$key_seq] = $fk_col;
485 foreach my $relid (keys %rels) {
487 remote_columns => [ grep defined, @{ $rels{$relid}{rcols} } ],
488 local_columns => [ grep defined, @{ $rels{$relid}{lcols} } ],
489 remote_table => $rels{$relid}->{tbl},
490 (exists $rels{$relid}{attrs} ?
491 (attrs => $rels{$relid}{attrs})
495 _constraint_name => $relid,
502 # ported in from DBIx::Class::Storage::DBI:
503 sub _columns_info_for {
504 my ($self, $table) = @_;
506 my $dbh = $self->schema->storage->dbh;
511 if (my $sth = try { $self->_dbh_column_info($dbh, undef, $table->schema, $table->name, '%' ) }) {
512 COL_INFO: while (my $info = try { $sth->fetchrow_hashref } catch { +{} }) {
513 next COL_INFO unless %$info;
515 my $column_info = {};
516 $column_info->{data_type} = lc $info->{TYPE_NAME};
518 my $size = $info->{COLUMN_SIZE};
520 if (defined $size && defined $info->{DECIMAL_DIGITS}) {
521 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
523 elsif (defined $size) {
524 $column_info->{size} = $size;
527 $column_info->{is_nullable} = $info->{NULLABLE} ? 1 : 0;
528 $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
529 my $col_name = $info->{COLUMN_NAME};
530 $col_name =~ s/^\"(.*)\"$/$1/;
532 my $extra_info = $self->_extra_column_info(
533 $table, $col_name, $column_info, $info
535 $column_info = { %$column_info, %$extra_info };
537 $raw_result{$col_name} = $info;
538 $result{$col_name} = $column_info;
543 my $sth = $self->_sth_for($table, undef, \'1 = 0');
546 my @columns = @{ $sth->{NAME} };
548 COL: for my $i (0 .. $#columns) {
549 next COL if %{ $result{ $columns[$i] }||{} };
551 my $column_info = {};
552 $column_info->{data_type} = lc $sth->{TYPE}[$i];
554 my $size = $sth->{PRECISION}[$i];
556 if (defined $size && defined $sth->{SCALE}[$i]) {
557 $column_info->{size} = [$size, $sth->{SCALE}[$i]];
559 elsif (defined $size) {
560 $column_info->{size} = $size;
563 $column_info->{is_nullable} = $sth->{NULLABLE}[$i] ? 1 : 0;
565 if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
566 $column_info->{data_type} = $1;
567 $column_info->{size} = $2;
570 my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info, $sth) || {};
571 $column_info = { %$column_info, %$extra_info };
573 $result{ $columns[$i] } = $column_info;
577 foreach my $col (keys %result) {
578 my $colinfo = $result{$col};
579 my $type_num = $colinfo->{data_type};
581 if (defined $type_num && $type_num =~ /^-?\d+\z/ && $dbh->can('type_info')) {
582 my $type_name = $self->_dbh_type_info_type_name($type_num);
583 $colinfo->{data_type} = lc $type_name if $type_name;
587 # check for instances of the same column name with different case in preserve_case=0 mode
588 if (not $self->preserve_case) {
591 foreach my $col (keys %result) {
592 push @{ $lc_colnames{lc $col} }, $col;
595 if (keys %lc_colnames != keys %result) {
596 my @offending_colnames = map @$_, grep @$_ > 1, values %lc_colnames;
598 my $offending_colnames = join ", ", map "'$_'", @offending_colnames;
600 croak "columns $offending_colnames in table @{[ $table->sql_name ]} collide in preserve_case=0 mode. preserve_case=1 mode required";
606 while (my ($col, $info) = each %result) {
607 $lc_result{ $self->_lc($col) } = $info;
610 %result = %lc_result;
613 return wantarray ? (\%result, \%raw_result) : \%result;
616 # Need to override this for the buggy Firebird ODBC driver.
617 sub _dbh_type_info_type_name {
618 my ($self, $type_num) = @_;
620 # We wrap it in a try block for MSSQL+DBD::Sybase, which can have issues.
621 # TODO investigate further
622 my $type_info = try { $self->dbh->type_info($type_num) };
624 return $type_info ? $type_info->{TYPE_NAME} : undef;
627 # do not use this, override _columns_info_for instead
628 sub _extra_column_info {}
630 # override to mask warnings if needed
631 sub _dbh_table_info {
632 my ($self, $dbh, $table) = (shift, shift, shift);
634 return undef if !$dbh->can('table_info');
635 my $sth = $dbh->table_info(undef, $table->schema, $table->name);
636 while (my $info = $sth->fetchrow_hashref) {
637 next if !$self->_table_info_matches($table, $info);
643 sub _table_info_matches {
644 my ($self, $table, $info) = @_;
646 no warnings 'uninitialized';
647 return $info->{TABLE_SCHEM} eq $table->schema
648 && $info->{TABLE_NAME} eq $table->name;
651 # override to mask warnings if needed (see mysql)
652 sub _dbh_column_info {
653 my ($self, $dbh) = (shift, shift);
655 return $dbh->column_info(@_);
658 # If a coderef uses DBI->connect, this should get its connect info.
659 sub _try_infer_connect_info_from_coderef {
660 my ($self, $code) = @_;
662 my ($dsn, $user, $pass, $params);
664 no warnings 'redefine';
666 local *DBI::connect = sub {
667 (undef, $dsn, $user, $pass, $params) = @_;
672 return ($dsn, $user, $pass, $params);
678 return $self->schema->storage->dbh;
682 my ($self, $table) = @_;
684 my $info = $self->_dbh_table_info($self->dbh, $table)
686 return $info->{TABLE_TYPE} eq 'VIEW';
691 L<DBIx::Class::Schema::Loader>
695 See L<DBIx::Class::Schema::Loader/AUTHORS>.
699 This library is free software; you can redistribute it and/or modify it under
700 the same terms as Perl itself.
705 # vim:et sts=4 sw=4 tw=0: