release 0.07022
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI.pm
CommitLineData
996be9ee 1package DBIx::Class::Schema::Loader::DBI;
2
3use strict;
4use warnings;
abaf2c66 5use base qw/DBIx::Class::Schema::Loader::Base/;
942bd5e0 6use mro 'c3';
61d1cca1 7use Try::Tiny;
c4a69b87 8use List::MoreUtils 'any';
116431d6 9use Carp::Clan qw/^DBIx::Class/;
61d1cca1 10use namespace::clean;
c4a69b87 11use DBIx::Class::Schema::Loader::Table ();
996be9ee 12
7c2059da 13our $VERSION = '0.07022';
32f784fc 14
3b17d988 15__PACKAGE__->mk_group_accessors('simple', qw/
16 _disable_pk_detection
17 _disable_uniq_detection
18 _disable_fk_detection
19 _passwords
c4a69b87 20 quote_char
21 name_sep
3b17d988 22/);
23
996be9ee 24=head1 NAME
25
26DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
27
28=head1 SYNOPSIS
29
30See L<DBIx::Class::Schema::Loader::Base>
31
32=head1 DESCRIPTION
33
34This is the base class for L<DBIx::Class::Schema::Loader::Base> classes for
35DBI-based storage backends, and implements the common functionality between them.
36
37See L<DBIx::Class::Schema::Loader::Base> for the available options.
38
39=head1 METHODS
40
41=head2 new
42
43Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
44things.
45
46=cut
47
48sub new {
49 my $self = shift->next::method(@_);
50
71a6e88a 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) {
c4a69b87 54 my $driver = $self->dbh->{Driver}->{Name};
71a6e88a 55
56 my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
383bd2a8 57 if ((not $self->isa($subclass)) && $self->load_optional_class($subclass)) {
58 bless $self, $subclass;
71a6e88a 59 $self->_rebless;
383bd2a8 60 Class::C3::reinitialize() if $] < 5.009005;
71a6e88a 61 }
996be9ee 62 }
63
64 # Set up the default quoting character and name seperators
c4a69b87 65 $self->quote_char($self->_build_quote_char);
66 $self->name_sep($self->_build_name_sep);
996be9ee 67
68 $self->_setup;
69
383bd2a8 70 return $self;
996be9ee 71}
72
c4a69b87 73sub _build_quote_char {
77d3753e 74 my $self = shift;
c4a69b87 75
76 my $quote_char = $self->dbh->get_info(29)
77d3753e 77 || $self->schema->storage->sql_maker->quote_char
78 || q{"};
c4a69b87 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;
77d3753e 87}
88
c4a69b87 89sub _build_name_sep {
77d3753e 90 my $self = shift;
c4a69b87 91 return $self->dbh->get_info(41)
77d3753e 92 || $self->schema->storage->sql_maker->name_sep
c4a69b87 93 || '.';
77d3753e 94}
95
996be9ee 96# Override this in vendor modules to do things at the end of ->new()
97sub _setup { }
98
6ae3f335 99# Override this in vendor module to load a subclass if necessary
100sub _rebless { }
101
c4a69b87 102sub _system_schemas {
103 return ('information_schema');
104}
105
106sub _system_tables {
107 return ();
108}
109
110sub _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
119sub _supports_db_schema { 1 }
120
121# Returns an array of table objects
996be9ee 122sub _tables_list {
bfb43060 123 my ($self, $opts) = (shift, shift);
996be9ee 124
c4a69b87 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;
e57fd726 168
c4a69b87 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 }
77d3753e 175
c4a69b87 176 next TABLE if $matches;
177 }
178
179 $schema_name ||= $schema;
385c593b 180
c4a69b87 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 );
c5ff1f26 189
c4a69b87 190 push @tables, $table;
191 }
385c593b 192 }
996be9ee 193
bfb43060 194 return $self->_filter_tables(\@tables, $opts);
075aff97 195}
196
bfb43060 197# apply constraint/exclude and ignore bad tables and views
075aff97 198sub _filter_tables {
bfb43060 199 my ($self, $tables, $opts) = @_;
075aff97 200
bfb43060 201 my @tables = @$tables;
075aff97 202 my @filtered_tables;
203
bfb43060 204 $opts ||= {};
205 my $constraint = $opts->{constraint};
206 my $exclude = $opts->{exclude};
207
2db2c898 208 @tables = grep { /$constraint/ } @tables if defined $constraint;
209 @tables = grep { ! /$exclude/ } @tables if defined $exclude;
bfb43060 210
c4a69b87 211 TABLE: for my $table (@tables) {
61d1cca1 212 try {
afcd3c32 213 local $^W = 0; # for ADO
805dbe0a 214 my $sth = $self->_sth_for($table, undef, \'1 = 0');
215 $sth->execute;
c4a69b87 216 1;
075aff97 217 }
61d1cca1 218 catch {
219 warn "Bad table or view '$table', ignoring: $_\n";
c4a69b87 220 0;
221 } or next TABLE;
61d1cca1 222
223 push @filtered_tables, $table;
075aff97 224 }
225
226 return @filtered_tables;
996be9ee 227}
228
12af3806 229=head2 load
230
231We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
232
233=cut
234
235sub load {
236 my $self = shift;
237
c4a69b87 238 local $self->dbh->{RaiseError} = 1;
239 local $self->dbh->{PrintError} = 0;
12b86f07 240
c4a69b87 241 $self->next::method(@_);
996be9ee 242
c4a69b87 243 $self->schema->storage->disconnect unless $self->dynamic;
075aff97 244}
245
246sub _sth_for {
247 my ($self, $table, $fields, $where) = @_;
248
c4a69b87 249 my $sth = $self->dbh->prepare($self->schema->storage->sql_maker
250 ->select(\$table->sql_name, $fields, $where));
075aff97 251
252 return $sth;
253}
254
255# Returns an arrayref of column names
256sub _table_columns {
257 my ($self, $table) = @_;
258
259 my $sth = $self->_sth_for($table, undef, \'1 = 0');
996be9ee 260 $sth->execute;
1af21646 261
262 my $retval = [ map $self->_lc($_), @{$sth->{NAME}} ];
263
3b7f80f9 264 $sth->finish;
265
1af21646 266 return $retval;
996be9ee 267}
268
269# Returns arrayref of pk col names
270sub _table_pk_info {
fd589700 271 my ($self, $table) = @_;
996be9ee 272
3b17d988 273 return [] if $self->_disable_pk_detection;
274
3b17d988 275 my @primary = try {
c4a69b87 276 $self->dbh->primary_key('', $table->schema, $table->name);
3b17d988 277 }
278 catch {
279 warn "Cannot find primary keys for this driver: $_";
280 $self->_disable_pk_detection(1);
281 return ();
282 };
283
284 return [] if not @primary;
285
286 @primary = map { $self->_lc($_) } @primary;
c4a69b87 287 s/[\Q$self->{quote_char}\E]//g for @primary;
996be9ee 288
289 return \@primary;
290}
291
fd589700 292# Override this for vendor-specific uniq info
996be9ee 293sub _table_uniq_info {
fd589700 294 my ($self, $table) = @_;
295
3b17d988 296 return [] if $self->_disable_uniq_detection;
297
c4a69b87 298 if (not $self->dbh->can('statistics_info')) {
3b17d988 299 warn "No UNIQUE constraint information can be gathered for this driver";
300 $self->_disable_uniq_detection(1);
fd589700 301 return [];
302 }
303
304 my %indices;
c4a69b87 305 my $sth = $self->dbh->statistics_info(undef, $table->schema, $table->name, 1, 1);
fd589700 306 while(my $row = $sth->fetchrow_hashref) {
307 # skip table-level stats, conditional indexes, and any index missing
308 # critical fields
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};
314
3b17d988 315 $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME});
fd589700 316 }
3b7f80f9 317 $sth->finish;
fd589700 318
319 my @retval;
320 foreach my $index_name (keys %indices) {
321 my $index = $indices{$index_name};
3b17d988 322 push(@retval, [ $index_name => [ @$index[1..$#$index] ] ]);
fd589700 323 }
324
325 return \@retval;
996be9ee 326}
327
c4a69b87 328sub _table_comment {
329 my ($self, $table) = @_;
7732645c 330 my $dbh = $self->dbh;
5c06aa08 331
b21abfca 332 my $comments_table = $table->clone;
333 $comments_table->name($self->table_comments_table);
5c06aa08 334
07307014 335 my ($comment) =
336 (exists $self->_tables->{$comments_table->sql_name} || undef)
337 && try { $dbh->selectrow_array(<<"EOF") };
c4a69b87 338SELECT comment_text
b21abfca 339FROM @{[ $comments_table->sql_name ]}
7732645c 340WHERE table_name = @{[ $dbh->quote($table->name) ]}
c4a69b87 341EOF
5c06aa08 342
5ffed88c 343 # Failback: try the REMARKS column on table_info
5ffed88c 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};
348 }
349
c4a69b87 350 return $comment;
5c06aa08 351}
352
353sub _column_comment {
b21abfca 354 my ($self, $table, $column_number, $column_name) = @_;
7732645c 355 my $dbh = $self->dbh;
c4a69b87 356
b21abfca 357 my $comments_table = $table->clone;
358 $comments_table->name($self->column_comments_table);
c4a69b87 359
07307014 360 my ($comment) =
361 (exists $self->_tables->{$comments_table->sql_name} || undef)
362 && try { $dbh->selectrow_array(<<"EOF") };
c4a69b87 363SELECT comment_text
b21abfca 364FROM @{[ $comments_table->sql_name ]}
7732645c 365WHERE table_name = @{[ $dbh->quote($table->name) ]}
366AND column_name = @{[ $dbh->quote($column_name) ]}
c4a69b87 367EOF
5ffed88c 368
369 # Failback: try the REMARKS column on column_info
5ffed88c 370 if (!$comment && $dbh->can('column_info')) {
1af21646 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};
374 }
5ffed88c 375 }
376
c4a69b87 377 return $comment;
5c06aa08 378}
379
996be9ee 380# Find relationships
381sub _table_fk_info {
382 my ($self, $table) = @_;
383
3b17d988 384 return [] if $self->_disable_fk_detection;
385
3b17d988 386 my $sth = try {
c4a69b87 387 $self->dbh->foreign_key_info( '', '', '',
388 '', ($table->schema || ''), $table->name );
3b17d988 389 }
390 catch {
391 warn "Cannot introspect relationships for this driver: $_";
392 $self->_disable_fk_detection(1);
393 return undef;
394 };
395
996be9ee 396 return [] if !$sth;
397
398 my %rels;
399
400 my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
c4a69b87 401 REL: while(my $raw_rel = $sth->fetchrow_arrayref) {
402 my $uk_scm = $raw_rel->[1];
996be9ee 403 my $uk_tbl = $raw_rel->[2];
c930f78b 404 my $uk_col = $self->_lc($raw_rel->[3]);
c4a69b87 405 my $fk_scm = $raw_rel->[5];
c930f78b 406 my $fk_col = $self->_lc($raw_rel->[7]);
996be9ee 407 my $relid = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
c4a69b87 408
409 foreach my $var ($uk_scm, $uk_tbl, $uk_col, $fk_scm, $fk_col, $relid) {
ba9954e0 410 $var =~ s/[\Q$self->{quote_char}\E]//g if defined $var;
c4a69b87 411 }
412
413 if ($self->db_schema && $self->db_schema->[0] ne '%'
414 && (not any { $_ eq $uk_scm } @{ $self->db_schema })) {
415
416 next REL;
417 }
418
419 $rels{$relid}{tbl} = DBIx::Class::Schema::Loader::Table->new(
420 loader => $self,
421 name => $uk_tbl,
422 schema => $uk_scm,
423 ($self->_supports_db_schema ? () : (
424 ignore_schema => 1
425 )),
426 );
427 $rels{$relid}{cols}{$uk_col} = $fk_col;
996be9ee 428 }
3b7f80f9 429 $sth->finish;
996be9ee 430
431 my @rels;
432 foreach my $relid (keys %rels) {
433 push(@rels, {
434 remote_columns => [ keys %{$rels{$relid}->{cols}} ],
435 local_columns => [ values %{$rels{$relid}->{cols}} ],
436 remote_table => $rels{$relid}->{tbl},
437 });
438 }
439
440 return \@rels;
441}
442
12af3806 443# ported in from DBIx::Class::Storage::DBI:
444sub _columns_info_for {
445 my ($self, $table) = @_;
446
447 my $dbh = $self->schema->storage->dbh;
448
61d1cca1 449 my %result;
450
1af21646 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;
454
61d1cca1 455 my $column_info = {};
456 $column_info->{data_type} = lc $info->{TYPE_NAME};
457
458 my $size = $info->{COLUMN_SIZE};
459
460 if (defined $size && defined $info->{DECIMAL_DIGITS}) {
461 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
12af3806 462 }
61d1cca1 463 elsif (defined $size) {
464 $column_info->{size} = $size;
465 }
466
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/;
471
61d1cca1 472 my $extra_info = $self->_extra_column_info(
473 $table, $col_name, $column_info, $info
474 ) || {};
475 $column_info = { %$column_info, %$extra_info };
476
477 $result{$col_name} = $column_info;
478 }
479 $sth->finish;
12af3806 480 }
481
075aff97 482 my $sth = $self->_sth_for($table, undef, \'1 = 0');
12af3806 483 $sth->execute;
61d1cca1 484
ed18888f 485 my @columns = @{ $sth->{NAME} };
61d1cca1 486
1af21646 487 COL: for my $i (0 .. $#columns) {
22f91663 488 next COL if %{ $result{ $columns[$i] }||{} };
1af21646 489
23d1f36b 490 my $column_info = {};
57a9fc92 491 $column_info->{data_type} = lc $sth->{TYPE}[$i];
26334ec1 492
493 my $size = $sth->{PRECISION}[$i];
494
495 if (defined $size && defined $sth->{SCALE}[$i]) {
496 $column_info->{size} = [$size, $sth->{SCALE}[$i]];
497 }
498 elsif (defined $size) {
499 $column_info->{size} = $size;
500 }
501
57a9fc92 502 $column_info->{is_nullable} = $sth->{NULLABLE}[$i] ? 1 : 0;
23d1f36b 503
504 if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
505 $column_info->{data_type} = $1;
506 $column_info->{size} = $2;
12af3806 507 }
508
698c11d8 509 my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info, $sth) || {};
23d1f36b 510 $column_info = { %$column_info, %$extra_info };
511
116431d6 512 $result{ $columns[$i] } = $column_info;
12af3806 513 }
6ce0bcc3 514 $sth->finish;
515
516 foreach my $col (keys %result) {
517 my $colinfo = $result{$col};
518 my $type_num = $colinfo->{data_type};
519 my $type_name;
afcd3c32 520 if (defined $type_num && $type_num =~ /^-?\d+\z/ && $dbh->can('type_info')) {
5111e5d0 521 my $type_name = $self->_dbh_type_info_type_name($type_num);
cf0ba25b 522 $colinfo->{data_type} = lc $type_name if $type_name;
6ce0bcc3 523 }
524 }
12af3806 525
116431d6 526 # check for instances of the same column name with different case in preserve_case=0 mode
527 if (not $self->preserve_case) {
528 my %lc_colnames;
529
530 foreach my $col (keys %result) {
531 push @{ $lc_colnames{lc $col} }, $col;
532 }
533
534 if (keys %lc_colnames != keys %result) {
535 my @offending_colnames = map @$_, grep @$_ > 1, values %lc_colnames;
536
537 my $offending_colnames = join ", ", map "'$_'", @offending_colnames;
538
539 croak "columns $offending_colnames in table @{[ $table->sql_name ]} collide in preserve_case=0 mode. preserve_case=1 mode required";
540 }
541
542 # apply lowercasing
543 my %lc_result;
544
545 while (my ($col, $info) = each %result) {
546 $lc_result{ $self->_lc($col) } = $info;
547 }
548
549 %result = %lc_result;
550 }
551
12af3806 552 return \%result;
553}
554
23024b3f 555# Need to override this for the buggy Firebird ODBC driver.
5111e5d0 556sub _dbh_type_info_type_name {
23024b3f 557 my ($self, $type_num) = @_;
558
354b6942 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) };
5111e5d0 562
563 return $type_info ? $type_info->{TYPE_NAME} : undef;
23024b3f 564}
565
db9c411a 566# do not use this, override _columns_info_for instead
a8df0345 567sub _extra_column_info {}
c5baf131 568
5ffed88c 569# override to mask warnings if needed
570sub _dbh_table_info {
571 my ($self, $dbh) = (shift, shift);
572
573 return $dbh->table_info(@_);
574}
575
db9c411a 576# override to mask warnings if needed (see mysql)
577sub _dbh_column_info {
578 my ($self, $dbh) = (shift, shift);
579
580 return $dbh->column_info(@_);
581}
582
3b17d988 583# If a coderef uses DBI->connect, this should get its connect info.
584sub _try_infer_connect_info_from_coderef {
585 my ($self, $code) = @_;
586
587 my ($dsn, $user, $pass, $params);
588
589 no warnings 'redefine';
590
591 local *DBI::connect = sub {
592 (undef, $dsn, $user, $pass, $params) = @_;
593 };
594
595 $code->();
596
597 return ($dsn, $user, $pass, $params);
598}
599
c4a69b87 600sub dbh {
601 my $self = shift;
602
603 return $self->schema->storage->dbh;
604}
605
996be9ee 606=head1 SEE ALSO
607
608L<DBIx::Class::Schema::Loader>
609
be80bba7 610=head1 AUTHOR
611
9cc8e7e1 612See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 613
614=head1 LICENSE
615
616This library is free software; you can redistribute it and/or modify it under
617the same terms as Perl itself.
618
996be9ee 619=cut
620
6211;
26334ec1 622# vim:et sts=4 sw=4 tw=0: