release 0.07010
[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';
fa994d3c 7use Carp::Clan qw/^DBIx::Class/;
61d1cca1 8use Try::Tiny;
9use namespace::clean;
996be9ee 10
4295c4b4 11our $VERSION = '0.07010';
32f784fc 12
3b17d988 13__PACKAGE__->mk_group_accessors('simple', qw/
14 _disable_pk_detection
15 _disable_uniq_detection
16 _disable_fk_detection
17 _passwords
18/);
19
996be9ee 20=head1 NAME
21
22DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
23
24=head1 SYNOPSIS
25
26See L<DBIx::Class::Schema::Loader::Base>
27
28=head1 DESCRIPTION
29
30This is the base class for L<DBIx::Class::Schema::Loader::Base> classes for
31DBI-based storage backends, and implements the common functionality between them.
32
33See L<DBIx::Class::Schema::Loader::Base> for the available options.
34
35=head1 METHODS
36
37=head2 new
38
39Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
40things.
41
42=cut
43
44sub new {
45 my $self = shift->next::method(@_);
46
71a6e88a 47 # rebless to vendor-specific class if it exists and loads and we're not in a
48 # custom class.
49 if (not $self->loader_class) {
50 my $dbh = $self->schema->storage->dbh;
51 my $driver = $dbh->{Driver}->{Name};
52
53 my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
54 if ($self->load_optional_class($subclass)) {
55 bless $self, $subclass unless $self->isa($subclass);
56 $self->_rebless;
57 }
996be9ee 58 }
59
60 # Set up the default quoting character and name seperators
243c6ebc 61 $self->{_quoter} = $self->_build_quoter;
77d3753e 62 $self->{_namesep} = $self->_build_namesep;
243c6ebc 63
996be9ee 64 # For our usage as regex matches, concatenating multiple quoter
65 # values works fine (e.g. s/\Q<>\E// if quoter was [ '<', '>' ])
66 if( ref $self->{_quoter} eq 'ARRAY') {
67 $self->{_quoter} = join(q{}, @{$self->{_quoter}});
68 }
69
70 $self->_setup;
71
72 $self;
73}
74
77d3753e 75sub _build_quoter {
76 my $self = shift;
77 my $dbh = $self->schema->storage->dbh;
78 return $dbh->get_info(29)
79 || $self->schema->storage->sql_maker->quote_char
80 || q{"};
81}
82
83sub _build_namesep {
84 my $self = shift;
85 my $dbh = $self->schema->storage->dbh;
86 return $dbh->get_info(41)
87 || $self->schema->storage->sql_maker->name_sep
88 || q{.};
89}
90
996be9ee 91# Override this in vendor modules to do things at the end of ->new()
92sub _setup { }
93
6ae3f335 94# Override this in vendor module to load a subclass if necessary
95sub _rebless { }
96
996be9ee 97# Returns an array of table names
98sub _tables_list {
bfb43060 99 my ($self, $opts) = (shift, shift);
996be9ee 100
e57fd726 101 my ($table, $type) = @_ ? @_ : ('%', '%');
102
996be9ee 103 my $dbh = $self->schema->storage->dbh;
e57fd726 104 my @tables = $dbh->tables(undef, $self->db_schema, $table, $type);
77d3753e 105
c5ff1f26 106 my $qt = qr/[\Q$self->{_quoter}\E"'`\[\]]/;
385c593b 107
c5ff1f26 108 my $all_tables_quoted = (grep /$qt/, @tables) == @tables;
109
110 if ($self->{_quoter} && $all_tables_quoted) {
385c593b 111 s/.* $qt (?= .* $qt)//xg for @tables;
112 } else {
113 s/^.*\Q$self->{_namesep}\E// for @tables;
114 }
115 s/$qt//g for @tables;
996be9ee 116
bfb43060 117 return $self->_filter_tables(\@tables, $opts);
075aff97 118}
119
bfb43060 120# apply constraint/exclude and ignore bad tables and views
075aff97 121sub _filter_tables {
bfb43060 122 my ($self, $tables, $opts) = @_;
075aff97 123
bfb43060 124 my @tables = @$tables;
075aff97 125 my @filtered_tables;
126
bfb43060 127 $opts ||= {};
128 my $constraint = $opts->{constraint};
129 my $exclude = $opts->{exclude};
130
131 @tables = grep { /$constraint/ } @$tables if defined $constraint;
132 @tables = grep { ! /$exclude/ } @$tables if defined $exclude;
133
b48f3f80 134 LOOP: for my $table (@tables) {
61d1cca1 135 try {
afcd3c32 136 local $^W = 0; # for ADO
805dbe0a 137 my $sth = $self->_sth_for($table, undef, \'1 = 0');
138 $sth->execute;
075aff97 139 }
61d1cca1 140 catch {
141 warn "Bad table or view '$table', ignoring: $_\n";
0c1d5b47 142 $self->_unregister_source_for_table($table);
b48f3f80 143 no warnings 'exiting';
144 next LOOP;
61d1cca1 145 };
146
147 push @filtered_tables, $table;
075aff97 148 }
149
150 return @filtered_tables;
996be9ee 151}
152
12af3806 153=head2 load
154
155We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
156
157=cut
158
159sub load {
160 my $self = shift;
161
162 local $self->schema->storage->dbh->{RaiseError} = 1;
163 local $self->schema->storage->dbh->{PrintError} = 0;
164 $self->next::method(@_);
165}
166
075aff97 167sub _table_as_sql {
996be9ee 168 my ($self, $table) = @_;
169
996be9ee 170 if($self->{db_schema}) {
385c593b 171 $table = $self->{db_schema} . $self->{_namesep} .
172 $self->_quote_table_name($table);
173 } else {
174 $table = $self->_quote_table_name($table);
996be9ee 175 }
176
075aff97 177 return $table;
178}
179
180sub _sth_for {
181 my ($self, $table, $fields, $where) = @_;
182
183 my $dbh = $self->schema->storage->dbh;
184
185 my $sth = $dbh->prepare($self->schema->storage->sql_maker
186 ->select(\$self->_table_as_sql($table), $fields, $where));
187
188 return $sth;
189}
190
191# Returns an arrayref of column names
192sub _table_columns {
193 my ($self, $table) = @_;
194
195 my $sth = $self->_sth_for($table, undef, \'1 = 0');
996be9ee 196 $sth->execute;
bc1cb85e 197 my $retval = $self->preserve_case ? \@{$sth->{NAME}} : \@{$sth->{NAME_lc}};
3b7f80f9 198 $sth->finish;
199
200 $retval;
996be9ee 201}
202
203# Returns arrayref of pk col names
204sub _table_pk_info {
fd589700 205 my ($self, $table) = @_;
996be9ee 206
3b17d988 207 return [] if $self->_disable_pk_detection;
208
996be9ee 209 my $dbh = $self->schema->storage->dbh;
210
3b17d988 211 my @primary = try {
212 $dbh->primary_key('', $self->db_schema, $table);
213 }
214 catch {
215 warn "Cannot find primary keys for this driver: $_";
216 $self->_disable_pk_detection(1);
217 return ();
218 };
219
220 return [] if not @primary;
221
222 @primary = map { $self->_lc($_) } @primary;
996be9ee 223 s/\Q$self->{_quoter}\E//g for @primary;
224
225 return \@primary;
226}
227
fd589700 228# Override this for vendor-specific uniq info
996be9ee 229sub _table_uniq_info {
fd589700 230 my ($self, $table) = @_;
231
3b17d988 232 return [] if $self->_disable_uniq_detection;
233
fd589700 234 my $dbh = $self->schema->storage->dbh;
3b17d988 235
236 if (not $dbh->can('statistics_info')) {
237 warn "No UNIQUE constraint information can be gathered for this driver";
238 $self->_disable_uniq_detection(1);
fd589700 239 return [];
240 }
241
242 my %indices;
243 my $sth = $dbh->statistics_info(undef, $self->db_schema, $table, 1, 1);
244 while(my $row = $sth->fetchrow_hashref) {
245 # skip table-level stats, conditional indexes, and any index missing
246 # critical fields
247 next if $row->{TYPE} eq 'table'
248 || defined $row->{FILTER_CONDITION}
249 || !$row->{INDEX_NAME}
250 || !defined $row->{ORDINAL_POSITION}
251 || !$row->{COLUMN_NAME};
252
3b17d988 253 $indices{$row->{INDEX_NAME}}[$row->{ORDINAL_POSITION}] = $self->_lc($row->{COLUMN_NAME});
fd589700 254 }
3b7f80f9 255 $sth->finish;
fd589700 256
257 my @retval;
258 foreach my $index_name (keys %indices) {
259 my $index = $indices{$index_name};
3b17d988 260 push(@retval, [ $index_name => [ @$index[1..$#$index] ] ]);
fd589700 261 }
262
263 return \@retval;
996be9ee 264}
265
266# Find relationships
267sub _table_fk_info {
268 my ($self, $table) = @_;
269
3b17d988 270 return [] if $self->_disable_fk_detection;
271
996be9ee 272 my $dbh = $self->schema->storage->dbh;
3b17d988 273 my $sth = try {
274 $dbh->foreign_key_info( '', $self->db_schema, '',
275 '', $self->db_schema, $table );
276 }
277 catch {
278 warn "Cannot introspect relationships for this driver: $_";
279 $self->_disable_fk_detection(1);
280 return undef;
281 };
282
996be9ee 283 return [] if !$sth;
284
285 my %rels;
286
287 my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
288 while(my $raw_rel = $sth->fetchrow_arrayref) {
289 my $uk_tbl = $raw_rel->[2];
c930f78b 290 my $uk_col = $self->_lc($raw_rel->[3]);
291 my $fk_col = $self->_lc($raw_rel->[7]);
996be9ee 292 my $relid = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
293 $uk_tbl =~ s/\Q$self->{_quoter}\E//g;
294 $uk_col =~ s/\Q$self->{_quoter}\E//g;
295 $fk_col =~ s/\Q$self->{_quoter}\E//g;
296 $relid =~ s/\Q$self->{_quoter}\E//g;
297 $rels{$relid}->{tbl} = $uk_tbl;
c930f78b 298 $rels{$relid}->{cols}{$uk_col} = $fk_col;
996be9ee 299 }
3b7f80f9 300 $sth->finish;
996be9ee 301
302 my @rels;
303 foreach my $relid (keys %rels) {
304 push(@rels, {
305 remote_columns => [ keys %{$rels{$relid}->{cols}} ],
306 local_columns => [ values %{$rels{$relid}->{cols}} ],
307 remote_table => $rels{$relid}->{tbl},
308 });
309 }
310
311 return \@rels;
312}
313
12af3806 314# ported in from DBIx::Class::Storage::DBI:
315sub _columns_info_for {
316 my ($self, $table) = @_;
317
318 my $dbh = $self->schema->storage->dbh;
319
61d1cca1 320 my %result;
321
12af3806 322 if ($dbh->can('column_info')) {
61d1cca1 323 my $sth = $self->_dbh_column_info($dbh, undef, $self->db_schema, $table, '%' );
324 while ( my $info = $sth->fetchrow_hashref() ){
325 my $column_info = {};
326 $column_info->{data_type} = lc $info->{TYPE_NAME};
327
328 my $size = $info->{COLUMN_SIZE};
329
330 if (defined $size && defined $info->{DECIMAL_DIGITS}) {
331 $column_info->{size} = [$size, $info->{DECIMAL_DIGITS}];
12af3806 332 }
61d1cca1 333 elsif (defined $size) {
334 $column_info->{size} = $size;
335 }
336
337 $column_info->{is_nullable} = $info->{NULLABLE} ? 1 : 0;
338 $column_info->{default_value} = $info->{COLUMN_DEF} if defined $info->{COLUMN_DEF};
339 my $col_name = $info->{COLUMN_NAME};
340 $col_name =~ s/^\"(.*)\"$/$1/;
341
342 $col_name = $self->_lc($col_name);
c38ec663 343
61d1cca1 344 my $extra_info = $self->_extra_column_info(
345 $table, $col_name, $column_info, $info
346 ) || {};
347 $column_info = { %$column_info, %$extra_info };
348
349 $result{$col_name} = $column_info;
350 }
351 $sth->finish;
352
353 return \%result if %result;
12af3806 354 }
355
075aff97 356 my $sth = $self->_sth_for($table, undef, \'1 = 0');
12af3806 357 $sth->execute;
61d1cca1 358
ed18888f 359 my @columns = @{ $sth->{NAME} };
61d1cca1 360
361 for my $i (0 .. $#columns) {
23d1f36b 362 my $column_info = {};
57a9fc92 363 $column_info->{data_type} = lc $sth->{TYPE}[$i];
26334ec1 364
365 my $size = $sth->{PRECISION}[$i];
366
367 if (defined $size && defined $sth->{SCALE}[$i]) {
368 $column_info->{size} = [$size, $sth->{SCALE}[$i]];
369 }
370 elsif (defined $size) {
371 $column_info->{size} = $size;
372 }
373
57a9fc92 374 $column_info->{is_nullable} = $sth->{NULLABLE}[$i] ? 1 : 0;
23d1f36b 375
376 if ($column_info->{data_type} =~ m/^(.*?)\((.*?)\)$/) {
377 $column_info->{data_type} = $1;
378 $column_info->{size} = $2;
12af3806 379 }
380
45be2ce7 381 my $extra_info = $self->_extra_column_info($table, $columns[$i], $column_info) || {};
23d1f36b 382 $column_info = { %$column_info, %$extra_info };
383
61d1cca1 384 $result{ $self->_lc($columns[$i]) } = $column_info;
12af3806 385 }
6ce0bcc3 386 $sth->finish;
387
388 foreach my $col (keys %result) {
389 my $colinfo = $result{$col};
390 my $type_num = $colinfo->{data_type};
391 my $type_name;
afcd3c32 392 if (defined $type_num && $type_num =~ /^-?\d+\z/ && $dbh->can('type_info')) {
6ce0bcc3 393 my $type_info = $dbh->type_info($type_num);
394 $type_name = $type_info->{TYPE_NAME} if $type_info;
cf0ba25b 395 $colinfo->{data_type} = lc $type_name if $type_name;
6ce0bcc3 396 }
397 }
12af3806 398
399 return \%result;
400}
401
db9c411a 402# do not use this, override _columns_info_for instead
a8df0345 403sub _extra_column_info {}
c5baf131 404
db9c411a 405# override to mask warnings if needed (see mysql)
406sub _dbh_column_info {
407 my ($self, $dbh) = (shift, shift);
408
409 return $dbh->column_info(@_);
410}
411
3b17d988 412# If a coderef uses DBI->connect, this should get its connect info.
413sub _try_infer_connect_info_from_coderef {
414 my ($self, $code) = @_;
415
416 my ($dsn, $user, $pass, $params);
417
418 no warnings 'redefine';
419
420 local *DBI::connect = sub {
421 (undef, $dsn, $user, $pass, $params) = @_;
422 };
423
424 $code->();
425
426 return ($dsn, $user, $pass, $params);
427}
428
996be9ee 429=head1 SEE ALSO
430
431L<DBIx::Class::Schema::Loader>
432
be80bba7 433=head1 AUTHOR
434
9cc8e7e1 435See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
be80bba7 436
437=head1 LICENSE
438
439This library is free software; you can redistribute it and/or modify it under
440the same terms as Perl itself.
441
996be9ee 442=cut
443
4441;
26334ec1 445# vim:et sts=4 sw=4 tw=0: