1 package DBIx::Class::Schema::Loader::DBI::MSSQL;
5 use base 'DBIx::Class::Schema::Loader::DBI::Sybase::Common';
8 use List::MoreUtils 'any';
11 use DBIx::Class::Schema::Loader::Table::Sybase ();
13 our $VERSION = '0.07033';
17 DBIx::Class::Schema::Loader::DBI::MSSQL - DBIx::Class::Schema::Loader::DBI MSSQL Implementation.
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
27 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base> for
30 =head1 CASE SENSITIVITY
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
36 We attempt to detect the database collation at startup for any database
37 included in L<db_schema|DBIx::Class::Schema::Loader::Base/db_schema>, and set
38 the column lowercasing behavior accordingly, as lower-cased column names do not
39 work on case-sensitive databases.
41 To manually control case-sensitive mode, put:
45 in your Loader options.
47 See L<preserve_case|DBIx::Class::Schema::Loader::Base/preserve_case>.
49 B<NOTE:> this option used to be called C<case_sensitive_collation>, but has
50 been renamed to a more generic option.
54 sub _system_databases {
56 master model tempdb msdb
62 spt_fallback_db spt_fallback_dev spt_fallback_usg spt_monitor spt_values MSreplication_options
69 my $owners = $self->dbh->selectcol_arrayref(<<"EOF");
71 FROM [$db].dbo.sysusers
75 return grep !/^(?:#|guest|INFORMATION_SCHEMA|sys)/, @$owners;
80 return ($self->dbh->selectrow_array('SELECT db_name()'))[0];
85 $self->dbh->do("use [$db]");
91 $self->next::method(@_);
93 my $current_db = $self->_current_db;
95 if (ref $self->db_schema eq 'HASH') {
96 if (keys %{ $self->db_schema } < 2) {
97 my ($db) = keys %{ $self->db_schema };
102 my $owners = $self->db_schema->{$db};
104 my $db_names = $self->dbh->selectcol_arrayref(<<'EOF');
106 FROM master.dbo.sysdatabases
111 foreach my $db_name (@$db_names) {
113 unless any { $_ eq $db_name } $self->_system_databases;
116 $self->db_schema({});
118 DB: foreach my $db (@dbs) {
119 if (not ((ref $owners eq 'ARRAY' && $owners->[0] eq '%') || $owners eq '%')) {
122 foreach my $owner (@$owners) {
124 if $self->dbh->selectrow_array(<<"EOF");
126 FROM [$db].dbo.sysusers
127 WHERE name = @{[ $self->dbh->quote($owner) ]}
131 next DB unless @owners;
133 $self->db_schema->{$db} = \@owners;
136 # for post-processing below
137 $self->db_schema->{$db} = '%';
141 $self->qualify_objects(1);
144 if ($db ne $current_db) {
145 $self->dbh->do("USE [$db]");
147 $self->qualify_objects(1);
152 $self->qualify_objects(1);
155 elsif (ref $self->db_schema eq 'ARRAY' || (not defined $self->db_schema)) {
156 my $owners = $self->db_schema;
157 $owners ||= [ $self->dbh->selectrow_array('SELECT user_name()') ];
159 $self->qualify_objects(1) if @$owners > 1;
161 $self->db_schema({ $current_db => $owners });
164 foreach my $db (keys %{ $self->db_schema }) {
165 if ($self->db_schema->{$db} eq '%') {
166 $self->db_schema->{$db} = [ $self->_owners($db) ];
168 $self->qualify_objects(1);
172 if (not defined $self->preserve_case) {
173 foreach my $db (keys %{ $self->db_schema }) {
174 # We use the sys.databases query for the general case, and fallback to
175 # databasepropertyex() if for some reason sys.databases is not available,
176 # which does not work over DBD::ODBC with unixODBC+FreeTDS.
178 # XXX why does databasepropertyex() not work over DBD::ODBC ?
180 # more on collations here: http://msdn.microsoft.com/en-us/library/ms143515.aspx
182 my $current_db = $self->_current_db;
184 $self->_switch_db($db);
187 (eval { $self->dbh->selectrow_array("SELECT collation_name FROM [$db].sys.databases WHERE name = @{[ $self->dbh->quote($db) ]}") })[0]
188 || (eval { $self->dbh->selectrow_array("SELECT CAST(databasepropertyex(@{[ $self->dbh->quote($db) ]}, 'Collation') AS VARCHAR)") })[0];
190 $self->_switch_db($current_db);
192 if (not $collation_name) {
195 WARNING: MSSQL Collation detection failed for database '$db'. Defaulting to
196 case-insensitive mode. Override the 'preserve_case' attribute in your Loader
199 See 'preserve_case' in
200 perldoc DBIx::Class::Schema::Loader::Base
202 $self->preserve_case(0) unless $self->preserve_case;
205 my $case_sensitive = $collation_name =~ /_(?:CS|BIN2?)(?:_|\z)/;
207 if ($case_sensitive && (not $self->preserve_case)) {
208 $self->preserve_case(1);
211 $self->preserve_case(0);
219 my ($self, $opts) = @_;
223 while (my ($db, $owners) = each %{ $self->db_schema }) {
224 foreach my $owner (@$owners) {
225 my $table_names = $self->dbh->selectcol_arrayref(<<"EOF");
227 FROM [$db].INFORMATION_SCHEMA.TABLES
228 WHERE table_schema = @{[ $self->dbh->quote($owner) ]}
231 TABLE: foreach my $table_name (@$table_names) {
232 next TABLE if any { $_ eq $table_name } $self->_system_tables;
234 push @tables, DBIx::Class::Schema::Loader::Table::Sybase->new(
244 return $self->_filter_tables(\@tables, $opts);
248 my ($self, $table) = @_;
250 my $db = $table->database;
252 my $pk = $self->dbh->selectcol_arrayref(<<"EOF");
253 SELECT kcu.column_name
254 FROM [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
255 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
256 ON kcu.table_name = tc.table_name
257 AND kcu.table_schema = tc.table_schema
258 AND kcu.constraint_name = tc.constraint_name
259 WHERE tc.table_name = @{[ $self->dbh->quote($table->name) ]}
260 AND tc.table_schema = @{[ $self->dbh->quote($table->schema) ]}
261 AND tc.constraint_type = 'PRIMARY KEY'
262 ORDER BY kcu.ordinal_position
265 $pk = [ map $self->_lc($_), @$pk ];
271 my ($self, $table) = @_;
273 my $db = $table->database;
275 my $sth = $self->dbh->prepare(<<"EOF");
276 SELECT rc.constraint_name, rc.unique_constraint_schema, uk_tc.table_name,
277 fk_kcu.column_name, uk_kcu.column_name, rc.delete_rule, rc.update_rule
278 FROM [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk_tc
279 JOIN [$db].INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
280 ON rc.constraint_name = fk_tc.constraint_name
281 AND rc.constraint_schema = fk_tc.table_schema
282 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE fk_kcu
283 ON fk_kcu.constraint_name = fk_tc.constraint_name
284 AND fk_kcu.table_name = fk_tc.table_name
285 AND fk_kcu.table_schema = fk_tc.table_schema
286 JOIN [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS uk_tc
287 ON uk_tc.constraint_name = rc.unique_constraint_name
288 AND uk_tc.table_schema = rc.unique_constraint_schema
289 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE uk_kcu
290 ON uk_kcu.constraint_name = rc.unique_constraint_name
291 AND uk_kcu.ordinal_position = fk_kcu.ordinal_position
292 AND uk_kcu.table_name = uk_tc.table_name
293 AND uk_kcu.table_schema = rc.unique_constraint_schema
294 WHERE fk_tc.table_name = @{[ $self->dbh->quote($table->name) ]}
295 AND fk_tc.table_schema = @{[ $self->dbh->quote($table->schema) ]}
296 ORDER BY fk_kcu.ordinal_position
303 while (my ($fk, $remote_schema, $remote_table, $col, $remote_col,
304 $delete_rule, $update_rule) = $sth->fetchrow_array) {
305 push @{ $rels{$fk}{local_columns} }, $self->_lc($col);
306 push @{ $rels{$fk}{remote_columns} }, $self->_lc($remote_col);
308 $rels{$fk}{remote_table} = DBIx::Class::Schema::Loader::Table::Sybase->new(
310 name => $remote_table,
312 schema => $remote_schema,
313 ) unless exists $rels{$fk}{remote_table};
315 $rels{$fk}{attrs} ||= {
316 on_delete => uc $delete_rule,
317 on_update => uc $update_rule,
318 is_deferrable => 1 # constraints can be temporarily disabled, but DEFERRABLE is not supported
322 return [ values %rels ];
325 sub _table_uniq_info {
326 my ($self, $table) = @_;
328 my $db = $table->database;
330 my $sth = $self->dbh->prepare(<<"EOF");
331 SELECT tc.constraint_name, kcu.column_name
332 FROM [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
333 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
334 ON kcu.constraint_name = tc.constraint_name
335 AND kcu.table_name = tc.table_name
336 AND kcu.table_schema = tc.table_schema
337 wHERE tc.table_name = @{[ $self->dbh->quote($table->name) ]}
338 AND tc.table_schema = @{[ $self->dbh->quote($table->schema) ]}
339 AND tc.constraint_type = 'UNIQUE'
340 ORDER BY kcu.ordinal_position
347 while (my ($constr, $col) = $sth->fetchrow_array) {
348 push @{ $uniq{$constr} }, $self->_lc($col);
351 return [ map [ $_ => $uniq{$_} ], keys %uniq ];
354 sub _columns_info_for {
358 my $db = $table->database;
360 my $result = $self->next::method(@_);
362 # SQL Server: Ancient as time itself, but still out in the wild
363 my $is_2k = $self->schema->storage->_server_info->{normalized_dbms_version} < 9;
365 # get type info (and identity)
366 my $rows = $self->dbh->selectall_arrayref($is_2k ? <<"EOF2K" : <<"EOF");
367 SELECT c.column_name, c.character_maximum_length, c.data_type, c.datetime_precision, c.column_default, (sc.status & 0x80) is_identity
368 FROM [$db].INFORMATION_SCHEMA.COLUMNS c
369 JOIN [$db].dbo.sysusers ss ON
370 c.table_schema = ss.name
371 JOIN [$db].dbo.sysobjects so ON
372 c.table_name = so.name
374 JOIN [$db].dbo.syscolumns sc ON
375 c.column_name = sc.name
377 WHERE c.table_schema = @{[ $self->dbh->quote($table->schema) ]}
378 AND c.table_name = @{[ $self->dbh->quote($table->name) ]}
380 SELECT c.column_name, c.character_maximum_length, c.data_type, c.datetime_precision, c.column_default, sc.is_identity
381 FROM [$db].INFORMATION_SCHEMA.COLUMNS c
382 JOIN [$db].sys.schemas ss ON
383 c.table_schema = ss.name
384 JOIN [$db].sys.objects so ON
385 c.table_name = so.name
386 AND so.schema_id = ss.schema_id
387 JOIN [$db].sys.columns sc ON
388 c.column_name = sc.name
389 AND sc.object_id = so.object_id
390 WHERE c.table_schema = @{[ $self->dbh->quote($table->schema) ]}
391 AND c.table_name = @{[ $self->dbh->quote($table->name) ]}
394 foreach my $row (@$rows) {
395 my ($col, $char_max_length, $data_type, $datetime_precision, $default, $is_identity) = @$row;
396 $col = lc $col unless $self->preserve_case;
397 my $info = $result->{$col} || next;
399 $info->{data_type} = $data_type;
401 if (defined $char_max_length) {
402 $info->{size} = $char_max_length;
403 $info->{size} = 0 if $char_max_length < 0;
407 $info->{is_auto_increment} = 1;
408 $info->{data_type} =~ s/\s*identity//i;
409 delete $info->{size};
413 if ($data_type eq 'int') {
414 $info->{data_type} = 'integer';
416 elsif ($data_type eq 'timestamp') {
417 $info->{inflate_datetime} = 0;
419 elsif ($data_type =~ /^(?:numeric|decimal)\z/) {
420 if (ref($info->{size}) && $info->{size}[0] == 18 && $info->{size}[1] == 0) {
421 delete $info->{size};
424 elsif ($data_type eq 'float') {
425 $info->{data_type} = 'double precision';
426 delete $info->{size};
428 elsif ($data_type =~ /^(?:small)?datetime\z/) {
429 # fixup for DBD::Sybase
430 if ($info->{default_value} && $info->{default_value} eq '3') {
431 delete $info->{default_value};
434 elsif ($data_type =~ /^(?:datetime(?:2|offset)|time)\z/) {
435 $info->{size} = $datetime_precision;
437 delete $info->{size} if $info->{size} == 7;
439 elsif ($data_type eq 'varchar' && $info->{size} == 0) {
440 $info->{data_type} = 'text';
441 delete $info->{size};
443 elsif ($data_type eq 'nvarchar' && $info->{size} == 0) {
444 $info->{data_type} = 'ntext';
445 delete $info->{size};
447 elsif ($data_type eq 'varbinary' && $info->{size} == 0) {
448 $info->{data_type} = 'image';
449 delete $info->{size};
452 if ($data_type !~ /^(?:n?char|n?varchar|binary|varbinary|numeric|decimal|float|datetime(?:2|offset)|time)\z/) {
453 delete $info->{size};
456 if (defined $default) {
458 $default =~ s/^\( (.*) \)\z/$1/x;
460 # Literal strings are in ''s, numbers are in ()s (in some versions of
461 # MSSQL, in others they are unquoted) everything else is a function.
462 $info->{default_value} =
463 $default =~ /^['(] (.*) [)']\z/x ? $1 :
464 $default =~ /^\d/ ? $default : \$default;
466 if ((eval { lc ${ $info->{default_value} } }||'') eq 'getdate()') {
467 ${ $info->{default_value} } = 'current_timestamp';
469 my $getdate = 'getdate()';
470 $info->{original}{default_value} = \$getdate;
480 L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server>,
481 L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server>,
482 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
483 L<DBIx::Class::Schema::Loader::DBI>
487 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
491 This library is free software; you can redistribute it and/or modify it under
492 the same terms as Perl itself.
497 # vim:et sts=4 sw=4 tw=0: