1 package DBIx::Class::Schema::Loader::DBI::MSSQL;
5 use base 'DBIx::Class::Schema::Loader::DBI::Sybase::Common';
11 use DBIx::Class::Schema::Loader::Table::Sybase ();
13 our $VERSION = '0.07046';
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 # SQL Server 2000: Ancient as time itself, but still out in the wild
56 return shift->schema->storage->_server_info->{normalized_dbms_version} < 9;
59 sub _system_databases {
61 master model tempdb msdb
67 spt_fallback_db spt_fallback_dev spt_fallback_usg spt_monitor spt_values MSreplication_options
74 my $owners = $self->dbh->selectcol_arrayref($self->_is_2k ? <<"EOF2K" : <<"EOF");
76 FROM [$db].dbo.sysusers
80 FROM [$db].sys.schemas
83 return grep !/^(?:#|guest|INFORMATION_SCHEMA|sys)/, @$owners;
90 return ($self->dbh->selectrow_array('SELECT user_name()'))[0];
93 return ($self->dbh->selectrow_array('SELECT schema_name()'))[0];
98 return ($self->dbh->selectrow_array('SELECT db_name()'))[0];
102 my ($self, $db) = @_;
103 $self->dbh->do("use [$db]");
109 $self->next::method(@_);
111 my $current_db = $self->_current_db;
113 if (ref $self->db_schema eq 'HASH') {
114 if (keys %{ $self->db_schema } < 2) {
115 my ($db) = keys %{ $self->db_schema };
120 my $owners = $self->db_schema->{$db};
122 my $db_names = $self->dbh->selectcol_arrayref(<<'EOF');
124 FROM master.dbo.sysdatabases
129 foreach my $db_name (@$db_names) {
131 unless any { $_ eq $db_name } $self->_system_databases;
134 $self->db_schema({});
136 DB: foreach my $db (@dbs) {
137 if (not ((ref $owners eq 'ARRAY' && $owners->[0] eq '%') || $owners eq '%')) {
140 foreach my $owner (@$owners) {
142 if $self->dbh->selectrow_array(<<"EOF");
144 FROM [$db].dbo.sysusers
145 WHERE name = @{[ $self->dbh->quote($owner) ]}
149 next DB unless @owners;
151 $self->db_schema->{$db} = \@owners;
154 # for post-processing below
155 $self->db_schema->{$db} = '%';
159 $self->qualify_objects(1);
162 if ($db ne $current_db) {
163 $self->_switch_db($db);
165 $self->qualify_objects(1);
170 $self->qualify_objects(1);
173 elsif (ref $self->db_schema eq 'ARRAY' || (not defined $self->db_schema)) {
174 my $owners = $self->db_schema;
175 $owners ||= [ $self->_current_schema ];
177 $self->qualify_objects(1) if @$owners > 1;
179 $self->db_schema({ $current_db => $owners });
182 foreach my $db (keys %{ $self->db_schema }) {
183 if ($self->db_schema->{$db} eq '%') {
184 $self->db_schema->{$db} = [ $self->_schemas($db) ];
186 $self->qualify_objects(1);
190 if (not defined $self->preserve_case) {
191 foreach my $db (keys %{ $self->db_schema }) {
192 # We use the sys.databases query for the general case, and fallback to
193 # databasepropertyex() if for some reason sys.databases is not available,
194 # which does not work over DBD::ODBC with unixODBC+FreeTDS.
196 # XXX why does databasepropertyex() not work over DBD::ODBC ?
198 # more on collations here: http://msdn.microsoft.com/en-us/library/ms143515.aspx
200 my $current_db = $self->_current_db;
202 $self->_switch_db($db);
205 (eval { $self->dbh->selectrow_array("SELECT collation_name FROM [$db].sys.databases WHERE name = @{[ $self->dbh->quote($db) ]}") })[0]
206 || (eval { $self->dbh->selectrow_array("SELECT CAST(databasepropertyex(@{[ $self->dbh->quote($db) ]}, 'Collation') AS VARCHAR)") })[0];
208 $self->_switch_db($current_db);
210 if (not $collation_name) {
213 WARNING: MSSQL Collation detection failed for database '$db'. Defaulting to
214 case-insensitive mode. Override the 'preserve_case' attribute in your Loader
217 See 'preserve_case' in
218 perldoc DBIx::Class::Schema::Loader::Base
220 $self->preserve_case(0) unless $self->preserve_case;
223 my $case_sensitive = $collation_name =~ /_(?:CS|BIN2?)(?:_|\z)/;
225 if ($case_sensitive && (not $self->preserve_case)) {
226 $self->preserve_case(1);
229 $self->preserve_case(0);
241 while (my ($db, $owners) = each %{ $self->db_schema }) {
242 foreach my $owner (@$owners) {
243 my $table_names = $self->dbh->selectcol_arrayref(<<"EOF");
245 FROM [$db].INFORMATION_SCHEMA.TABLES
246 WHERE table_schema = @{[ $self->dbh->quote($owner) ]}
249 TABLE: foreach my $table_name (@$table_names) {
250 next TABLE if any { $_ eq $table_name } $self->_system_tables;
252 push @tables, DBIx::Class::Schema::Loader::Table::Sybase->new(
262 return $self->_filter_tables(\@tables);
266 my ($self, $table) = @_;
268 my $db = $table->database;
270 my $pk = $self->dbh->selectcol_arrayref(<<"EOF");
271 SELECT kcu.column_name
272 FROM [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
273 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
274 ON kcu.table_name = tc.table_name
275 AND kcu.table_schema = tc.table_schema
276 AND kcu.constraint_name = tc.constraint_name
277 WHERE tc.table_name = @{[ $self->dbh->quote($table->name) ]}
278 AND tc.table_schema = @{[ $self->dbh->quote($table->schema) ]}
279 AND tc.constraint_type = 'PRIMARY KEY'
280 ORDER BY kcu.ordinal_position
283 $pk = [ map $self->_lc($_), @$pk ];
289 my ($self, $table) = @_;
291 my $db = $table->database;
293 my $sth = $self->dbh->prepare(<<"EOF");
294 SELECT rc.constraint_name, rc.unique_constraint_schema, uk_tc.table_name,
295 fk_kcu.column_name, uk_kcu.column_name, rc.delete_rule, rc.update_rule
296 FROM [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk_tc
297 JOIN [$db].INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
298 ON rc.constraint_name = fk_tc.constraint_name
299 AND rc.constraint_schema = fk_tc.table_schema
300 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE fk_kcu
301 ON fk_kcu.constraint_name = fk_tc.constraint_name
302 AND fk_kcu.table_name = fk_tc.table_name
303 AND fk_kcu.table_schema = fk_tc.table_schema
304 JOIN [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS uk_tc
305 ON uk_tc.constraint_name = rc.unique_constraint_name
306 AND uk_tc.table_schema = rc.unique_constraint_schema
307 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE uk_kcu
308 ON uk_kcu.constraint_name = rc.unique_constraint_name
309 AND uk_kcu.ordinal_position = fk_kcu.ordinal_position
310 AND uk_kcu.table_name = uk_tc.table_name
311 AND uk_kcu.table_schema = rc.unique_constraint_schema
312 WHERE fk_tc.table_name = @{[ $self->dbh->quote($table->name) ]}
313 AND fk_tc.table_schema = @{[ $self->dbh->quote($table->schema) ]}
314 ORDER BY fk_kcu.ordinal_position
321 while (my ($fk, $remote_schema, $remote_table, $col, $remote_col,
322 $delete_rule, $update_rule) = $sth->fetchrow_array) {
323 push @{ $rels{$fk}{local_columns} }, $self->_lc($col);
324 push @{ $rels{$fk}{remote_columns} }, $self->_lc($remote_col);
326 $rels{$fk}{remote_table} = DBIx::Class::Schema::Loader::Table::Sybase->new(
328 name => $remote_table,
330 schema => $remote_schema,
331 ) unless exists $rels{$fk}{remote_table};
333 $rels{$fk}{attrs} ||= {
334 on_delete => uc $delete_rule,
335 on_update => uc $update_rule,
336 is_deferrable => 1 # constraints can be temporarily disabled, but DEFERRABLE is not supported
340 return [ values %rels ];
343 sub _table_uniq_info {
344 my ($self, $table) = @_;
346 my $db = $table->database;
348 my $sth = $self->dbh->prepare(<<"EOF");
349 SELECT tc.constraint_name, kcu.column_name
350 FROM [$db].INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
351 JOIN [$db].INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
352 ON kcu.constraint_name = tc.constraint_name
353 AND kcu.table_name = tc.table_name
354 AND kcu.table_schema = tc.table_schema
355 wHERE tc.table_name = @{[ $self->dbh->quote($table->name) ]}
356 AND tc.table_schema = @{[ $self->dbh->quote($table->schema) ]}
357 AND tc.constraint_type = 'UNIQUE'
358 ORDER BY kcu.ordinal_position
365 while (my ($constr, $col) = $sth->fetchrow_array) {
366 push @{ $uniq{$constr} }, $self->_lc($col);
369 return [ map [ $_ => $uniq{$_} ], sort keys %uniq ];
372 sub _columns_info_for {
376 my $db = $table->database;
378 my $result = $self->next::method(@_);
380 # get type info (and identity)
381 my $rows = $self->dbh->selectall_arrayref($self->_is_2k ? <<"EOF2K" : <<"EOF");
382 SELECT c.column_name, c.character_maximum_length, c.data_type, c.datetime_precision, c.column_default, (sc.status & 0x80) is_identity
383 FROM [$db].INFORMATION_SCHEMA.COLUMNS c
384 JOIN [$db].dbo.sysusers ss ON
385 c.table_schema = ss.name
386 JOIN [$db].dbo.sysobjects so ON
387 c.table_name = so.name
389 JOIN [$db].dbo.syscolumns sc ON
390 c.column_name = sc.name
392 WHERE c.table_schema = @{[ $self->dbh->quote($table->schema) ]}
393 AND c.table_name = @{[ $self->dbh->quote($table->name) ]}
395 SELECT c.column_name, c.character_maximum_length, c.data_type, c.datetime_precision, c.column_default, sc.is_identity
396 FROM [$db].INFORMATION_SCHEMA.COLUMNS c
397 JOIN [$db].sys.schemas ss ON
398 c.table_schema = ss.name
399 JOIN [$db].sys.objects so ON
400 c.table_name = so.name
401 AND so.schema_id = ss.schema_id
402 JOIN [$db].sys.columns sc ON
403 c.column_name = sc.name
404 AND sc.object_id = so.object_id
405 WHERE c.table_schema = @{[ $self->dbh->quote($table->schema) ]}
406 AND c.table_name = @{[ $self->dbh->quote($table->name) ]}
409 foreach my $row (@$rows) {
410 my ($col, $char_max_length, $data_type, $datetime_precision, $default, $is_identity) = @$row;
411 $col = lc $col unless $self->preserve_case;
412 my $info = $result->{$col} || next;
414 $info->{data_type} = $data_type;
416 if (defined $char_max_length) {
417 $info->{size} = $char_max_length;
418 $info->{size} = 0 if $char_max_length < 0;
422 $info->{is_auto_increment} = 1;
423 $info->{data_type} =~ s/\s*identity//i;
424 delete $info->{size};
428 if ($data_type eq 'int') {
429 $info->{data_type} = 'integer';
431 elsif ($data_type eq 'timestamp') {
432 $info->{inflate_datetime} = 0;
434 elsif ($data_type =~ /^(?:numeric|decimal)\z/) {
435 if (ref($info->{size}) && $info->{size}[0] == 18 && $info->{size}[1] == 0) {
436 delete $info->{size};
439 elsif ($data_type eq 'float') {
440 $info->{data_type} = 'double precision';
441 delete $info->{size};
443 elsif ($data_type =~ /^(?:small)?datetime\z/) {
444 # fixup for DBD::Sybase
445 if ($info->{default_value} && $info->{default_value} eq '3') {
446 delete $info->{default_value};
449 elsif ($data_type =~ /^(?:datetime(?:2|offset)|time)\z/) {
450 $info->{size} = $datetime_precision;
452 delete $info->{size} if $info->{size} == 7;
454 elsif ($data_type eq 'varchar' && $info->{size} == 0) {
455 $info->{data_type} = 'text';
456 delete $info->{size};
458 elsif ($data_type eq 'nvarchar' && $info->{size} == 0) {
459 $info->{data_type} = 'ntext';
460 delete $info->{size};
462 elsif ($data_type eq 'varbinary' && $info->{size} == 0) {
463 $info->{data_type} = 'image';
464 delete $info->{size};
467 if ($data_type !~ /^(?:n?char|n?varchar|binary|varbinary|numeric|decimal|float|datetime(?:2|offset)|time)\z/) {
468 delete $info->{size};
471 if (defined $default) {
473 $default =~ s/^\( (.*) \)\z/$1/x;
475 # Literal strings are in ''s, numbers are in ()s (in some versions of
476 # MSSQL, in others they are unquoted) everything else is a function.
477 $info->{default_value} =
478 $default =~ /^['(] (.*) [)']\z/x ? $1 :
479 $default =~ /^\d/ ? $default : \$default;
481 if ((eval { lc ${ $info->{default_value} } }||'') eq 'getdate()') {
482 ${ $info->{default_value} } = 'current_timestamp';
484 my $getdate = 'getdate()';
485 $info->{original}{default_value} = \$getdate;
495 L<DBIx::Class::Schema::Loader::DBI::Sybase::Microsoft_SQL_Server>,
496 L<DBIx::Class::Schema::Loader::DBI::ODBC::Microsoft_SQL_Server>,
497 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
498 L<DBIx::Class::Schema::Loader::DBI>
502 See L<DBIx::Class::Schema::Loader/AUTHORS>.
506 This library is free software; you can redistribute it and/or modify it under
507 the same terms as Perl itself.
512 # vim:et sts=4 sw=4 tw=0: