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