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