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