better _tables_list for Sybase ASE
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / Sybase.pm
1 package DBIx::Class::Schema::Loader::DBI::Sybase;
2
3 use strict;
4 use warnings;
5 use base 'DBIx::Class::Schema::Loader::DBI::Sybase::Common';
6 use Carp::Clan qw/^DBIx::Class/;
7 use mro 'c3';
8
9 our $VERSION = '0.07002';
10
11 =head1 NAME
12
13 DBIx::Class::Schema::Loader::DBI::Sybase - DBIx::Class::Schema::Loader::DBI
14 Sybase ASE Implementation.
15
16 =head1 DESCRIPTION
17
18 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
19
20 =cut
21
22 sub _setup {
23     my $self = shift;
24
25     $self->next::method(@_);
26
27     if (not defined $self->preserve_case) {
28         $self->preserve_case(1);
29     }
30
31     $self->{db_schema} ||=
32         ($self->schema->storage->dbh->selectrow_array('select user_name()'))[0];
33 }
34
35 sub _rebless {
36     my $self = shift;
37
38     my $dbh = $self->schema->storage->dbh;
39     my $DBMS_VERSION = @{$dbh->selectrow_arrayref(qq{sp_server_info \@attribute_id=1})}[2];
40     if ($DBMS_VERSION =~ /^Microsoft /i) {
41         $DBMS_VERSION =~ s/\s/_/g;
42         my $subclass = "DBIx::Class::Schema::Loader::DBI::Sybase::$DBMS_VERSION";
43         if ($self->load_optional_class($subclass) && !$self->isa($subclass)) {
44             bless $self, $subclass;
45             $self->_rebless;
46       }
47     }
48 }
49
50 sub _tables_list {
51     my ($self, $opts) = @_;
52
53     my $dbh = $self->schema->storage->dbh;
54
55     my $sth = $dbh->table_info(undef, $self->db_schema, undef, "'TABLE','VIEW'");
56
57     my @tables = grep $_ ne 'sysquerymetrics',
58               map $_->{table_name}, @{ $sth->fetchall_arrayref({ table_name => 1 }) };
59
60     return $self->_filter_tables(\@tables, $opts);
61 }
62
63 sub _table_columns {
64     my ($self, $table) = @_;
65
66     my $dbh = $self->schema->storage->dbh;
67     my $columns = $dbh->selectcol_arrayref(qq{
68 SELECT c.name
69 FROM syscolumns c JOIN sysobjects o
70 ON c.id = o.id
71 WHERE o.name = @{[ $dbh->quote($table) ]} AND o.type = 'U'
72 });
73
74     return $columns;
75 }
76
77 sub _table_pk_info {
78     my ($self, $table) = @_;
79
80     my $dbh = $self->schema->storage->dbh;
81     my $sth = $dbh->prepare(qq{sp_pkeys @{[ $dbh->quote($table) ]}});
82     $sth->execute;
83
84     my @keydata;
85
86     while (my $row = $sth->fetchrow_hashref) {
87         push @keydata, $row->{column_name};
88     }
89
90     return \@keydata;
91 }
92
93 sub _table_fk_info {
94     my ($self, $table) = @_;
95
96     # check if FK_NAME is supported
97
98     my $dbh = $self->schema->storage->dbh;
99     local $dbh->{FetchHashKeyName} = 'NAME_lc';
100     # hide "Object does not exist in this database." when trying to fetch fkeys
101     local $dbh->{syb_err_handler} = sub { return $_[0] == 17461 ? 0 : 1 }; 
102     my $sth = $dbh->prepare(qq{sp_fkeys \@fktable_name = @{[ $dbh->quote($table) ]}});
103     $sth->execute;
104     my $row = $sth->fetchrow_hashref;
105
106     return unless $row;
107
108     if (exists $row->{fk_name}) {
109         $sth->finish;
110         return $self->_table_fk_info_by_name($table);
111     }
112
113     $sth->finish;
114     return $self->_table_fk_info_builder($table);
115 }
116
117 sub _table_fk_info_by_name {
118     my ($self, $table) = @_;
119     my ($local_cols, $remote_cols, $remote_table, @rels);
120
121     my $dbh = $self->schema->storage->dbh;
122     local $dbh->{FetchHashKeyName} = 'NAME_lc';
123     # hide "Object does not exist in this database." when trying to fetch fkeys
124     local $dbh->{syb_err_handler} = sub { return $_[0] == 17461 ? 0 : 1 }; 
125     my $sth = $dbh->prepare(qq{sp_fkeys \@fktable_name = @{[ $dbh->quote($table) ]}});
126     $sth->execute;
127
128     while (my $row = $sth->fetchrow_hashref) {
129         my $fk = $row->{fk_name};
130         next unless defined $fk;
131
132         push @{$local_cols->{$fk}}, $row->{fkcolumn_name};
133         push @{$remote_cols->{$fk}}, $row->{pkcolumn_name};
134         $remote_table->{$fk} = $row->{pktable_name};
135     }
136
137     foreach my $fk (keys %$remote_table) {
138         push @rels, {
139                      local_columns => \@{$local_cols->{$fk}},
140                      remote_columns => \@{$remote_cols->{$fk}},
141                      remote_table => $remote_table->{$fk},
142                     };
143
144     }
145     return \@rels;
146 }
147
148 sub _table_fk_info_builder {
149     my ($self, $table) = @_;
150
151     my $dbh = $self->schema->storage->dbh;
152     local $dbh->{FetchHashKeyName} = 'NAME_lc';
153     # hide "Object does not exist in this database." when trying to fetch fkeys
154     local $dbh->{syb_err_handler} = sub { return 0 if $_[0] == 17461; }; 
155     my $sth = $dbh->prepare(qq{sp_fkeys \@fktable_name = @{[ $dbh->quote($table) ]}});
156     $sth->execute;
157
158     my @fk_info;
159     while (my $row = $sth->fetchrow_hashref) {
160         (my $ksq = $row->{key_seq}) =~ s/\s+//g;
161
162         my @keys = qw/pktable_name pkcolumn_name fktable_name fkcolumn_name/;
163         my %ds;
164         @ds{@keys}   = @{$row}{@keys};
165         $ds{key_seq} = $ksq;
166
167         push @{ $fk_info[$ksq] }, \%ds;
168     }
169
170     my $max_keys = $#fk_info;
171     my @rels;
172     for my $level (reverse 1 .. $max_keys) {
173         my @level_rels;
174         $level_rels[$level] = splice @fk_info, $level, 1;
175         my $count = @{ $level_rels[$level] };
176
177         for my $sub_level (reverse 1 .. $level-1) {
178             my $total = @{ $fk_info[$sub_level] };
179
180             $level_rels[$sub_level] = [
181                 splice @{ $fk_info[$sub_level] }, $total-$count, $count
182             ];
183         }
184
185         while (1) {
186             my @rel = map shift @$_, @level_rels[1..$level];
187
188             last unless defined $rel[0];
189
190             my @local_columns  = map $_->{fkcolumn_name}, @rel;
191             my @remote_columns = map $_->{pkcolumn_name}, @rel;
192             my $remote_table   = $rel[0]->{pktable_name};
193
194             push @rels, {
195                 local_columns => \@local_columns,
196                 remote_columns => \@remote_columns,
197                 remote_table => $remote_table
198             };
199         }
200     }
201
202     return \@rels;
203 }
204
205 sub _table_uniq_info {
206     no warnings 'uninitialized'; # for presumably XS weirdness with null operations
207     my ($self, $table) = @_;
208
209     local $SIG{__WARN__} = sub { warn @_
210         unless $_[0] =~ /^Formula for Calculation:|^(?:--?|\+|=) Number of (?:self )?references|^Total Number of Referential Constraints|^Details:|^\s*$/ };
211
212     my $dbh = $self->schema->storage->dbh;
213     local $dbh->{FetchHashKeyName} = 'NAME_lc';
214     my $sth = $dbh->prepare(qq{sp_helpconstraint \@objname=@{[ $dbh->quote($table) ]}, \@nomsg='nomsg'});
215     eval { $sth->execute };
216     return if $@;
217
218     my $constraints;
219     while (my $row = $sth->fetchrow_hashref) {
220         if (exists $row->{constraint_type}) {
221             my $type = $row->{constraint_type} || '';
222             if ($type =~ /^unique/i) {
223                 my $name = $row->{constraint_name};
224                 push @{$constraints->{$name}},
225                     ( split /,/, $row->{constraint_keys} );
226             }
227         } else {
228             my $def = $row->{definition} || next;
229             next unless $def =~ /^unique/i;
230             my $name = $row->{name};
231             my ($keys) = $def =~ /\((.*)\)/;
232             $keys =~ s/\s*//g;
233             my @keys = split /,/ => $keys;
234             push @{$constraints->{$name}}, @keys;
235         }
236     }
237
238     my @uniqs = map { [ $_ => $constraints->{$_} ] } keys %$constraints;
239     return \@uniqs;
240 }
241
242 # get the correct data types, defaults and size
243 sub _columns_info_for {
244     my $self    = shift;
245     my ($table) = @_;
246     my $result  = $self->next::method(@_);
247
248     my $dbh = $self->schema->storage->dbh;
249     my $sth = $dbh->prepare(qq{
250 SELECT c.name name, bt.name base_type, ut.name user_type, cm.text deflt, c.prec prec, c.scale scale, c.length len
251 FROM syscolumns c
252 JOIN sysobjects o ON c.id = o.id
253 LEFT JOIN systypes bt ON c.type     = bt.type 
254 LEFT JOIN systypes ut ON c.usertype = ut.usertype
255 LEFT JOIN syscomments cm
256     ON cm.id = CASE WHEN c.cdefault = 0 THEN c.computedcol ELSE c.cdefault END
257 WHERE o.name = @{[ $dbh->quote($table) ]} AND o.type = 'U'
258 });
259     $sth->execute;
260     local $dbh->{FetchHashKeyName} = 'NAME_lc';
261     my $info = $sth->fetchall_hashref('name');
262
263     while (my ($col, $res) = each %$result) {
264         my $data_type = $res->{data_type} = $info->{$col}{user_type} || $info->{$col}{base_type};
265
266         if ($data_type && $data_type =~ /^timestamp\z/i) {
267             $res->{inflate_datetime} = 0;
268         }
269
270         if (my $default = $info->{$col}{deflt}) {
271             if ($default =~ /^AS \s+ (\S+)/ix) {
272                 my $function = $1;
273                 $res->{default_value} = \$function;
274
275                 if ($function =~ /^getdate\b/) {
276                     $res->{inflate_datetime} = 1;
277                 }
278
279                 delete $res->{size};
280                 $res->{data_type} = undef;
281             }
282             elsif ($default =~ /^DEFAULT \s+ (\S+)/ix) {
283                 my ($constant_default) = $1 =~ /^['"\[\]]?(.*?)['"\[\]]?\z/;
284                 $res->{default_value} = $constant_default;
285             }
286         }
287
288         if (my $data_type = $res->{data_type}) {
289             if ($data_type eq 'int') {
290                 $data_type = $res->{data_type} = 'integer';
291             }
292             elsif ($data_type eq 'decimal') {
293                 $data_type = $res->{data_type} = 'numeric';
294             }
295
296             if ($data_type =~ /^(?:text|unitext|image|bigint|integer|smallint|tinyint|real|double|double precision|float|date|time|datetime|smalldatetime|money|smallmoney|timestamp|bit)\z/i) {
297                 delete $res->{size};
298             }
299             elsif ($data_type eq 'numeric') {
300                 my ($prec, $scale) = @{$info->{$col}}{qw/prec scale/};
301
302                 if ($prec == 18 && $scale == 0) {
303                     delete $res->{size};
304                 }
305                 else {
306                     $res->{size} = [ $prec, $scale ];
307                 }
308             }
309             elsif ($data_type =~ /^(?:unichar|univarchar)\z/i) {
310                 $res->{size} /= 2;
311             }
312         }
313
314         if ($data_type eq 'float') {
315             $res->{data_type} = $info->{$col}{len} <= 4 ? 'real' : 'double precision';
316         }
317     }
318
319     return $result;
320 }
321
322 sub _extra_column_info {
323     my ($self, $table, $column, $info, $dbi_info) = @_;
324     my %extra_info;
325
326     my $dbh = $self->schema->storage->dbh;
327     my $sth = $dbh->prepare(qq{SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = @{[ $dbh->quote($table) ]}) AND (status & 0x80) = 0x80 AND name = @{[ $dbh->quote($column) ]}});
328     $sth->execute();
329
330     if ($sth->fetchrow_array) {
331         $extra_info{is_auto_increment} = 1;
332     }
333
334     return \%extra_info;
335 }
336
337 =head1 SEE ALSO
338
339 L<DBIx::Class::Schema::Loader::DBI::Sybase::Common>,
340 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
341 L<DBIx::Class::Schema::Loader::DBI>
342
343 =head1 AUTHOR
344
345 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
346
347 =head1 LICENSE
348
349 This library is free software; you can redistribute it and/or modify it under
350 the same terms as Perl itself.
351
352 =cut
353
354 1;
355 # vim:et sts=4 sw=4 tw=0: