726599cd719fef8a7dc56190d20aed2ee6ee522b
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI.pm
1 package DBIx::Class::Schema::Loader::DBI;
2
3 use strict;
4 use warnings;
5 use base qw/DBIx::Class::Schema::Loader::Base/;
6 use Class::C3;
7 use Carp::Clan qw/^DBIx::Class/;
8
9 our $VERSION = '0.04999_13';
10
11 =head1 NAME
12
13 DBIx::Class::Schema::Loader::DBI - DBIx::Class::Schema::Loader DBI Implementation.
14
15 =head1 SYNOPSIS
16
17 See L<DBIx::Class::Schema::Loader::Base>
18
19 =head1 DESCRIPTION
20
21 This is the base class for L<DBIx::Class::Schema::Loader::Base> classes for
22 DBI-based storage backends, and implements the common functionality between them.
23
24 See L<DBIx::Class::Schema::Loader::Base> for the available options.
25
26 =head1 METHODS
27
28 =head2 new
29
30 Overlays L<DBIx::Class::Schema::Loader::Base/new> to do some DBI-specific
31 things.
32
33 =cut
34
35 sub new {
36     my $self = shift->next::method(@_);
37
38     # rebless to vendor-specific class if it exists and loads
39     my $dbh = $self->schema->storage->dbh;
40     my $driver = $dbh->{Driver}->{Name};
41
42     my $subclass = 'DBIx::Class::Schema::Loader::DBI::' . $driver;
43     if ($self->load_optional_class($subclass)) {
44         bless $self, $subclass unless $self->isa($subclass);
45         $self->_rebless;
46     }
47
48     # Set up the default quoting character and name seperators
49     $self->{_quoter} = $self->_build_quoter;
50     $self->{_namesep} = $self->_build_namesep;
51     # For our usage as regex matches, concatenating multiple quoter
52     # values works fine (e.g. s/\Q<>\E// if quoter was [ '<', '>' ])
53     if( ref $self->{_quoter} eq 'ARRAY') {
54         $self->{_quoter} = join(q{}, @{$self->{_quoter}});
55     }
56
57     $self->_setup;
58
59     $self;
60 }
61
62 sub _build_quoter {
63     my $self = shift;
64     my $dbh = $self->schema->storage->dbh;
65     return $dbh->get_info(29)
66            || $self->schema->storage->sql_maker->quote_char
67            || q{"};
68 }
69
70 sub _build_namesep {
71     my $self = shift;
72     my $dbh = $self->schema->storage->dbh;
73     return $dbh->get_info(41)
74            || $self->schema->storage->sql_maker->name_sep
75            || q{.};
76 }
77
78 # Override this in vendor modules to do things at the end of ->new()
79 sub _setup { }
80
81 # Override this in vendor module to load a subclass if necessary
82 sub _rebless { }
83
84 # Returns an array of table names
85 sub _tables_list { 
86     my $self = shift;
87
88     my ($table, $type) = @_ ? @_ : ('%', '%');
89
90     my $dbh = $self->schema->storage->dbh;
91     my @tables = $dbh->tables(undef, $self->db_schema, $table, $type);
92
93     my $qt = qr/\Q$self->{_quoter}\E/;
94
95     if ($self->{_quoter} && $tables[0] =~ /$qt/) {
96         s/.* $qt (?= .* $qt)//xg for @tables;
97     } else {
98         s/^.*\Q$self->{_namesep}\E// for @tables;
99     }
100     s/$qt//g for @tables;
101
102     return $self->_filter_tables(@tables);
103 }
104
105 # ignore bad tables and views
106 sub _filter_tables {
107     my ($self, @tables) = @_;
108
109     my @filtered_tables;
110
111     for my $table (@tables) {
112         eval {
113             my $sth = $self->_sth_for($table, undef, \'1 = 0');
114             $sth->execute;
115         };
116         if (not $@) {
117             push @filtered_tables, $table;
118         }
119         else {
120             warn "Bad table or view '$table', ignoring: $@\n";
121         }
122     }
123
124     return @filtered_tables;
125 }
126
127 =head2 load
128
129 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
130
131 =cut
132
133 sub load {
134     my $self = shift;
135
136     local $self->schema->storage->dbh->{RaiseError} = 1;
137     local $self->schema->storage->dbh->{PrintError} = 0;
138     $self->next::method(@_);
139 }
140
141 sub _table_as_sql {
142     my ($self, $table) = @_;
143
144     if($self->{db_schema}) {
145         $table = $self->{db_schema} . $self->{_namesep} .
146             $self->_quote_table_name($table);
147     } else {
148         $table = $self->_quote_table_name($table);
149     }
150
151     return $table;
152 }
153
154 sub _sth_for {
155     my ($self, $table, $fields, $where) = @_;
156
157     my $dbh = $self->schema->storage->dbh;
158
159     my $sth = $dbh->prepare($self->schema->storage->sql_maker
160         ->select(\$self->_table_as_sql($table), $fields, $where));
161
162     return $sth;
163 }
164
165 # Returns an arrayref of column names
166 sub _table_columns {
167     my ($self, $table) = @_;
168
169     my $sth = $self->_sth_for($table, undef, \'1 = 0');
170     $sth->execute;
171     my $retval = \@{$sth->{NAME_lc}};
172     $sth->finish;
173
174     $retval;
175 }
176
177 # Returns arrayref of pk col names
178 sub _table_pk_info { 
179     my ($self, $table) = @_;
180
181     my $dbh = $self->schema->storage->dbh;
182
183     my @primary = map { lc } $dbh->primary_key('', $self->db_schema, $table);
184     s/\Q$self->{_quoter}\E//g for @primary;
185
186     return \@primary;
187 }
188
189 # Override this for vendor-specific uniq info
190 sub _table_uniq_info {
191     my ($self, $table) = @_;
192
193     my $dbh = $self->schema->storage->dbh;
194     if(!$dbh->can('statistics_info')) {
195         warn "No UNIQUE constraint information can be gathered for this vendor";
196         return [];
197     }
198
199     my %indices;
200     my $sth = $dbh->statistics_info(undef, $self->db_schema, $table, 1, 1);
201     while(my $row = $sth->fetchrow_hashref) {
202         # skip table-level stats, conditional indexes, and any index missing
203         #  critical fields
204         next if $row->{TYPE} eq 'table'
205             || defined $row->{FILTER_CONDITION}
206             || !$row->{INDEX_NAME}
207             || !defined $row->{ORDINAL_POSITION}
208             || !$row->{COLUMN_NAME};
209
210         $indices{$row->{INDEX_NAME}}->{$row->{ORDINAL_POSITION}} = $row->{COLUMN_NAME};
211     }
212     $sth->finish;
213
214     my @retval;
215     foreach my $index_name (keys %indices) {
216         my $index = $indices{$index_name};
217         push(@retval, [ $index_name => [
218             map { $index->{$_} }
219                 sort keys %$index
220         ]]);
221     }
222
223     return \@retval;
224 }
225
226 # Find relationships
227 sub _table_fk_info {
228     my ($self, $table) = @_;
229
230     my $dbh = $self->schema->storage->dbh;
231     my $sth = $dbh->foreign_key_info( '', $self->db_schema, '',
232                                       '', $self->db_schema, $table );
233     return [] if !$sth;
234
235     my %rels;
236
237     my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
238     while(my $raw_rel = $sth->fetchrow_arrayref) {
239         my $uk_tbl  = $raw_rel->[2];
240         my $uk_col  = lc $raw_rel->[3];
241         my $fk_col  = lc $raw_rel->[7];
242         my $relid   = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
243         $uk_tbl =~ s/\Q$self->{_quoter}\E//g;
244         $uk_col =~ s/\Q$self->{_quoter}\E//g;
245         $fk_col =~ s/\Q$self->{_quoter}\E//g;
246         $relid  =~ s/\Q$self->{_quoter}\E//g;
247         $rels{$relid}->{tbl} = $uk_tbl;
248         $rels{$relid}->{cols}->{$uk_col} = $fk_col;
249     }
250     $sth->finish;
251
252     my @rels;
253     foreach my $relid (keys %rels) {
254         push(@rels, {
255             remote_columns => [ keys   %{$rels{$relid}->{cols}} ],
256             local_columns  => [ values %{$rels{$relid}->{cols}} ],
257             remote_table   => $rels{$relid}->{tbl},
258         });
259     }
260
261     return \@rels;
262 }
263
264 # ported in from DBIx::Class::Storage::DBI:
265 sub _columns_info_for {
266     my ($self, $table) = @_;
267
268     my $dbh = $self->schema->storage->dbh;
269
270     if ($dbh->can('column_info')) {
271         my %result;
272         eval {
273             my $sth = $dbh->column_info( undef, $self->db_schema, $table, '%' );
274             while ( my $info = $sth->fetchrow_hashref() ){
275                 my %column_info;
276                 $column_info{data_type}   = $info->{TYPE_NAME};
277                 $column_info{size}      = $info->{COLUMN_SIZE};
278                 $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
279                 $column_info{default_value} = $info->{COLUMN_DEF};
280                 my $col_name = $info->{COLUMN_NAME};
281                 $col_name =~ s/^\"(.*)\"$/$1/;
282
283                 my $extra_info = $self->_extra_column_info($info) || {};
284
285                 $result{$col_name} = { %column_info, %$extra_info };
286             }
287             $sth->finish;
288         };
289       return \%result if !$@ && scalar keys %result;
290     }
291
292     my %result;
293     my $sth = $self->_sth_for($table, undef, \'1 = 0');
294     $sth->execute;
295     my @columns = @{$sth->{NAME_lc}};
296     for my $i ( 0 .. $#columns ){
297         my %column_info;
298         $column_info{data_type} = $sth->{TYPE}->[$i];
299         $column_info{size} = $sth->{PRECISION}->[$i];
300         $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
301
302         if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
303             $column_info{data_type} = $1;
304             $column_info{size}    = $2;
305         }
306
307         my $extra_info = $self->_extra_column_info($table, $columns[$i], $sth, $i) || {};
308
309         $result{$columns[$i]} = { %column_info, %$extra_info };
310     }
311     $sth->finish;
312
313     foreach my $col (keys %result) {
314         my $colinfo = $result{$col};
315         my $type_num = $colinfo->{data_type};
316         my $type_name;
317         if(defined $type_num && $dbh->can('type_info')) {
318             my $type_info = $dbh->type_info($type_num);
319             $type_name = $type_info->{TYPE_NAME} if $type_info;
320             $colinfo->{data_type} = $type_name if $type_name;
321         }
322     }
323
324     return \%result;
325 }
326
327 # Override this in vendor class to return any additional column
328 # attributes
329 sub _extra_column_info {}
330
331 =head1 SEE ALSO
332
333 L<DBIx::Class::Schema::Loader>
334
335 =head1 AUTHOR
336
337 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
338
339 =head1 LICENSE
340
341 This library is free software; you can redistribute it and/or modify it under
342 the same terms as Perl itself.
343
344 =cut
345
346 1;