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.07019';
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 ($self->load_optional_class($subclass)) {
58 bless $self, $subclass unless $self->isa($subclass);
63 # Set up the default quoting character and name seperators
64 $self->quote_char($self->_build_quote_char);
65 $self->name_sep($self->_build_name_sep);
72 sub _build_quote_char {
75 my $quote_char = $self->dbh->get_info(29)
76 || $self->schema->storage->sql_maker->quote_char
79 # For our usage as regex matches, concatenating multiple quote_char
80 # values works fine (e.g. s/[\Q<>\E]// if quote_char was [ '<', '>' ])
81 if (ref $quote_char eq 'ARRAY') {
82 $quote_char = join '', @$quote_char;
90 return $self->dbh->get_info(41)
91 || $self->schema->storage->sql_maker->name_sep
95 # Override this in vendor modules to do things at the end of ->new()
98 # Override this in vendor module to load a subclass if necessary
101 sub _system_schemas {
102 return ('information_schema');
110 my ($self, $schema) = (shift, shift);
112 my ($table_pattern, $table_type_pattern) = @_ ? @_ : ('%', '%');
114 return $self->dbh->tables(undef, $schema, $table_pattern, $table_type_pattern);
117 # default to be overridden in subclasses if necessary
118 sub _supports_db_schema { 1 }
120 # Returns an array of table objects
122 my ($self, $opts) = (shift, shift);
126 my $qt = qr/[\Q$self->{quote_char}\E"'`\[\]]/;
127 my $nqt = qr/[^\Q$self->{quote_char}\E"'`\[\]]/;
128 my $ns = qr/[\Q$self->{name_sep}\E]/;
129 my $nns = qr/[^\Q$self->{name_sep}\E]/;
131 foreach my $schema (@{ $self->db_schema || [undef] }) {
132 my @raw_table_names = $self->_dbh_tables($schema, @_);
134 TABLE: foreach my $raw_table_name (@raw_table_names) {
135 my $quoted = $raw_table_name =~ /^$qt/;
137 # These regexes are not entirely correct, but hopefully they will work
138 # in most cases. RT reports welcome.
139 my ($schema_name, $table_name1, $table_name2) = $quoted ?
140 $raw_table_name =~ /^(?:${qt}(${nqt}+?)${qt}${ns})?(?:${qt}(.+?)${qt}|(${nns}+))\z/
142 $raw_table_name =~ /^(?:(${nns}+?)${ns})?(?:${qt}(.+?)${qt}|(${nns}+))\z/;
144 my $table_name = $table_name1 || $table_name2;
146 foreach my $system_schema ($self->_system_schemas) {
150 if (ref $system_schema) {
152 if $schema_name =~ $system_schema
153 && $schema !~ $system_schema;
157 if $schema_name eq $system_schema
158 && $schema ne $system_schema;
161 next TABLE if $matches;
165 foreach my $system_table ($self->_system_tables) {
168 if (ref $system_table) {
169 $matches = 1 if $table_name =~ $system_table;
172 $matches = 1 if $table_name eq $system_table
175 next TABLE if $matches;
178 $schema_name ||= $schema;
180 my $table = DBIx::Class::Schema::Loader::Table->new(
183 schema => $schema_name,
184 ($self->_supports_db_schema ? () : (
189 push @tables, $table;
193 return $self->_filter_tables(\@tables, $opts);
196 # apply constraint/exclude and ignore bad tables and views
198 my ($self, $tables, $opts) = @_;
200 my @tables = @$tables;
204 my $constraint = $opts->{constraint};
205 my $exclude = $opts->{exclude};
207 @tables = grep { /$constraint/ } @tables if defined $constraint;
208 @tables = grep { ! /$exclude/ } @tables if defined $exclude;
210 TABLE: for my $table (@tables) {
212 local $^W = 0; # for ADO
213 my $sth = $self->_sth_for($table, undef, \'1 = 0');
218 warn "Bad table or view '$table', ignoring: $_\n";
222 push @filtered_tables, $table;
225 return @filtered_tables;
230 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
237 local $self->dbh->{RaiseError} = 1;
238 local $self->dbh->{PrintError} = 0;
240 $self->next::method(@_);
242 $self->schema->storage->disconnect unless $self->dynamic;
246 my ($self, $table, $fields, $where) = @_;
248 my $sth = $self->dbh->prepare($self->schema->storage->sql_maker
249 ->select(\$table->sql_name, $fields, $where));
254 # Returns an arrayref of column names
256 my ($self, $table) = @_;
258 my $sth = $self->_sth_for($table, undef, \'1 = 0');
261 my $retval = [ map $self->_lc($_), @{$sth->{NAME}} ];
268 # Returns arrayref of pk col names
270 my ($self, $table) = @_;
272 return [] if $self->_disable_pk_detection;
275 $self->dbh->primary_key('', $table->schema, $table->name);
278 warn "Cannot find primary keys for this driver: $_";
279 $self->_disable_pk_detection(1);
283 return [] if not @primary;
285 @primary = map { $self->_lc($_) } @primary;
286 s/[\Q$self->{quote_char}\E]//g for @primary;
291 # Override this for vendor-specific uniq info
292 sub _table_uniq_info {
293 my ($self, $table) = @_;
295 return [] if $self->_disable_uniq_detection;
297 if (not $self->dbh->can('statistics_info')) {
298 warn "No UNIQUE constraint information can be gathered for this driver";
299 $self->_disable_uniq_detection(1);
304 my $sth = $self->dbh->statistics_info(undef, $table->schema, $table->name, 1, 1);
305 while(my $row = $sth->fetchrow_hashref) {
306 # skip table-level stats, conditional indexes, and any index missing
308 next if $row->{TYPE} eq 'table'
309 || defined $row->{FILTER_CONDITION}
310 || !$row->{INDEX_NAME}
311 || !defined $row->{ORDINAL_POSITION}
312 || !$row->{COLUMN_NAME};
314 $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME});
319 foreach my $index_name (keys %indices) {
320 my $index = $indices{$index_name};
321 push(@retval, [ $index_name => [ @$index[1..$#$index] ] ]);
328 my ($self, $table) = @_;
329 my $dbh = $self->dbh;
331 my $comments_table = $table->clone;
332 $comments_table->name($self->table_comments_table);
335 (exists $self->_tables->{$comments_table->sql_name} || undef)
336 && try { $dbh->selectrow_array(<<"EOF") };
338 FROM @{[ $comments_table->sql_name ]}
339 WHERE table_name = @{[ $dbh->quote($table->name) ]}
342 # Failback: try the REMARKS column on table_info
343 if (!$comment && $dbh->can('table_info')) {
344 my $sth = $self->_dbh_table_info( $dbh, undef, $table->schema, $table->name );
345 my $info = $sth->fetchrow_hashref();
346 $comment = $info->{REMARKS};
352 sub _column_comment {
353 my ($self, $table, $column_number, $column_name) = @_;
354 my $dbh = $self->dbh;
356 my $comments_table = $table->clone;
357 $comments_table->name($self->column_comments_table);
360 (exists $self->_tables->{$comments_table->sql_name} || undef)
361 && try { $dbh->selectrow_array(<<"EOF") };
363 FROM @{[ $comments_table->sql_name ]}
364 WHERE table_name = @{[ $dbh->quote($table->name) ]}
365 AND column_name = @{[ $dbh->quote($column_name) ]}
368 # Failback: try the REMARKS column on column_info
369 if (!$comment && $dbh->can('column_info')) {
370 if (my $sth = try { $self->_dbh_column_info( $dbh, undef, $table->schema, $table->name, $column_name ) }) {
371 my $info = $sth->fetchrow_hashref();
372 $comment = $info->{REMARKS};
381 my ($self, $table) = @_;
383 return [] if $self->_disable_fk_detection;
386 $self->dbh->foreign_key_info( '', '', '',
387 '', ($table->schema || ''), $table->name );
390 warn "Cannot introspect relationships for this driver: $_";
391 $self->_disable_fk_detection(1);
399 my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
400 REL: while(my $raw_rel = $sth->fetchrow_arrayref) {
401 my $uk_scm = $raw_rel->[1];
402 my $uk_tbl = $raw_rel->[2];
403 my $uk_col = $self->_lc($raw_rel->[3]);
404 my $fk_scm = $raw_rel->[5];
405 my $fk_col = $self->_lc($raw_rel->[7]);
406 my $relid = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
408 foreach my $var ($uk_scm, $uk_tbl, $uk_col, $fk_scm, $fk_col, $relid) {
409 $var =~ s/[\Q$self->{quote_char}\E]//g if defined $var;
412 if ($self->db_schema && $self->db_schema->[0] ne '%'
413 && (not any { $_ eq $uk_scm } @{ $self->db_schema })) {
418 $rels{$relid}{tbl} = DBIx::Class::Schema::Loader::Table->new(
422 ($self->_supports_db_schema ? () : (
426 $rels{$relid}{cols}{$uk_col} = $fk_col;
431 foreach my $relid (keys %rels) {
433 remote_columns => [ keys %{$rels{$relid}->{cols}} ],
434 local_columns => [ values %{$rels{$relid}->{cols}} ],
435 remote_table => $rels{$relid}->{tbl},
442 # ported in from DBIx::Class::Storage::DBI:
443 sub _columns_info_for {
444 my ($self, $table) = @_;
446 my $dbh = $self->schema->storage->dbh;
450 if (my $sth = try { $self->_dbh_column_info($dbh, undef, $table->schema, $table->name, '%' ) }) {
451 COL_INFO: while (my $info = try { $sth->fetchrow_hashref } catch { +{} }) {
452 next COL_INFO unless %$info;
454 my $column_info = {};
455 $column_info->{data_type} = lc $info->{TYPE_NAME};
457 my $size = $info->{COLUMN_SIZE};
459 if (defined $size && defined $info->{DECIMAL_DIGITS}) {
460 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
462 elsif (defined $size) {
463 $column_info->{size} = $size;
466 $column_info->{is_nullable} = $info->{NULLABLE} ? 1 : 0;
467 $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
468 my $col_name = $info->{COLUMN_NAME};
469 $col_name =~ s/^\"(.*)\"$/$1/;
471 my $extra_info = $self->_extra_column_info(
472 $table, $col_name, $column_info, $info
474 $column_info = { %$column_info, %$extra_info };
476 $result{$col_name} = $column_info;
481 my $sth = $self->_sth_for($table, undef, \'1 = 0');
484 my @columns = @{ $sth->{NAME} };
486 COL: for my $i (0 .. $#columns) {
487 next COL if %{ $result{ $columns[$i] }||{} };
489 my $column_info = {};
490 $column_info->{data_type} = lc $sth->{TYPE}[$i];
492 my $size = $sth->{PRECISION}[$i];
494 if (defined $size && defined $sth->{SCALE}[$i]) {
495 $column_info->{size} = [$size, $sth->{SCALE}[$i]];
497 elsif (defined $size) {
498 $column_info->{size} = $size;
501 $column_info->{is_nullable} = $sth->{NULLABLE}[$i] ? 1 : 0;
503 if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
504 $column_info->{data_type} = $1;
505 $column_info->{size} = $2;
508 my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info, $sth) || {};
509 $column_info = { %$column_info, %$extra_info };
511 $result{ $columns[$i] } = $column_info;
515 foreach my $col (keys %result) {
516 my $colinfo = $result{$col};
517 my $type_num = $colinfo->{data_type};
519 if (defined $type_num && $type_num =~ /^-?\d+\z/ && $dbh->can('type_info')) {
520 my $type_name = $self->_dbh_type_info_type_name($type_num);
521 $colinfo->{data_type} = lc $type_name if $type_name;
525 # check for instances of the same column name with different case in preserve_case=0 mode
526 if (not $self->preserve_case) {
529 foreach my $col (keys %result) {
530 push @{ $lc_colnames{lc $col} }, $col;
533 if (keys %lc_colnames != keys %result) {
534 my @offending_colnames = map @$_, grep @$_ > 1, values %lc_colnames;
536 my $offending_colnames = join ", ", map "'$_'", @offending_colnames;
538 croak "columns $offending_colnames in table @{[ $table->sql_name ]} collide in preserve_case=0 mode. preserve_case=1 mode required";
544 while (my ($col, $info) = each %result) {
545 $lc_result{ $self->_lc($col) } = $info;
548 %result = %lc_result;
554 # Need to override this for the buggy Firebird ODBC driver.
555 sub _dbh_type_info_type_name {
556 my ($self, $type_num) = @_;
558 # We wrap it in a try block for MSSQL+DBD::Sybase, which can have issues.
559 # TODO investigate further
560 my $type_info = try { $self->dbh->type_info($type_num) };
562 return $type_info ? $type_info->{TYPE_NAME} : undef;
565 # do not use this, override _columns_info_for instead
566 sub _extra_column_info {}
568 # override to mask warnings if needed
569 sub _dbh_table_info {
570 my ($self, $dbh) = (shift, shift);
572 return $dbh->table_info(@_);
575 # override to mask warnings if needed (see mysql)
576 sub _dbh_column_info {
577 my ($self, $dbh) = (shift, shift);
579 return $dbh->column_info(@_);
582 # If a coderef uses DBI->connect, this should get its connect info.
583 sub _try_infer_connect_info_from_coderef {
584 my ($self, $code) = @_;
586 my ($dsn, $user, $pass, $params);
588 no warnings 'redefine';
590 local *DBI::connect = sub {
591 (undef, $dsn, $user, $pass, $params) = @_;
596 return ($dsn, $user, $pass, $params);
602 return $self->schema->storage->dbh;
607 L<DBIx::Class::Schema::Loader>
611 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
615 This library is free software; you can redistribute it and/or modify it under
616 the same terms as Perl itself.
621 # vim:et sts=4 sw=4 tw=0: