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