1 package DBIx::Class::Schema::Loader::DBI;
5 use base qw/DBIx::Class::Schema::Loader::Base/;
8 use List::MoreUtils 'any';
9 use Carp::Clan qw/^DBIx::Class/;
11 use DBIx::Class::Schema::Loader::Table ();
13 our $VERSION = '0.07022';
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 seperators
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');
111 my ($self, $schema) = (shift, shift);
113 my ($table_pattern, $table_type_pattern) = @_ ? @_ : ('%', '%');
115 return $self->dbh->tables(undef, $schema, $table_pattern, $table_type_pattern);
118 # default to be overridden in subclasses if necessary
119 sub _supports_db_schema { 1 }
121 # Returns an array of table objects
123 my ($self, $opts) = (shift, shift);
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]/;
132 foreach my $schema (@{ $self->db_schema || [undef] }) {
133 my @raw_table_names = $self->_dbh_tables($schema, @_);
135 TABLE: foreach my $raw_table_name (@raw_table_names) {
136 my $quoted = $raw_table_name =~ /^$qt/;
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/
143 $raw_table_name =~ /^(?:(${nns}+?)${ns})?(?:${qt}(.+?)${qt}|(${nns}+))\z/;
145 my $table_name = $table_name1 || $table_name2;
147 foreach my $system_schema ($self->_system_schemas) {
151 if (ref $system_schema) {
153 if $schema_name =~ $system_schema
154 && $schema !~ $system_schema;
158 if $schema_name eq $system_schema
159 && $schema ne $system_schema;
162 next TABLE if $matches;
166 foreach my $system_table ($self->_system_tables) {
169 if (ref $system_table) {
170 $matches = 1 if $table_name =~ $system_table;
173 $matches = 1 if $table_name eq $system_table
176 next TABLE if $matches;
179 $schema_name ||= $schema;
181 my $table = DBIx::Class::Schema::Loader::Table->new(
184 schema => $schema_name,
185 ($self->_supports_db_schema ? () : (
190 push @tables, $table;
194 return $self->_filter_tables(\@tables, $opts);
197 # apply constraint/exclude and ignore bad tables and views
199 my ($self, $tables, $opts) = @_;
201 my @tables = @$tables;
205 my $constraint = $opts->{constraint};
206 my $exclude = $opts->{exclude};
208 @tables = grep { /$constraint/ } @tables if defined $constraint;
209 @tables = grep { ! /$exclude/ } @tables if defined $exclude;
211 TABLE: for my $table (@tables) {
213 local $^W = 0; # for ADO
214 my $sth = $self->_sth_for($table, undef, \'1 = 0');
219 warn "Bad table or view '$table', ignoring: $_\n";
223 push @filtered_tables, $table;
226 return @filtered_tables;
231 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
238 local $self->dbh->{RaiseError} = 1;
239 local $self->dbh->{PrintError} = 0;
241 $self->next::method(@_);
243 $self->schema->storage->disconnect unless $self->dynamic;
247 my ($self, $table, $fields, $where) = @_;
249 my $sth = $self->dbh->prepare($self->schema->storage->sql_maker
250 ->select(\$table->sql_name, $fields, $where));
255 # Returns an arrayref of column names
257 my ($self, $table) = @_;
259 my $sth = $self->_sth_for($table, undef, \'1 = 0');
262 my $retval = [ map $self->_lc($_), @{$sth->{NAME}} ];
269 # Returns arrayref of pk col names
271 my ($self, $table) = @_;
273 return [] if $self->_disable_pk_detection;
276 $self->dbh->primary_key('', $table->schema, $table->name);
279 warn "Cannot find primary keys for this driver: $_";
280 $self->_disable_pk_detection(1);
284 return [] if not @primary;
286 @primary = map { $self->_lc($_) } @primary;
287 s/[\Q$self->{quote_char}\E]//g for @primary;
292 # Override this for vendor-specific uniq info
293 sub _table_uniq_info {
294 my ($self, $table) = @_;
296 return [] if $self->_disable_uniq_detection;
298 if (not $self->dbh->can('statistics_info')) {
299 warn "No UNIQUE constraint information can be gathered for this driver";
300 $self->_disable_uniq_detection(1);
305 my $sth = $self->dbh->statistics_info(undef, $table->schema, $table->name, 1, 1);
306 while(my $row = $sth->fetchrow_hashref) {
307 # skip table-level stats, conditional indexes, and any index missing
309 next if $row->{TYPE} eq 'table'
310 || defined $row->{FILTER_CONDITION}
311 || !$row->{INDEX_NAME}
312 || !defined $row->{ORDINAL_POSITION}
313 || !$row->{COLUMN_NAME};
315 $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME});
320 foreach my $index_name (keys %indices) {
321 my $index = $indices{$index_name};
322 push(@retval, [ $index_name => [ @$index[1..$#$index] ] ]);
329 my ($self, $table) = @_;
330 my $dbh = $self->dbh;
332 my $comments_table = $table->clone;
333 $comments_table->name($self->table_comments_table);
336 (exists $self->_tables->{$comments_table->sql_name} || undef)
337 && try { $dbh->selectrow_array(<<"EOF") };
339 FROM @{[ $comments_table->sql_name ]}
340 WHERE table_name = @{[ $dbh->quote($table->name) ]}
343 # Failback: try the REMARKS column on table_info
344 if (!$comment && $dbh->can('table_info')) {
345 my $sth = $self->_dbh_table_info( $dbh, undef, $table->schema, $table->name );
346 my $info = $sth->fetchrow_hashref();
347 $comment = $info->{REMARKS};
353 sub _column_comment {
354 my ($self, $table, $column_number, $column_name) = @_;
355 my $dbh = $self->dbh;
357 my $comments_table = $table->clone;
358 $comments_table->name($self->column_comments_table);
361 (exists $self->_tables->{$comments_table->sql_name} || undef)
362 && try { $dbh->selectrow_array(<<"EOF") };
364 FROM @{[ $comments_table->sql_name ]}
365 WHERE table_name = @{[ $dbh->quote($table->name) ]}
366 AND column_name = @{[ $dbh->quote($column_name) ]}
369 # Failback: try the REMARKS column on column_info
370 if (!$comment && $dbh->can('column_info')) {
371 if (my $sth = try { $self->_dbh_column_info( $dbh, undef, $table->schema, $table->name, $column_name ) }) {
372 my $info = $sth->fetchrow_hashref();
373 $comment = $info->{REMARKS};
382 my ($self, $table) = @_;
384 return [] if $self->_disable_fk_detection;
387 $self->dbh->foreign_key_info( '', '', '',
388 '', ($table->schema || ''), $table->name );
391 warn "Cannot introspect relationships for this driver: $_";
392 $self->_disable_fk_detection(1);
400 my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
401 REL: while(my $raw_rel = $sth->fetchrow_arrayref) {
402 my $uk_scm = $raw_rel->[1];
403 my $uk_tbl = $raw_rel->[2];
404 my $uk_col = $self->_lc($raw_rel->[3]);
405 my $fk_scm = $raw_rel->[5];
406 my $fk_col = $self->_lc($raw_rel->[7]);
407 my $relid = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
409 foreach my $var ($uk_scm, $uk_tbl, $uk_col, $fk_scm, $fk_col, $relid) {
410 $var =~ s/[\Q$self->{quote_char}\E]//g if defined $var;
413 if ($self->db_schema && $self->db_schema->[0] ne '%'
414 && (not any { $_ eq $uk_scm } @{ $self->db_schema })) {
419 $rels{$relid}{tbl} = DBIx::Class::Schema::Loader::Table->new(
423 ($self->_supports_db_schema ? () : (
427 $rels{$relid}{cols}{$uk_col} = $fk_col;
432 foreach my $relid (keys %rels) {
434 remote_columns => [ keys %{$rels{$relid}->{cols}} ],
435 local_columns => [ values %{$rels{$relid}->{cols}} ],
436 remote_table => $rels{$relid}->{tbl},
443 # ported in from DBIx::Class::Storage::DBI:
444 sub _columns_info_for {
445 my ($self, $table) = @_;
447 my $dbh = $self->schema->storage->dbh;
451 if (my $sth = try { $self->_dbh_column_info($dbh, undef, $table->schema, $table->name, '%' ) }) {
452 COL_INFO: while (my $info = try { $sth->fetchrow_hashref } catch { +{} }) {
453 next COL_INFO unless %$info;
455 my $column_info = {};
456 $column_info->{data_type} = lc $info->{TYPE_NAME};
458 my $size = $info->{COLUMN_SIZE};
460 if (defined $size && defined $info->{DECIMAL_DIGITS}) {
461 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
463 elsif (defined $size) {
464 $column_info->{size} = $size;
467 $column_info->{is_nullable} = $info->{NULLABLE} ? 1 : 0;
468 $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
469 my $col_name = $info->{COLUMN_NAME};
470 $col_name =~ s/^\"(.*)\"$/$1/;
472 my $extra_info = $self->_extra_column_info(
473 $table, $col_name, $column_info, $info
475 $column_info = { %$column_info, %$extra_info };
477 $result{$col_name} = $column_info;
482 my $sth = $self->_sth_for($table, undef, \'1 = 0');
485 my @columns = @{ $sth->{NAME} };
487 COL: for my $i (0 .. $#columns) {
488 next COL if %{ $result{ $columns[$i] }||{} };
490 my $column_info = {};
491 $column_info->{data_type} = lc $sth->{TYPE}[$i];
493 my $size = $sth->{PRECISION}[$i];
495 if (defined $size && defined $sth->{SCALE}[$i]) {
496 $column_info->{size} = [$size, $sth->{SCALE}[$i]];
498 elsif (defined $size) {
499 $column_info->{size} = $size;
502 $column_info->{is_nullable} = $sth->{NULLABLE}[$i] ? 1 : 0;
504 if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
505 $column_info->{data_type} = $1;
506 $column_info->{size} = $2;
509 my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info, $sth) || {};
510 $column_info = { %$column_info, %$extra_info };
512 $result{ $columns[$i] } = $column_info;
516 foreach my $col (keys %result) {
517 my $colinfo = $result{$col};
518 my $type_num = $colinfo->{data_type};
520 if (defined $type_num && $type_num =~ /^-?\d+\z/ && $dbh->can('type_info')) {
521 my $type_name = $self->_dbh_type_info_type_name($type_num);
522 $colinfo->{data_type} = lc $type_name if $type_name;
526 # check for instances of the same column name with different case in preserve_case=0 mode
527 if (not $self->preserve_case) {
530 foreach my $col (keys %result) {
531 push @{ $lc_colnames{lc $col} }, $col;
534 if (keys %lc_colnames != keys %result) {
535 my @offending_colnames = map @$_, grep @$_ > 1, values %lc_colnames;
537 my $offending_colnames = join ", ", map "'$_'", @offending_colnames;
539 croak "columns $offending_colnames in table @{[ $table->sql_name ]} collide in preserve_case=0 mode. preserve_case=1 mode required";
545 while (my ($col, $info) = each %result) {
546 $lc_result{ $self->_lc($col) } = $info;
549 %result = %lc_result;
555 # Need to override this for the buggy Firebird ODBC driver.
556 sub _dbh_type_info_type_name {
557 my ($self, $type_num) = @_;
559 # We wrap it in a try block for MSSQL+DBD::Sybase, which can have issues.
560 # TODO investigate further
561 my $type_info = try { $self->dbh->type_info($type_num) };
563 return $type_info ? $type_info->{TYPE_NAME} : undef;
566 # do not use this, override _columns_info_for instead
567 sub _extra_column_info {}
569 # override to mask warnings if needed
570 sub _dbh_table_info {
571 my ($self, $dbh) = (shift, shift);
573 return $dbh->table_info(@_);
576 # override to mask warnings if needed (see mysql)
577 sub _dbh_column_info {
578 my ($self, $dbh) = (shift, shift);
580 return $dbh->column_info(@_);
583 # If a coderef uses DBI->connect, this should get its connect info.
584 sub _try_infer_connect_info_from_coderef {
585 my ($self, $code) = @_;
587 my ($dsn, $user, $pass, $params);
589 no warnings 'redefine';
591 local *DBI::connect = sub {
592 (undef, $dsn, $user, $pass, $params) = @_;
597 return ($dsn, $user, $pass, $params);
603 return $self->schema->storage->dbh;
608 L<DBIx::Class::Schema::Loader>
612 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
616 This library is free software; you can redistribute it and/or modify it under
617 the same terms as Perl itself.
622 # vim:et sts=4 sw=4 tw=0: