1 package DBIx::Class::Schema::Loader::DBI;
5 use base qw/DBIx::Class::Schema::Loader::Base/;
8 use List::MoreUtils 'any';
10 use DBIx::Class::Schema::Loader::Table ();
12 our $VERSION = '0.07018';
14 __PACKAGE__->mk_group_accessors('simple', qw/
16 _disable_uniq_detection
25 DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
29 See L<DBIx::Class::Schema::Loader::Base>
33 This is the base class for L<DBIx::Class::Schema::Loader::Base> classes for
34 DBI-based storage backends, and implements the common functionality between them.
36 See L<DBIx::Class::Schema::Loader::Base> for the available options.
42 Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
48 my $self = shift->next::method(@_);
50 # rebless to vendor-specific class if it exists and loads and we're not in a
52 if (not $self->loader_class) {
53 my $driver = $self->dbh->{Driver}->{Name};
55 my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
56 if ($self->load_optional_class($subclass)) {
57 bless $self, $subclass unless $self->isa($subclass);
62 # Set up the default quoting character and name seperators
63 $self->quote_char($self->_build_quote_char);
64 $self->name_sep($self->_build_name_sep);
71 sub _build_quote_char {
74 my $quote_char = $self->dbh->get_info(29)
75 || $self->schema->storage->sql_maker->quote_char
78 # For our usage as regex matches, concatenating multiple quote_char
79 # values works fine (e.g. s/[\Q<>\E]// if quote_char was [ '<', '>' ])
80 if (ref $quote_char eq 'ARRAY') {
81 $quote_char = join '', @$quote_char;
89 return $self->dbh->get_info(41)
90 || $self->schema->storage->sql_maker->name_sep
94 # Override this in vendor modules to do things at the end of ->new()
97 # Override this in vendor module to load a subclass if necessary
100 sub _system_schemas {
101 return ('information_schema');
109 my ($self, $schema) = (shift, shift);
111 my ($table_pattern, $table_type_pattern) = @_ ? @_ : ('%', '%');
113 return $self->dbh->tables(undef, $schema, $table_pattern, $table_type_pattern);
116 # default to be overridden in subclasses if necessary
117 sub _supports_db_schema { 1 }
119 # Returns an array of table objects
121 my ($self, $opts) = (shift, shift);
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, $opts);
195 # apply constraint/exclude and ignore bad tables and views
197 my ($self, $tables, $opts) = @_;
199 my @tables = @$tables;
203 my $constraint = $opts->{constraint};
204 my $exclude = $opts->{exclude};
206 @tables = grep { /$constraint/ } @tables if defined $constraint;
207 @tables = grep { ! /$exclude/ } @tables if defined $exclude;
209 TABLE: for my $table (@tables) {
211 local $^W = 0; # for ADO
212 my $sth = $self->_sth_for($table, undef, \'1 = 0');
217 warn "Bad table or view '$table', ignoring: $_\n";
221 push @filtered_tables, $table;
224 return @filtered_tables;
229 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
236 local $self->dbh->{RaiseError} = 1;
237 local $self->dbh->{PrintError} = 0;
239 $self->next::method(@_);
241 $self->schema->storage->disconnect unless $self->dynamic;
245 my ($self, $table, $fields, $where) = @_;
247 my $sth = $self->dbh->prepare($self->schema->storage->sql_maker
248 ->select(\$table->sql_name, $fields, $where));
253 # Returns an arrayref of column names
255 my ($self, $table) = @_;
257 my $sth = $self->_sth_for($table, undef, \'1 = 0');
260 my $retval = [ map $self->_lc($_), @{$sth->{NAME}} ];
267 # Returns arrayref of pk col names
269 my ($self, $table) = @_;
271 return [] if $self->_disable_pk_detection;
274 $self->dbh->primary_key('', $table->schema, $table->name);
277 warn "Cannot find primary keys for this driver: $_";
278 $self->_disable_pk_detection(1);
282 return [] if not @primary;
284 @primary = map { $self->_lc($_) } @primary;
285 s/[\Q$self->{quote_char}\E]//g for @primary;
290 # Override this for vendor-specific uniq info
291 sub _table_uniq_info {
292 my ($self, $table) = @_;
294 return [] if $self->_disable_uniq_detection;
296 if (not $self->dbh->can('statistics_info')) {
297 warn "No UNIQUE constraint information can be gathered for this driver";
298 $self->_disable_uniq_detection(1);
303 my $sth = $self->dbh->statistics_info(undef, $table->schema, $table->name, 1, 1);
304 while(my $row = $sth->fetchrow_hashref) {
305 # skip table-level stats, conditional indexes, and any index missing
307 next if $row->{TYPE} eq 'table'
308 || defined $row->{FILTER_CONDITION}
309 || !$row->{INDEX_NAME}
310 || !defined $row->{ORDINAL_POSITION}
311 || !$row->{COLUMN_NAME};
313 $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME});
318 foreach my $index_name (keys %indices) {
319 my $index = $indices{$index_name};
320 push(@retval, [ $index_name => [ @$index[1..$#$index] ] ]);
327 my ($self, $table) = @_;
328 my $dbh = $self->dbh;
330 my $comments_table = $table->clone;
331 $comments_table->name($self->table_comments_table);
334 (exists $self->_tables->{$comments_table->sql_name} || undef)
335 && try { $dbh->selectrow_array(<<"EOF") };
337 FROM @{[ $comments_table->sql_name ]}
338 WHERE table_name = @{[ $dbh->quote($table->name) ]}
341 # Failback: try the REMARKS column on table_info
342 if (!$comment && $dbh->can('table_info')) {
343 my $sth = $self->_dbh_table_info( $dbh, undef, $table->schema, $table->name );
344 my $info = $sth->fetchrow_hashref();
345 $comment = $info->{REMARKS};
351 sub _column_comment {
352 my ($self, $table, $column_number, $column_name) = @_;
353 my $dbh = $self->dbh;
355 my $comments_table = $table->clone;
356 $comments_table->name($self->column_comments_table);
359 (exists $self->_tables->{$comments_table->sql_name} || undef)
360 && try { $dbh->selectrow_array(<<"EOF") };
362 FROM @{[ $comments_table->sql_name ]}
363 WHERE table_name = @{[ $dbh->quote($table->name) ]}
364 AND column_name = @{[ $dbh->quote($column_name) ]}
367 # Failback: try the REMARKS column on column_info
368 if (!$comment && $dbh->can('column_info')) {
369 if (my $sth = try { $self->_dbh_column_info( $dbh, undef, $table->schema, $table->name, $column_name ) }) {
370 my $info = $sth->fetchrow_hashref();
371 $comment = $info->{REMARKS};
380 my ($self, $table) = @_;
382 return [] if $self->_disable_fk_detection;
385 $self->dbh->foreign_key_info( '', '', '',
386 '', ($table->schema || ''), $table->name );
389 warn "Cannot introspect relationships for this driver: $_";
390 $self->_disable_fk_detection(1);
398 my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
399 REL: while(my $raw_rel = $sth->fetchrow_arrayref) {
400 my $uk_scm = $raw_rel->[1];
401 my $uk_tbl = $raw_rel->[2];
402 my $uk_col = $self->_lc($raw_rel->[3]);
403 my $fk_scm = $raw_rel->[5];
404 my $fk_col = $self->_lc($raw_rel->[7]);
405 my $relid = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
407 foreach my $var ($uk_scm, $uk_tbl, $uk_col, $fk_scm, $fk_col, $relid) {
408 $var =~ s/[\Q$self->{quote_char}\E]//g if defined $var;
411 if ($self->db_schema && $self->db_schema->[0] ne '%'
412 && (not any { $_ eq $uk_scm } @{ $self->db_schema })) {
417 $rels{$relid}{tbl} = DBIx::Class::Schema::Loader::Table->new(
421 ($self->_supports_db_schema ? () : (
425 $rels{$relid}{cols}{$uk_col} = $fk_col;
430 foreach my $relid (keys %rels) {
432 remote_columns => [ keys %{$rels{$relid}->{cols}} ],
433 local_columns => [ values %{$rels{$relid}->{cols}} ],
434 remote_table => $rels{$relid}->{tbl},
441 # ported in from DBIx::Class::Storage::DBI:
442 sub _columns_info_for {
443 my ($self, $table) = @_;
445 my $dbh = $self->schema->storage->dbh;
449 if (my $sth = try { $self->_dbh_column_info($dbh, undef, $table->schema, $table->name, '%' ) }) {
450 COL_INFO: while (my $info = try { $sth->fetchrow_hashref } catch { +{} }) {
451 next COL_INFO unless %$info;
453 my $column_info = {};
454 $column_info->{data_type} = lc $info->{TYPE_NAME};
456 my $size = $info->{COLUMN_SIZE};
458 if (defined $size && defined $info->{DECIMAL_DIGITS}) {
459 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
461 elsif (defined $size) {
462 $column_info->{size} = $size;
465 $column_info->{is_nullable} = $info->{NULLABLE} ? 1 : 0;
466 $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
467 my $col_name = $info->{COLUMN_NAME};
468 $col_name =~ s/^\"(.*)\"$/$1/;
470 $col_name = $self->_lc($col_name);
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{ $self->_lc($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{ $self->_lc($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;
529 # Need to override this for the buggy Firebird ODBC driver.
530 sub _dbh_type_info_type_name {
531 my ($self, $type_num) = @_;
533 # We wrap it in a try block for MSSQL+DBD::Sybase, which can have issues.
534 # TODO investigate further
535 my $type_info = try { $self->dbh->type_info($type_num) };
537 return $type_info ? $type_info->{TYPE_NAME} : undef;
540 # do not use this, override _columns_info_for instead
541 sub _extra_column_info {}
543 # override to mask warnings if needed
544 sub _dbh_table_info {
545 my ($self, $dbh) = (shift, shift);
547 return $dbh->table_info(@_);
550 # override to mask warnings if needed (see mysql)
551 sub _dbh_column_info {
552 my ($self, $dbh) = (shift, shift);
554 return $dbh->column_info(@_);
557 # If a coderef uses DBI->connect, this should get its connect info.
558 sub _try_infer_connect_info_from_coderef {
559 my ($self, $code) = @_;
561 my ($dsn, $user, $pass, $params);
563 no warnings 'redefine';
565 local *DBI::connect = sub {
566 (undef, $dsn, $user, $pass, $params) = @_;
571 return ($dsn, $user, $pass, $params);
577 return $self->schema->storage->dbh;
582 L<DBIx::Class::Schema::Loader>
586 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
590 This library is free software; you can redistribute it and/or modify it under
591 the same terms as Perl itself.
596 # vim:et sts=4 sw=4 tw=0: