cleaned up ODBC crap and added docs
[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_07';
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->schema->storage->sql_maker->quote_char
50                     || $dbh->get_info(29)
51                     || q{"};
52
53     $self->{_namesep} = $self->schema->storage->sql_maker->name_sep
54                      || $dbh->get_info(41)
55                      || q{.};
56
57     # For our usage as regex matches, concatenating multiple quoter
58     # values works fine (e.g. s/\Q<>\E// if quoter was [ '<', '>' ])
59     if( ref $self->{_quoter} eq 'ARRAY') {
60         $self->{_quoter} = join(q{}, @{$self->{_quoter}});
61     }
62
63     $self->_setup;
64
65     $self;
66 }
67
68 # Override this in vendor modules to do things at the end of ->new()
69 sub _setup { }
70
71 # Override this in vendor module to load a subclass if necessary
72 sub _rebless { }
73
74 # Returns an array of table names
75 sub _tables_list { 
76     my $self = shift;
77
78     my ($table, $type) = @_ ? @_ : ('%', '%');
79
80     my $dbh = $self->schema->storage->dbh;
81     my @tables = $dbh->tables(undef, $self->db_schema, $table, $type);
82     s/\Q$self->{_quoter}\E//g for @tables;
83     s/^.*\Q$self->{_namesep}\E// for @tables;
84
85     return @tables;
86 }
87
88 =head2 load
89
90 We override L<DBIx::Class::Schema::Loader::Base/load> here to hook in our localized settings for C<$dbh> error handling.
91
92 =cut
93
94 sub load {
95     my $self = shift;
96
97     local $self->schema->storage->dbh->{RaiseError} = 1;
98     local $self->schema->storage->dbh->{PrintError} = 0;
99     $self->next::method(@_);
100 }
101
102 # Returns an arrayref of column names
103 sub _table_columns {
104     my ($self, $table) = @_;
105
106     my $dbh = $self->schema->storage->dbh;
107
108     if($self->{db_schema}) {
109         $table = $self->{db_schema} . $self->{_namesep} . $table;
110     }
111
112     my $sth = $dbh->prepare($self->schema->storage->sql_maker->select($table, undef, \'1 = 0'));
113     $sth->execute;
114     my $retval = \@{$sth->{NAME_lc}};
115     $sth->finish;
116
117     $retval;
118 }
119
120 # Returns arrayref of pk col names
121 sub _table_pk_info { 
122     my ($self, $table) = @_;
123
124     my $dbh = $self->schema->storage->dbh;
125
126     my @primary = map { lc } $dbh->primary_key('', $self->db_schema, $table);
127     s/\Q$self->{_quoter}\E//g for @primary;
128
129     return \@primary;
130 }
131
132 # Override this for vendor-specific uniq info
133 sub _table_uniq_info {
134     my ($self, $table) = @_;
135
136     my $dbh = $self->schema->storage->dbh;
137     if(!$dbh->can('statistics_info')) {
138         warn "No UNIQUE constraint information can be gathered for this vendor";
139         return [];
140     }
141
142     my %indices;
143     my $sth = $dbh->statistics_info(undef, $self->db_schema, $table, 1, 1);
144     while(my $row = $sth->fetchrow_hashref) {
145         # skip table-level stats, conditional indexes, and any index missing
146         #  critical fields
147         next if $row->{TYPE} eq 'table'
148             || defined $row->{FILTER_CONDITION}
149             || !$row->{INDEX_NAME}
150             || !defined $row->{ORDINAL_POSITION}
151             || !$row->{COLUMN_NAME};
152
153         $indices{$row->{INDEX_NAME}}->{$row->{ORDINAL_POSITION}} = $row->{COLUMN_NAME};
154     }
155     $sth->finish;
156
157     my @retval;
158     foreach my $index_name (keys %indices) {
159         my $index = $indices{$index_name};
160         push(@retval, [ $index_name => [
161             map { $index->{$_} }
162                 sort keys %$index
163         ]]);
164     }
165
166     return \@retval;
167 }
168
169 # Find relationships
170 sub _table_fk_info {
171     my ($self, $table) = @_;
172
173     my $dbh = $self->schema->storage->dbh;
174     my $sth = $dbh->foreign_key_info( '', $self->db_schema, '',
175                                       '', $self->db_schema, $table );
176     return [] if !$sth;
177
178     my %rels;
179
180     my $i = 1; # for unnamed rels, which hopefully have only 1 column ...
181     while(my $raw_rel = $sth->fetchrow_arrayref) {
182         my $uk_tbl  = $raw_rel->[2];
183         my $uk_col  = lc $raw_rel->[3];
184         my $fk_col  = lc $raw_rel->[7];
185         my $relid   = ($raw_rel->[11] || ( "__dcsld__" . $i++ ));
186         $uk_tbl =~ s/\Q$self->{_quoter}\E//g;
187         $uk_col =~ s/\Q$self->{_quoter}\E//g;
188         $fk_col =~ s/\Q$self->{_quoter}\E//g;
189         $relid  =~ s/\Q$self->{_quoter}\E//g;
190         $rels{$relid}->{tbl} = $uk_tbl;
191         $rels{$relid}->{cols}->{$uk_col} = $fk_col;
192     }
193     $sth->finish;
194
195     my @rels;
196     foreach my $relid (keys %rels) {
197         push(@rels, {
198             remote_columns => [ keys   %{$rels{$relid}->{cols}} ],
199             local_columns  => [ values %{$rels{$relid}->{cols}} ],
200             remote_table   => $rels{$relid}->{tbl},
201         });
202     }
203
204     return \@rels;
205 }
206
207 # ported in from DBIx::Class::Storage::DBI:
208 sub _columns_info_for {
209     my ($self, $table) = @_;
210
211     my $dbh = $self->schema->storage->dbh;
212
213     if ($dbh->can('column_info')) {
214         my %result;
215         eval {
216             my $sth = $dbh->column_info( undef, $self->db_schema, $table, '%' );
217             while ( my $info = $sth->fetchrow_hashref() ){
218                 my %column_info;
219                 $column_info{data_type}   = $info->{TYPE_NAME};
220                 $column_info{size}      = $info->{COLUMN_SIZE};
221                 $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
222                 $column_info{default_value} = $info->{COLUMN_DEF};
223                 my $col_name = $info->{COLUMN_NAME};
224                 $col_name =~ s/^\"(.*)\"$/$1/;
225
226                 my $extra_info = $self->_extra_column_info($info) || {};
227
228                 $result{$col_name} = { %column_info, %$extra_info };
229             }
230             $sth->finish;
231         };
232       return \%result if !$@ && scalar keys %result;
233     }
234
235     if($self->db_schema) {
236         $table = $self->db_schema . $self->{_namesep} . $table;
237     }
238     my %result;
239     my $sth = $dbh->prepare($self->schema->storage->sql_maker->select($table, undef, \'1 = 0'));
240     $sth->execute;
241     my @columns = @{$sth->{NAME_lc}};
242     for my $i ( 0 .. $#columns ){
243         my %column_info;
244         $column_info{data_type} = $sth->{TYPE}->[$i];
245         $column_info{size} = $sth->{PRECISION}->[$i];
246         $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
247
248         if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
249             $column_info{data_type} = $1;
250             $column_info{size}    = $2;
251         }
252
253         my $extra_info = $self->_extra_column_info($table, $columns[$i], $sth, $i) || {};
254
255         $result{$columns[$i]} = { %column_info, %$extra_info };
256     }
257     $sth->finish;
258
259     foreach my $col (keys %result) {
260         my $colinfo = $result{$col};
261         my $type_num = $colinfo->{data_type};
262         my $type_name;
263         if(defined $type_num && $dbh->can('type_info')) {
264             my $type_info = $dbh->type_info($type_num);
265             $type_name = $type_info->{TYPE_NAME} if $type_info;
266             $colinfo->{data_type} = $type_name if $type_name;
267         }
268     }
269
270     return \%result;
271 }
272
273 # Override this in vendor class to return any additional column
274 # attributes
275 sub _extra_column_info {}
276
277 =head1 SEE ALSO
278
279 L<DBIx::Class::Schema::Loader>
280
281 =cut
282
283 1;