MSSQL data type fixes for native client and EasySoft driver
[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/;
942bd5e0 7use mro 'c3';
fe67d343 8
e94ccbea 9our $VERSION = '0.07006';
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
ae38ed69 193# get datetime precision
194 $sth = $dbh->prepare(qq{
195SELECT datetime_precision
196FROM INFORMATION_SCHEMA.COLUMNS
197WHERE table_name = @{[ $dbh->quote($table) ]} AND column_name = @{[ $dbh->quote($col) ]}
198 });
199 $sth->execute;
200 my ($datetime_precision) = $sth->fetchrow_array;
201
81ade4d9 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 }
81ade4d9 214 elsif ($info->{data_type} eq 'float') {
215 $info->{data_type} = 'double precision';
216 }
217 elsif ($info->{data_type} =~ /^(?:small)?datetime\z/) {
218 # fixup for DBD::Sybase
219 if ($info->{default_value} && $info->{default_value} eq '3') {
220 delete $info->{default_value};
221 }
222 }
ae38ed69 223 elsif ($info->{data_type} =~ /^(?:datetime(?:2|offset)|time)\z/) {
224 $info->{size} = $datetime_precision;
81ade4d9 225
226 delete $info->{size} if $info->{size} == 7;
227 }
ae38ed69 228 elsif ($info->{data_type} eq 'varchar' && $info->{size} == 0) {
229 $info->{data_type} = 'text';
230 delete $info->{size};
81ade4d9 231 }
ae38ed69 232 elsif ($info->{data_type} eq 'nvarchar' && $info->{size} == 0) {
233 $info->{data_type} = 'ntext';
234 delete $info->{size};
235 }
236 elsif ($info->{data_type} eq 'varbinary' && $info->{size} == 0) {
237 $info->{data_type} = 'image';
238 delete $info->{size};
81ade4d9 239 }
240
241 if ($info->{data_type} !~ /^(?:n?char|n?varchar|binary|varbinary|numeric|decimal|float|datetime(?:2|offset)|time)\z/) {
242 delete $info->{size};
243 }
244
5c6fb0a1 245# get default
9c9197d6 246 $sth = $dbh->prepare(qq{
020f3c3a 247SELECT column_default
060f5ecd 248FROM INFORMATION_SCHEMA.COLUMNS
8c41c3ce 249wHERE table_name = @{[ $dbh->quote($table) ]} AND column_name = @{[ $dbh->quote($col) ]}
9c9197d6 250 });
020f3c3a 251 my ($default) = eval { $sth->execute; $sth->fetchrow_array };
9c9197d6 252
253 if (defined $default) {
254 # strip parens
255 $default =~ s/^\( (.*) \)\z/$1/x;
256
257 # Literal strings are in ''s, numbers are in ()s (in some versions of
258 # MSSQL, in others they are unquoted) everything else is a function.
259 $info->{default_value} =
260 $default =~ /^['(] (.*) [)']\z/x ? $1 :
261 $default =~ /^\d/ ? $default : \$default;
8a64178e 262
268cc246 263 if ((eval { lc ${ $info->{default_value} } }||'') eq 'getdate()') {
6e566cc4 264 ${ $info->{default_value} } = 'current_timestamp';
701cd3e3 265
266 my $getdate = 'getdate()';
267 $info->{original}{default_value} = \$getdate;
8a64178e 268 }
9c9197d6 269 }
5c6fb0a1 270 }
271
9c9197d6 272 return $result;
fe67d343 273}
274
fe67d343 275=head1 SEE ALSO
276
acfcc1fb 277L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server>,
278L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server>,
fe67d343 279L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
280L<DBIx::Class::Schema::Loader::DBI>
281
282=head1 AUTHOR
283
9cc8e7e1 284See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
fe67d343 285
be80bba7 286=head1 LICENSE
0852b7b8 287
be80bba7 288This library is free software; you can redistribute it and/or modify it under
289the same terms as Perl itself.
0852b7b8 290
fe67d343 291=cut
292
2931;
bfb43060 294# vim:et sts=4 sw=4 tw=0: