13c57d44a81d20125cb5c0f0ee46a5702ccfa286
[dbsrgits/DBIx-Class-Schema-Loader.git] / t / 10_07mssql_common.t
1 use strict;
2 use warnings;
3 use Test::More;
4 use Test::Exception;
5 use DBIx::Class::Schema::Loader::Utils 'warnings_exist_silent';
6 use Try::Tiny;
7 use File::Path 'rmtree';
8 use DBIx::Class::Schema::Loader 'make_schema_at';
9 use namespace::clean;
10 use Scope::Guard ();
11
12 # use this if you keep a copy of DBD::Sybase linked to FreeTDS somewhere else
13 BEGIN {
14   if (my $lib_dirs = $ENV{DBICTEST_MSSQL_PERL5LIB}) {
15     unshift @INC, $_ for split /:/, $lib_dirs;
16   }
17 }
18
19 use lib qw(t/lib);
20
21 use dbixcsl_common_tests ();
22 use dbixcsl_test_dir '$tdir';
23
24 use constant EXTRA_DUMP_DIR => "$tdir/mssql_extra_dump";
25
26 # for extra tests cleanup
27 my $schema;
28
29 my ($dsns, $common_version);
30
31 for (qw/MSSQL MSSQL_ODBC MSSQL_ADO/) {
32   next unless $ENV{"DBICTEST_${_}_DSN"};
33
34   $dsns->{$_}{dsn} = $ENV{"DBICTEST_${_}_DSN"};
35   $dsns->{$_}{user} = $ENV{"DBICTEST_${_}_USER"};
36   $dsns->{$_}{password} = $ENV{"DBICTEST_${_}_PASS"};
37
38   require DBI;
39   my $dbh = DBI->connect (@{$dsns->{$_}}{qw/dsn user password/}, { RaiseError => 1, PrintError => 0} );
40   my $srv_ver = eval {
41     $dbh->get_info(18)
42       ||
43     $dbh->selectrow_hashref('master.dbo.xp_msver ProductVersion')->{Character_Value}
44   } || 0;
45
46   my ($maj_srv_ver) = $srv_ver =~ /^(\d+)/;
47
48   if (! defined $common_version or $common_version > $maj_srv_ver ) {
49     $common_version = $maj_srv_ver;
50   }
51 }
52
53 plan skip_all => 'You need to set the DBICTEST_MSSQL_DSN, _USER and _PASS and/or the DBICTEST_MSSQL_ODBC_DSN, _USER and _PASS environment variables'
54   unless $dsns;
55
56 my $mssql_2008_new_data_types = {
57   date     => { data_type => 'date' },
58   time     => { data_type => 'time' },
59   'time(0)'=> { data_type => 'time', size => 0 },
60   'time(1)'=> { data_type => 'time', size => 1 },
61   'time(2)'=> { data_type => 'time', size => 2 },
62   'time(3)'=> { data_type => 'time', size => 3 },
63   'time(4)'=> { data_type => 'time', size => 4 },
64   'time(5)'=> { data_type => 'time', size => 5 },
65   'time(6)'=> { data_type => 'time', size => 6 },
66   'time(7)'=> { data_type => 'time' },
67   datetimeoffset => { data_type => 'datetimeoffset' },
68   'datetimeoffset(0)' => { data_type => 'datetimeoffset', size => 0 },
69   'datetimeoffset(1)' => { data_type => 'datetimeoffset', size => 1 },
70   'datetimeoffset(2)' => { data_type => 'datetimeoffset', size => 2 },
71   'datetimeoffset(3)' => { data_type => 'datetimeoffset', size => 3 },
72   'datetimeoffset(4)' => { data_type => 'datetimeoffset', size => 4 },
73   'datetimeoffset(5)' => { data_type => 'datetimeoffset', size => 5 },
74   'datetimeoffset(6)' => { data_type => 'datetimeoffset', size => 6 },
75   'datetimeoffset(7)' => { data_type => 'datetimeoffset' },
76   datetime2      => { data_type => 'datetime2' },
77   'datetime2(0)' => { data_type => 'datetime2', size => 0 },
78   'datetime2(1)' => { data_type => 'datetime2', size => 1 },
79   'datetime2(2)' => { data_type => 'datetime2', size => 2 },
80   'datetime2(3)' => { data_type => 'datetime2', size => 3 },
81   'datetime2(4)' => { data_type => 'datetime2', size => 4 },
82   'datetime2(5)' => { data_type => 'datetime2', size => 5 },
83   'datetime2(6)' => { data_type => 'datetime2', size => 6 },
84   'datetime2(7)' => { data_type => 'datetime2' },
85
86   hierarchyid      => { data_type => 'hierarchyid' },
87 };
88
89 my $tester = dbixcsl_common_tests->new(
90     vendor      => 'mssql',
91     auto_inc_pk => 'INTEGER IDENTITY NOT NULL PRIMARY KEY',
92     default_function_def => 'DATETIME DEFAULT getdate()',
93     connect_info => [values %$dsns],
94     preserve_case_mode_is_exclusive => 1,
95     quote_char => [ qw/[ ]/ ],
96     basic_date_datatype => ($common_version >= 10) ? 'DATE' : 'SMALLDATETIME',
97     data_types => {
98         # http://msdn.microsoft.com/en-us/library/ms187752.aspx
99
100         # numeric types
101         'int identity' => { data_type => 'integer', is_auto_increment => 1 },
102         bigint   => { data_type => 'bigint' },
103         int      => { data_type => 'integer' },
104         integer  => { data_type => 'integer' },
105         smallint => { data_type => 'smallint' },
106         tinyint  => { data_type => 'tinyint' },
107         money       => { data_type => 'money' },
108         smallmoney  => { data_type => 'smallmoney' },
109         bit         => { data_type => 'bit' },
110         real           => { data_type => 'real' },
111         'float(14)'    => { data_type => 'real' },
112         'float(24)'    => { data_type => 'real' },
113         'float(25)'    => { data_type => 'double precision' },
114         'float(53)'    => { data_type => 'double precision' },
115         float          => { data_type => 'double precision' },
116         'double precision'
117                        => { data_type => 'double precision' },
118         'numeric(6)'   => { data_type => 'numeric', size => [6,0] },
119         'numeric(6,3)' => { data_type => 'numeric', size => [6,3] },
120         'decimal(6)'   => { data_type => 'decimal', size => [6,0] },
121         'decimal(6,3)' => { data_type => 'decimal', size => [6,3] },
122         'dec(6,3)'     => { data_type => 'decimal', size => [6,3] },
123         numeric        => { data_type => 'numeric' },
124         decimal        => { data_type => 'decimal' },
125         dec            => { data_type => 'decimal' },
126
127         # datetime types
128         datetime => { data_type => 'datetime' },
129         # test rewriting getdate() to current_timestamp
130         'datetime default getdate()'
131                  => { data_type => 'datetime', default_value => \'current_timestamp',
132                       original => { default_value => \'getdate()' } },
133         smalldatetime  => { data_type => 'smalldatetime' },
134
135         ($common_version >= 10) ? %$mssql_2008_new_data_types : (),
136
137         # string types
138         char           => { data_type => 'char', size => 1 },
139         'char(2)'      => { data_type => 'char', size => 2 },
140         character      => { data_type => 'char', size => 1 },
141         'character(2)' => { data_type => 'char', size => 2 },
142         'varchar(2)'   => { data_type => 'varchar', size => 2 },
143
144         nchar          => { data_type => 'nchar', size => 1 },
145         'nchar(2)'     => { data_type => 'nchar', size => 2 },
146         'nvarchar(2)'  => { data_type => 'nvarchar', size => 2 },
147
148         # binary types
149         'binary'       => { data_type => 'binary', size => 1 },
150         'binary(2)'    => { data_type => 'binary', size => 2 },
151         'varbinary(2)' => { data_type => 'varbinary', size => 2 },
152
153         # blob types
154         'varchar(max)'   => { data_type => 'text' },
155         text             => { data_type => 'text' },
156
157         'nvarchar(max)'  => { data_type => 'ntext' },
158         ntext            => { data_type => 'ntext' },
159
160         'varbinary(max)' => { data_type => 'image' },
161         image            => { data_type => 'image' },
162
163         # other types
164         timestamp        => { data_type => 'timestamp', inflate_datetime => 0 },
165         rowversion       => { data_type => 'rowversion' },
166         uniqueidentifier => { data_type => 'uniqueidentifier' },
167         sql_variant      => { data_type => 'sql_variant' },
168         xml              => { data_type => 'xml' },
169     },
170     extra => {
171         create => [
172             q{
173                 CREATE TABLE [mssql_loader_test1.dot] (
174                     id INT IDENTITY NOT NULL PRIMARY KEY,
175                     dat VARCHAR(8)
176                 )
177             },
178             q{
179                 CREATE TABLE mssql_loader_test3 (
180                     id INT IDENTITY NOT NULL PRIMARY KEY
181                 )
182             },
183             q{
184                 CREATE VIEW mssql_loader_test4 AS
185                 SELECT * FROM mssql_loader_test3
186             },
187             # test capitalization of cols in unique constraints and rels
188             q{ SET QUOTED_IDENTIFIER ON },
189             q{ SET ANSI_NULLS ON },
190             q{
191                 CREATE TABLE [MSSQL_Loader_Test5] (
192                     [Id] INT IDENTITY NOT NULL PRIMARY KEY,
193                     [FooCol] INT NOT NULL,
194                     [BarCol] INT NOT NULL,
195                     UNIQUE ([FooCol], [BarCol])
196                 )
197             },
198             q{
199                 CREATE TABLE [MSSQL_Loader_Test6] (
200                     [Five_Id] INT REFERENCES [MSSQL_Loader_Test5] ([Id])
201                 )
202             },
203         ],
204         pre_drop_ddl => [
205             'CREATE TABLE mssql_loader_test3 (id INT IDENTITY NOT NULL PRIMARY KEY)',
206             'DROP VIEW mssql_loader_test4',
207         ],
208         drop   => [
209             '[mssql_loader_test1.dot]',
210             'mssql_loader_test3',
211             'MSSQL_Loader_Test6',
212             'MSSQL_Loader_Test5',
213         ],
214         count  => 10 + 30 * 2 + 26 * 2, # extra + multi-schema + mutli-db
215         run    => sub {
216             my ($monikers, $classes, $self);
217             ($schema, $monikers, $classes, $self) = @_;
218
219             my $connect_info = [@$self{qw/dsn user password/}];
220
221 # Test that the table above (with '.' in name) gets loaded correctly.
222             ok((my $rs = eval {
223                 $schema->resultset('MssqlLoaderTest1Dot') }),
224                 'got a resultset for table with dot in name');
225
226             ok((my $from = eval { $rs->result_source->from }),
227                 'got an $rsrc->from for table with dot in name');
228
229             is ref($from), 'SCALAR', '->table with dot in name is a scalar ref';
230
231             is eval { $$from }, "[mssql_loader_test1.dot]",
232                 '->table with dot in name has correct name';
233
234 # Test capitalization of columns and unique constraints
235             ok ((my $rsrc = $schema->resultset($monikers->{mssql_loader_test5})->result_source),
236                 'got result_source');
237
238             if ($schema->loader->preserve_case) {
239                 is_deeply [ $rsrc->columns ], [qw/Id FooCol BarCol/],
240                     'column name case is preserved with case-sensitive collation';
241
242                 my %uniqs = $rsrc->unique_constraints;
243                 delete $uniqs{primary};
244
245                 is_deeply ((values %uniqs)[0], [qw/FooCol BarCol/],
246                     'column name case is preserved in unique constraint with case-sensitive collation');
247             }
248             else {
249                 is_deeply [ $rsrc->columns ], [qw/id foocol barcol/],
250                     'column names are lowercased for case-insensitive collation';
251
252                 my %uniqs = $rsrc->unique_constraints;
253                 delete $uniqs{primary};
254
255                 is_deeply ((values %uniqs)[0], [qw/foocol barcol/],
256                     'columns in unique constraint lowercased for case-insensitive collation');
257             }
258
259             lives_and {
260                 my $five_row = $schema->resultset($monikers->{mssql_loader_test5})->new_result({});
261
262                 if ($schema->loader->preserve_case) {
263                     $five_row->foo_col(1);
264                     $five_row->bar_col(2);
265                 }
266                 else {
267                     $five_row->foocol(1);
268                     $five_row->barcol(2);
269                 }
270                 $five_row->insert;
271
272                 my $six_row = $five_row->create_related('mssql_loader_test6s', {});
273
274                 is $six_row->five->id, 1;
275             } 'relationships for mixed-case tables/columns detected';
276
277 # Test that a bad view (where underlying table is gone) is ignored.
278             my $dbh = $schema->storage->dbh;
279             $dbh->do("DROP TABLE mssql_loader_test3");
280
281             warnings_exist_silent { $schema->rescan }
282               qr/^Bad table or view 'mssql_loader_test4'/, 'bad view ignored';
283
284             throws_ok {
285                 $schema->resultset($monikers->{mssql_loader_test4})
286             } qr/Can't find source/,
287                 'no source registered for bad view';
288
289             SKIP: {
290                 my $dbh = $schema->storage->dbh;
291
292                 try {
293                     $dbh->do('CREATE SCHEMA [dbicsl-test]');
294                 }
295                 catch {
296                     skip "no CREATE SCHEMA privileges", 30 * 2;
297                 };
298
299                 $dbh->do(<<"EOF");
300                     CREATE TABLE [dbicsl-test].mssql_loader_test8 (
301                         id INT IDENTITY PRIMARY KEY,
302                         value VARCHAR(100)
303                     )
304 EOF
305                 $dbh->do(<<"EOF");
306                     CREATE TABLE [dbicsl-test].mssql_loader_test9 (
307                         id INT IDENTITY PRIMARY KEY,
308                         value VARCHAR(100),
309                         eight_id INTEGER NOT NULL,
310                         CONSTRAINT loader_test9_uniq UNIQUE (eight_id),
311                         FOREIGN KEY (eight_id) REFERENCES [dbicsl-test].mssql_loader_test8 (id)
312                     )
313 EOF
314                 $dbh->do('CREATE SCHEMA [dbicsl.test]');
315                 $dbh->do(<<"EOF");
316                     CREATE TABLE [dbicsl.test].mssql_loader_test9 (
317                         pk INT IDENTITY PRIMARY KEY,
318                         value VARCHAR(100),
319                         eight_id INTEGER NOT NULL,
320                         CONSTRAINT loader_test9_uniq UNIQUE (eight_id),
321                         FOREIGN KEY (eight_id) REFERENCES [dbicsl-test].mssql_loader_test8 (id)
322                     )
323 EOF
324                 $dbh->do(<<"EOF");
325                     CREATE TABLE [dbicsl.test].mssql_loader_test10 (
326                         id INT IDENTITY PRIMARY KEY,
327                         value VARCHAR(100),
328                         mssql_loader_test8_id INTEGER,
329                         FOREIGN KEY (mssql_loader_test8_id) REFERENCES [dbicsl-test].mssql_loader_test8 (id)
330                     )
331 EOF
332                 $dbh->do(<<"EOF");
333                     CREATE TABLE [dbicsl.test].mssql_loader_test11 (
334                         id INT IDENTITY PRIMARY KEY,
335                         value VARCHAR(100),
336                         ten_id INTEGER NOT NULL UNIQUE,
337                         FOREIGN KEY (ten_id) REFERENCES [dbicsl.test].mssql_loader_test10 (id)
338                     )
339 EOF
340                 $dbh->do(<<"EOF");
341                     CREATE TABLE [dbicsl-test].mssql_loader_test12 (
342                         id INT IDENTITY PRIMARY KEY,
343                         value VARCHAR(100),
344                         mssql_loader_test11_id INTEGER,
345                         FOREIGN KEY (mssql_loader_test11_id) REFERENCES [dbicsl.test].mssql_loader_test11 (id)
346                     )
347 EOF
348
349                 my $guard = Scope::Guard->new(\&cleanup_schemas);
350
351                 foreach my $db_schema (['dbicsl-test', 'dbicsl.test'], '%') {
352                     lives_and {
353                         rmtree EXTRA_DUMP_DIR;
354
355                         my @warns;
356                         local $SIG{__WARN__} = sub {
357                             push @warns, $_[0] unless $_[0] =~ /\bcollides\b/;
358                         };
359
360                         make_schema_at(
361                             'MSSQLMultiSchema',
362                             {
363                                 naming => 'current',
364                                 db_schema => $db_schema,
365                                 dump_directory => EXTRA_DUMP_DIR,
366                                 quiet => 1,
367                             },
368                             $connect_info,
369                         );
370
371                         diag join "\n", @warns if @warns;
372
373                         is @warns, 0;
374                     } 'dumped schema for "dbicsl-test" and "dbicsl.test" schemas with no warnings';
375
376                     my ($test_schema, $rsrc, $rs, $row, %uniqs, $rel_info);
377
378                     lives_and {
379                         ok $test_schema = MSSQLMultiSchema->connect(@$connect_info);
380                     } 'connected test schema';
381
382                     lives_and {
383                         ok $rsrc = $test_schema->source('MssqlLoaderTest8');
384                     } 'got source for table in schema name with dash';
385
386                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
387                         'column in schema name with dash';
388
389                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar',
390                         'column in schema name with dash';
391
392                     is try { $rsrc->column_info('value')->{size} }, 100,
393                         'column in schema name with dash';
394
395                     lives_and {
396                         ok $rs = $test_schema->resultset('MssqlLoaderTest8');
397                     } 'got resultset for table in schema name with dash';
398
399                     lives_and {
400                         ok $row = $rs->create({ value => 'foo' });
401                     } 'executed SQL on table in schema name with dash';
402
403                     $rel_info = try { $rsrc->relationship_info('dbicsl_dash_test_mssql_loader_test9') };
404
405                     is_deeply $rel_info->{cond}, {
406                         'foreign.eight_id' => 'self.id'
407                     }, 'relationship in schema name with dash';
408
409                     is $rel_info->{attrs}{accessor}, 'single',
410                         'relationship in schema name with dash';
411
412                     is $rel_info->{attrs}{join_type}, 'LEFT',
413                         'relationship in schema name with dash';
414
415                     lives_and {
416                         ok $rsrc = $test_schema->source('DbicslDashTestMssqlLoaderTest9');
417                     } 'got source for table in schema name with dash';
418
419                     %uniqs = try { $rsrc->unique_constraints };
420
421                     is keys %uniqs, 2,
422                         'got unique and primary constraint in schema name with dash';
423
424                     delete $uniqs{primary};
425
426                     is_deeply ((values %uniqs)[0], ['eight_id'],
427                         'correct unique constraint in schema name with dash');
428
429                     lives_and {
430                         ok $rsrc = $test_schema->source('MssqlLoaderTest10');
431                     } 'got source for table in schema name with dot';
432
433                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
434                         'column in schema name with dot introspected correctly';
435
436                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar',
437                         'column in schema name with dot introspected correctly';
438
439                     is try { $rsrc->column_info('value')->{size} }, 100,
440                         'column in schema name with dot introspected correctly';
441
442                     lives_and {
443                         ok $rs = $test_schema->resultset('MssqlLoaderTest10');
444                     } 'got resultset for table in schema name with dot';
445
446                     lives_and {
447                         ok $row = $rs->create({ value => 'foo' });
448                     } 'executed SQL on table in schema name with dot';
449
450                     $rel_info = try { $rsrc->relationship_info('mssql_loader_test11') };
451
452                     is_deeply $rel_info->{cond}, {
453                         'foreign.ten_id' => 'self.id'
454                     }, 'relationship in schema name with dot';
455
456                     is $rel_info->{attrs}{accessor}, 'single',
457                         'relationship in schema name with dot';
458
459                     is $rel_info->{attrs}{join_type}, 'LEFT',
460                         'relationship in schema name with dot';
461
462                     lives_and {
463                         ok $rsrc = $test_schema->source('MssqlLoaderTest11');
464                     } 'got source for table in schema name with dot';
465
466                     %uniqs = try { $rsrc->unique_constraints };
467
468                     is keys %uniqs, 2,
469                         'got unique and primary constraint in schema name with dot';
470
471                     delete $uniqs{primary};
472
473                     is_deeply ((values %uniqs)[0], ['ten_id'],
474                         'correct unique constraint in schema name with dot');
475
476                     lives_and {
477                         ok $test_schema->source('MssqlLoaderTest10')
478                             ->has_relationship('mssql_loader_test8');
479                     } 'cross-schema relationship in multi-db_schema';
480
481                     lives_and {
482                         ok $test_schema->source('MssqlLoaderTest8')
483                             ->has_relationship('mssql_loader_test10s');
484                     } 'cross-schema relationship in multi-db_schema';
485
486                     lives_and {
487                         ok $test_schema->source('MssqlLoaderTest12')
488                             ->has_relationship('mssql_loader_test11');
489                     } 'cross-schema relationship in multi-db_schema';
490
491                     lives_and {
492                         ok $test_schema->source('MssqlLoaderTest11')
493                             ->has_relationship('mssql_loader_test12s');
494                     } 'cross-schema relationship in multi-db_schema';
495                 }
496             }
497
498             SKIP: {
499                 # for ADO
500                 my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
501                 local $SIG{__WARN__} = sub {
502                     $warn_handler->(@_) unless $_[0] =~ /Changed database context/;
503                 };
504
505                 my $dbh = $schema->storage->dbh;
506
507                 try {
508                     $dbh->do('USE master');
509                     $dbh->do('CREATE DATABASE dbicsl_test1');
510                 }
511                 catch {
512                     diag "no CREATE DATABASE privileges: '$_'";
513                     skip "no CREATE DATABASE privileges", 26 * 2;
514                 };
515
516                 $dbh->do('CREATE DATABASE dbicsl_test2');
517
518                 $dbh->do('USE dbicsl_test1');
519
520                 $dbh->do(<<'EOF');
521                     CREATE TABLE mssql_loader_test13 (
522                         id INT IDENTITY PRIMARY KEY,
523                         value VARCHAR(100)
524                     )
525 EOF
526                 $dbh->do(<<'EOF');
527                     CREATE TABLE mssql_loader_test14 (
528                         id INT IDENTITY PRIMARY KEY,
529                         value VARCHAR(100),
530                         thirteen_id INTEGER REFERENCES mssql_loader_test13 (id),
531                         CONSTRAINT loader_test14_uniq UNIQUE (thirteen_id)
532                     )
533 EOF
534
535                 $dbh->do('USE dbicsl_test2');
536
537                 $dbh->do(<<'EOF');
538                     CREATE TABLE mssql_loader_test14 (
539                         pk INT IDENTITY PRIMARY KEY,
540                         value VARCHAR(100),
541                         thirteen_id INTEGER,
542                         CONSTRAINT loader_test14_uniq UNIQUE (thirteen_id)
543                     )
544 EOF
545
546                 $dbh->do(<<"EOF");
547                     CREATE TABLE mssql_loader_test15 (
548                         id INT IDENTITY PRIMARY KEY,
549                         value VARCHAR(100)
550                     )
551 EOF
552                 $dbh->do(<<"EOF");
553                     CREATE TABLE mssql_loader_test16 (
554                         id INT IDENTITY PRIMARY KEY,
555                         value VARCHAR(100),
556                         fifteen_id INTEGER UNIQUE REFERENCES mssql_loader_test15 (id)
557                     )
558 EOF
559
560                 my $guard = Scope::Guard->new(\&cleanup_databases);
561
562                 foreach my $db_schema ({ dbicsl_test1 => '%', dbicsl_test2 => '%' }, { '%' => '%' }) {
563                     lives_and {
564                         my @warns;
565                         local $SIG{__WARN__} = sub {
566                             push @warns, $_[0] unless $_[0] =~ /\bcollides\b/;
567                         };
568      
569                         make_schema_at(
570                             'MSSQLMultiDatabase',
571                             {
572                                 naming => 'current',
573                                 db_schema => $db_schema,
574                                 dump_directory => EXTRA_DUMP_DIR,
575                                 quiet => 1,
576                             },
577                             $connect_info,
578                         );
579
580                         diag join "\n", @warns if @warns;
581
582                         is @warns, 0;
583                     } "dumped schema for databases 'dbicsl_test1' and 'dbicsl_test2' with no warnings";
584
585                     my $test_schema;
586
587                     lives_and {
588                         ok $test_schema = MSSQLMultiDatabase->connect(@$connect_info);
589                     } 'connected test schema';
590
591                     my ($rsrc, $rs, $row, $rel_info, %uniqs);
592
593                     lives_and {
594                         ok $rsrc = $test_schema->source('MssqlLoaderTest13');
595                     } 'got source for table in database one';
596
597                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
598                         'column in database one';
599
600                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar',
601                         'column in database one';
602
603                     is try { $rsrc->column_info('value')->{size} }, 100,
604                         'column in database one';
605
606                     lives_and {
607                         ok $rs = $test_schema->resultset('MssqlLoaderTest13');
608                     } 'got resultset for table in database one';
609
610                     lives_and {
611                         ok $row = $rs->create({ value => 'foo' });
612                     } 'executed SQL on table in database one';
613
614                     $rel_info = try { $rsrc->relationship_info('mssql_loader_test14') };
615
616                     is_deeply $rel_info->{cond}, {
617                         'foreign.thirteen_id' => 'self.id'
618                     }, 'relationship in database one';
619
620                     is $rel_info->{attrs}{accessor}, 'single',
621                         'relationship in database one';
622
623                     is $rel_info->{attrs}{join_type}, 'LEFT',
624                         'relationship in database one';
625
626                     lives_and {
627                         ok $rsrc = $test_schema->source('DbicslTest1MssqlLoaderTest14');
628                     } 'got source for table in database one';
629
630                     %uniqs = try { $rsrc->unique_constraints };
631
632                     is keys %uniqs, 2,
633                         'got unique and primary constraint in database one';
634
635                     delete $uniqs{primary};
636
637                     is_deeply ((values %uniqs)[0], ['thirteen_id'],
638                         'correct unique constraint in database one');
639
640                     lives_and {
641                         ok $rsrc = $test_schema->source('MssqlLoaderTest15');
642                     } 'got source for table in database two';
643
644                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
645                         'column in database two introspected correctly';
646
647                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar',
648                         'column in database two introspected correctly';
649
650                     is try { $rsrc->column_info('value')->{size} }, 100,
651                         'column in database two introspected correctly';
652
653                     lives_and {
654                         ok $rs = $test_schema->resultset('MssqlLoaderTest15');
655                     } 'got resultset for table in database two';
656
657                     lives_and {
658                         ok $row = $rs->create({ value => 'foo' });
659                     } 'executed SQL on table in database two';
660
661                     $rel_info = try { $rsrc->relationship_info('mssql_loader_test16') };
662
663                     is_deeply $rel_info->{cond}, {
664                         'foreign.fifteen_id' => 'self.id'
665                     }, 'relationship in database two';
666
667                     is $rel_info->{attrs}{accessor}, 'single',
668                         'relationship in database two';
669
670                     is $rel_info->{attrs}{join_type}, 'LEFT',
671                         'relationship in database two';
672
673                     lives_and {
674                         ok $rsrc = $test_schema->source('MssqlLoaderTest16');
675                     } 'got source for table in database two';
676
677                     %uniqs = try { $rsrc->unique_constraints };
678
679                     is keys %uniqs, 2,
680                         'got unique and primary constraint in database two';
681
682                     delete $uniqs{primary};
683
684                     is_deeply ((values %uniqs)[0], ['fifteen_id'],
685                         'correct unique constraint in database two');
686                 }
687             }
688         },
689     },
690 );
691
692 $tester->run_tests();
693
694 sub cleanup_schemas {
695     return if $ENV{SCHEMA_LOADER_TESTS_NOCLEANUP};
696
697     # switch back to default database
698     $schema->storage->disconnect;
699     my $dbh = $schema->storage->dbh;
700
701     foreach my $table ('[dbicsl-test].mssql_loader_test12',
702                        '[dbicsl.test].mssql_loader_test11',
703                        '[dbicsl.test].mssql_loader_test10',
704                        '[dbicsl.test].mssql_loader_test9',
705                        '[dbicsl-test].mssql_loader_test9',
706                        '[dbicsl-test].mssql_loader_test8') {
707         try {
708             $dbh->do("DROP TABLE $table");
709         }
710         catch {
711             diag "Error dropping table: $_";
712         };
713     }
714
715     foreach my $db_schema (qw/dbicsl-test dbicsl.test/) {
716         try {
717             $dbh->do(qq{DROP SCHEMA [$db_schema]});
718         }
719         catch {
720             diag "Error dropping test schema $db_schema: $_";
721         };
722     }
723
724     rmtree EXTRA_DUMP_DIR;
725 }
726
727 sub cleanup_databases {
728     return if $ENV{SCHEMA_LOADER_TESTS_NOCLEANUP};
729
730     # for ADO
731     my $warn_handler = $SIG{__WARN__} || sub { warn @_ };
732     local $SIG{__WARN__} = sub {
733         $warn_handler->(@_) unless $_[0] =~ /Changed database context/;
734     };
735
736     my $dbh = $schema->storage->dbh;
737
738     $dbh->do('USE dbicsl_test1');
739
740     foreach my $table ('mssql_loader_test14',
741                        'mssql_loader_test13') {
742         try {
743             $dbh->do("DROP TABLE $table");
744         }
745         catch {
746             diag "Error dropping table: $_";
747         };
748     }
749
750     $dbh->do('USE dbicsl_test2');
751
752     foreach my $table ('mssql_loader_test16',
753                        'mssql_loader_test15',
754                        'mssql_loader_test14') {
755         try {
756             $dbh->do("DROP TABLE $table");
757         }
758         catch {
759             diag "Error dropping table: $_";
760         };
761     }
762
763     $dbh->do('USE master');
764
765     foreach my $database (qw/dbicsl_test1 dbicsl_test2/) {
766         try {
767             $dbh->do(qq{DROP DATABASE $database});
768         }
769         catch {
770             diag "Error dropping test database '$database': $_";
771         };
772     }
773
774     rmtree EXTRA_DUMP_DIR;
775 }
776 # vim:et sts=4 sw=4 tw=0: