fix type info for MSSQL
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / MSSQL.pm
1 package DBIx::Class::Schema::Loader::DBI::MSSQL;
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 __PACKAGE__->mk_group_accessors('simple', qw/
10     case_sensitive_collation
11 /);
12
13 our $VERSION = '0.06000';
14
15 =head1 NAME
16
17 DBIx::Class::Schema::Loader::DBI::MSSQL - DBIx::Class::Schema::Loader::DBI MSSQL Implementation.
18
19 =head1 DESCRIPTION
20
21 Base driver for Microsoft SQL Server, used by
22 L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server> for support
23 via L<DBD::Sybase> and
24 L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server> for support via
25 L<DBD::ODBC>.
26
27 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base> for
28 usage information.
29
30 =head1 CASE SENSITIVITY
31
32 Most MSSQL databases use C<CI> (case-insensitive) collation, for this reason
33 generated column names are lower-cased as this makes them easier to work with
34 in L<DBIx::Class>.
35
36 We attempt to detect the database collation at startup, and set the column
37 lowercasing behavior accordingly, as lower-cased column names do not work on
38 case-sensitive databases.
39
40 To manually control case-sensitive mode, put:
41
42     case_sensitive_collation => 1|0
43
44 in your Loader options.
45
46 =cut
47
48 sub _is_case_sensitive {
49     my $self = shift;
50
51     return $self->case_sensitive_collation ? 1 : 0;
52 }
53
54 sub _setup {
55     my $self = shift;
56
57     $self->next::method;
58
59     return if defined $self->case_sensitive_collation;
60
61     my $dbh = $self->schema->storage->dbh;
62
63     # We use the sys.databases query for the general case, and fallback to
64     # databasepropertyex() if for some reason sys.databases is not available,
65     # which does not work over DBD::ODBC with unixODBC+FreeTDS.
66     #
67     # XXX why does databasepropertyex() not work over DBD::ODBC ?
68     #
69     # more on collations here: http://msdn.microsoft.com/en-us/library/ms143515.aspx
70     my ($collation_name) =
71            eval { $dbh->selectrow_array('SELECT collation_name FROM sys.databases WHERE name = DB_NAME()') }
72         || eval { $dbh->selectrow_array("SELECT CAST(databasepropertyex(DB_NAME(), 'Collation') AS VARCHAR)") };
73
74     if (not $collation_name) {
75         warn <<'EOF';
76
77 WARNING: MSSQL Collation detection failed. Defaulting to case-insensitive mode.
78 Override the 'case_sensitive_collation' attribute in your Loader options if
79 needed.
80 EOF
81         $self->case_sensitive_collation(0);
82         return;
83     }
84
85     my $case_sensitive = $collation_name =~ /_(?:CS|BIN2?)(?:_|\z)/;
86
87     $self->case_sensitive_collation($case_sensitive ? 1 : 0);
88 }
89
90 sub _lc {
91     my ($self, $name) = @_;
92
93     return $self->case_sensitive_collation ? $name : lc($name);
94 }
95
96 sub _tables_list {
97     my ($self, $opts) = @_;
98
99     my $dbh = $self->schema->storage->dbh;
100     my $sth = $dbh->prepare(<<'EOF');
101 SELECT t.table_name
102 FROM INFORMATION_SCHEMA.TABLES t
103 WHERE lower(t.table_schema) = ?
104 EOF
105     $sth->execute(lc $self->db_schema);
106
107     my @tables = map @$_, @{ $sth->fetchall_arrayref };
108
109     return $self->_filter_tables(\@tables, $opts);
110 }
111
112 sub _table_pk_info {
113     my ($self, $table) = @_;
114     my $dbh = $self->schema->storage->dbh;
115     my $sth = $dbh->prepare(qq{sp_pkeys '$table'});
116     $sth->execute;
117
118     my @keydata;
119
120     while (my $row = $sth->fetchrow_hashref) {
121         push @keydata, $self->_lc($row->{COLUMN_NAME});
122     }
123
124     return \@keydata;
125 }
126
127 sub _table_fk_info {
128     my ($self, $table) = @_;
129
130     my ($local_cols, $remote_cols, $remote_table, @rels, $sth);
131     my $dbh = $self->schema->storage->dbh;
132     eval {
133         $sth = $dbh->prepare(qq{sp_fkeys \@fktable_name = '$table'});
134         $sth->execute;
135     };
136
137     while (my $row = eval { $sth->fetchrow_hashref }) {
138         my $fk = $row->{FK_NAME};
139         push @{$local_cols->{$fk}}, $self->_lc($row->{FKCOLUMN_NAME});
140         push @{$remote_cols->{$fk}}, $self->_lc($row->{PKCOLUMN_NAME});
141         $remote_table->{$fk} = $row->{PKTABLE_NAME};
142     }
143
144     foreach my $fk (keys %$remote_table) {
145         push @rels, {
146                       local_columns => \@{$local_cols->{$fk}},
147                       remote_columns => \@{$remote_cols->{$fk}},
148                       remote_table => $remote_table->{$fk},
149                     };
150
151     }
152     return \@rels;
153 }
154
155 sub _table_uniq_info {
156     my ($self, $table) = @_;
157
158     my $dbh = $self->schema->storage->dbh;
159     local $dbh->{FetchHashKeyName} = 'NAME_lc';
160
161     my $sth = $dbh->prepare(qq{
162 SELECT ccu.constraint_name, ccu.column_name
163 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
164 JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc on (ccu.constraint_name = tc.constraint_name)
165 JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu on (ccu.constraint_name = kcu.constraint_name and ccu.column_name = kcu.column_name)
166 wHERE lower(ccu.table_name) = @{[ $dbh->quote(lc $table) ]} AND constraint_type = 'UNIQUE' ORDER BY kcu.ordinal_position
167     });
168     $sth->execute;
169     my $constraints;
170     while (my $row = $sth->fetchrow_hashref) {
171         my $name = $row->{constraint_name};
172         my $col  = $self->_lc($row->{column_name});
173         push @{$constraints->{$name}}, $col;
174     }
175
176     my @uniqs = map { [ $_ => $constraints->{$_} ] } keys %$constraints;
177     return \@uniqs;
178 }
179
180 sub _columns_info_for {
181     my $self    = shift;
182     my ($table) = @_;
183
184     my $result = $self->next::method(@_);
185
186     while (my ($col, $info) = each %$result) {
187         my $dbh = $self->schema->storage->dbh;
188
189 # find identities
190         my $sth = $dbh->prepare(qq{
191 SELECT column_name 
192 FROM INFORMATION_SCHEMA.COLUMNS
193 WHERE columnproperty(object_id(@{[ $dbh->quote(lc $table) ]}, 'U'), @{[ $dbh->quote(lc $col) ]}, 'IsIdentity') = 1
194 AND lower(table_name) = @{[ $dbh->quote(lc $table) ]} AND lower(column_name) = @{[ $dbh->quote(lc $col) ]}
195         });
196         if (eval { $sth->execute; $sth->fetchrow_array }) {
197             $info->{is_auto_increment} = 1;
198             $info->{data_type} =~ s/\s*identity//i;
199             delete $info->{size};
200         }
201
202 # fix types
203         if ($info->{data_type} eq 'int') {
204             $info->{data_type} = 'integer';
205         }
206         elsif ($info->{data_type} eq 'timestamp') {
207             $info->{inflate_datetime} = 0;
208         }
209         elsif ($info->{data_type} =~ /^(?:numeric|decimal)\z/) {
210             if (ref($info->{size}) && $info->{size}[0] == 18 && $info->{size}[1] == 0) {
211                 delete $info->{size};
212             }
213         }
214         elsif ($info->{data_type} eq 'real') {
215             $info->{data_type} = 'float';
216             $info->{size}      = 24;
217         }
218         elsif ($info->{data_type} eq 'float') {
219             $info->{data_type} = 'double precision';
220         }
221         elsif ($info->{data_type} =~ /^(?:small)?datetime\z/) {
222             # fixup for DBD::Sybase
223             if ($info->{default_value} && $info->{default_value} eq '3') {
224                 delete $info->{default_value};
225             }
226         }
227         elsif ($info->{data_type} eq 'datetimeoffset') {
228             $info->{size} = {
229                 26 => 0,
230                 28 => 1,
231                 29 => 2,
232                 30 => 3,
233                 31 => 4,
234                 32 => 5,
235                 33 => 6,
236                 34 => 7,
237             }->{$info->{size}};
238
239             delete $info->{size} if $info->{size} == 7;
240         }
241         elsif ($info->{data_type} eq 'datetime2') {
242             $info->{size} = {
243                 19 => 0,
244                 21 => 1,
245                 22 => 2,
246                 23 => 3,
247                 24 => 4,
248                 25 => 5,
249                 26 => 6,
250                 27 => 7,
251             }->{$info->{size}};
252
253             delete $info->{size} if $info->{size} == 7;
254         }
255         elsif ($info->{data_type} eq 'time') {
256             $info->{size} = {
257                  8 => 0,
258                 10 => 1,
259                 11 => 2,
260                 12 => 3,
261                 13 => 4,
262                 14 => 5,
263                 15 => 6,
264                 16 => 7,
265             }->{$info->{size}};
266
267             delete $info->{size} if $info->{size} == 7;
268         }
269
270         if ($info->{data_type} !~ /^(?:n?char|n?varchar|binary|varbinary|numeric|decimal|float|datetime(?:2|offset)|time)\z/) {
271             delete $info->{size};
272         }
273
274 # get default
275         $sth = $dbh->prepare(qq{
276 SELECT column_default
277 FROM INFORMATION_SCHEMA.COLUMNS
278 wHERE lower(table_name) = @{[ $dbh->quote(lc $table) ]} AND lower(column_name) = @{[ $dbh->quote(lc $col) ]}
279         });
280         my ($default) = eval { $sth->execute; $sth->fetchrow_array };
281
282         if (defined $default) {
283             # strip parens
284             $default =~ s/^\( (.*) \)\z/$1/x;
285
286             # Literal strings are in ''s, numbers are in ()s (in some versions of
287             # MSSQL, in others they are unquoted) everything else is a function.
288             $info->{default_value} =
289                 $default =~ /^['(] (.*) [)']\z/x ? $1 :
290                     $default =~ /^\d/ ? $default : \$default;
291         }
292     }
293
294     return $result;
295 }
296
297 =head1 SEE ALSO
298
299 L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server>,
300 L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server>,
301 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
302 L<DBIx::Class::Schema::Loader::DBI>
303
304 =head1 AUTHOR
305
306 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
307
308 =head1 LICENSE
309
310 This library is free software; you can redistribute it and/or modify it under
311 the same terms as Perl itself.
312
313 =cut
314
315 1;
316 # vim:et sts=4 sw=4 tw=0: