Make sure Win32-like DBICTest checks are not tripped by repeated disconnects
[dbsrgits/DBIx-Class.git] / t / 86sqlt.t
1 use DBIx::Class::Optional::Dependencies -skip_all_without => 'deploy';
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Warn;
8 use Scalar::Util 'blessed';
9
10 use lib qw(t/lib);
11 use DBICTest;
12
13 my $custom_deployment_statements_called = 0;
14
15 sub DBICTest::Schema::deployment_statements {
16   $custom_deployment_statements_called = 1;
17   my $self = shift;
18   return $self->next::method(@_);
19 }
20
21 # Check deployment statements ctx sensitivity
22 {
23   my $schema = DBICTest->init_schema (no_deploy => 1, quote_names => 1);
24   my $not_first_table_creation_re = qr/CREATE TABLE "fourkeys_to_twokeys"/;
25
26   my $statements = $schema->deployment_statements;
27   like (
28     $statements,
29     $not_first_table_creation_re,
30     'All create statements returned in 1 string in scalar ctx'
31   );
32
33   my @statements = $schema->deployment_statements;
34   cmp_ok (scalar @statements, '>', 1, 'Multiple statement lines in array ctx');
35
36   my $i = 0;
37   while ($i <= $#statements) {
38     last if $statements[$i] =~ $not_first_table_creation_re;
39     $i++;
40   }
41
42   ok (
43     ($i > 0) && ($i <= $#statements),
44     "Creation statement was found somewherere within array ($i)"
45   );
46 }
47
48 {
49   # use our own throw-away schema, since we'll be deploying twice
50   my $schema = DBICTest->init_schema (no_deploy => 1);
51
52   my $deploy_hook_called = 0;
53   $custom_deployment_statements_called = 0;
54
55   # add a temporary sqlt_deploy_hook to a source
56   local $DBICTest::Schema::Track::hook_cb = sub {
57     my ($class, $sqlt_table) = @_;
58
59     $deploy_hook_called = 1;
60
61     is ($class, 'DBICTest::Track', 'Result class passed to plain hook');
62
63     is (
64       $sqlt_table->schema->translator->producer_type,
65       join ('::', 'SQL::Translator::Producer', $schema->storage->sqlt_type),
66       'Production type passed to translator object',
67     );
68   };
69
70   my $component_deploy_hook_called = 0;
71   local $DBICTest::DeployComponent::hook_cb = sub {
72     $component_deploy_hook_called = 1;
73   };
74
75   $schema->deploy; # do not remove, this fires the is() test in the callback above
76   ok($deploy_hook_called, 'deploy hook got called');
77   ok($custom_deployment_statements_called, '->deploy used the schemas deploy_statements method');
78   ok($component_deploy_hook_called, 'component deploy hook got called');
79 }
80
81 my $schema = DBICTest->init_schema (no_deploy => 1);
82
83 {
84   my $deploy_hook_called = 0;
85   $custom_deployment_statements_called = 0;
86   my $sqlt_type = $schema->storage->sqlt_type;
87
88   # replace the sqlt calback with a custom version ading an index
89   $schema->source('Track')->sqlt_deploy_callback(sub {
90     my ($self, $sqlt_table) = @_;
91
92     $deploy_hook_called = 1;
93
94     is (
95       $sqlt_table->schema->translator->producer_type,
96       join ('::', 'SQL::Translator::Producer', $sqlt_type),
97       'Production type passed to translator object',
98     );
99
100     if ($sqlt_type eq 'SQLite' ) {
101       $sqlt_table->add_index( name => 'track_title', fields => ['title'] )
102         or die $sqlt_table->error;
103     }
104
105     $self->default_sqlt_deploy_hook($sqlt_table);
106   });
107
108   $schema->deploy; # do not remove, this fires the is() test in the callback above
109   ok($deploy_hook_called, 'deploy hook got called');
110   ok($custom_deployment_statements_called, '->deploy used the schemas deploy_statements method');
111 }
112
113
114 my $translator = SQL::Translator->new(
115   parser_args => {
116     dbic_schema => $schema,
117   },
118   producer_args => {},
119 );
120
121 warnings_exist {
122     my $relinfo = $schema->source('Artist')->relationship_info ('cds');
123     local $relinfo->{attrs}{on_delete} = 'restrict';
124
125     $translator->parser('SQL::Translator::Parser::DBIx::Class');
126     $translator->producer('SQLite');
127
128     my $output = $translator->translate();
129
130     ok($output, "SQLT produced someoutput")
131       or diag($translator->error);
132
133 } [
134   (qr/SQLT attribute .+? was supplied for relationship .+? which does not appear to be a foreign constraint/) x 2
135 ], 'Warn about dubious on_delete/on_update attributes';
136
137 # Note that the constraints listed here are the only ones that are tested -- if
138 # more exist in the Schema than are listed here and all listed constraints are
139 # correct, the test will still pass. If you add a class with UNIQUE or FOREIGN
140 # KEY constraints to DBICTest::Schema, add tests here if you think the existing
141 # test coverage is not sufficient
142
143 my %fk_constraints = (
144
145   # TwoKeys
146   twokeys => [
147     {
148       'display' => 'twokeys->cd',
149       'name' => 'twokeys_fk_cd', 'index_name' => 'twokeys_idx_cd',
150       'selftable' => 'twokeys', 'foreigntable' => 'cd',
151       'selfcols'  => ['cd'], 'foreigncols' => ['cdid'],
152       'noindex'  => 1,
153       on_delete => '', on_update => '', deferrable => 0,
154     },
155     {
156       'display' => 'twokeys->artist',
157       'name' => 'twokeys_fk_artist', 'index_name' => 'twokeys_idx_artist',
158       'selftable' => 'twokeys', 'foreigntable' => 'artist',
159       'selfcols'  => ['artist'], 'foreigncols' => ['artistid'],
160       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
161     },
162   ],
163
164   # FourKeys_to_TwoKeys
165   fourkeys_to_twokeys => [
166     {
167       'display' => 'fourkeys_to_twokeys->twokeys',
168       'name' => 'fourkeys_to_twokeys_fk_t_artist_t_cd', 'index_name' => 'fourkeys_to_twokeys_idx_t_artist_t_cd',
169       'selftable' => 'fourkeys_to_twokeys', 'foreigntable' => 'twokeys',
170       'selfcols'  => ['t_artist', 't_cd'], 'foreigncols' => ['artist', 'cd'],
171       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
172     },
173     {
174       'display' => 'fourkeys_to_twokeys->fourkeys', 'index_name' => 'fourkeys_to_twokeys_idx_f_foo_f_bar_f_hello_f_goodbye',
175       'name' => 'fourkeys_to_twokeys_fk_f_foo_f_bar_f_hello_f_goodbye',
176       'selftable' => 'fourkeys_to_twokeys', 'foreigntable' => 'fourkeys',
177       'selfcols'  => [qw(f_foo f_bar f_hello f_goodbye)],
178       'foreigncols' => [qw(foo bar hello goodbye)],
179       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
180     },
181   ],
182
183   # CD_to_Producer
184   cd_to_producer => [
185     {
186       'display' => 'cd_to_producer->cd',
187       'name' => 'cd_to_producer_fk_cd', 'index_name' => 'cd_to_producer_idx_cd',
188       'selftable' => 'cd_to_producer', 'foreigntable' => 'cd',
189       'selfcols'  => ['cd'], 'foreigncols' => ['cdid'],
190       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
191     },
192     {
193       'display' => 'cd_to_producer->producer',
194       'name' => 'cd_to_producer_fk_producer', 'index_name' => 'cd_to_producer_idx_producer',
195       'selftable' => 'cd_to_producer', 'foreigntable' => 'producer',
196       'selfcols'  => ['producer'], 'foreigncols' => ['producerid'],
197       on_delete => '', on_update => '', deferrable => 1,
198     },
199   ],
200
201   # Self_ref_alias
202   self_ref_alias => [
203     {
204       'display' => 'self_ref_alias->self_ref for self_ref',
205       'name' => 'self_ref_alias_fk_self_ref', 'index_name' => 'self_ref_alias_idx_self_ref',
206       'selftable' => 'self_ref_alias', 'foreigntable' => 'self_ref',
207       'selfcols'  => ['self_ref'], 'foreigncols' => ['id'],
208       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
209     },
210     {
211       'display' => 'self_ref_alias->self_ref for alias',
212       'name' => 'self_ref_alias_fk_alias', 'index_name' => 'self_ref_alias_idx_alias',
213       'selftable' => 'self_ref_alias', 'foreigntable' => 'self_ref',
214       'selfcols'  => ['alias'], 'foreigncols' => ['id'],
215       on_delete => '', on_update => '', deferrable => 1,
216     },
217   ],
218
219   # CD
220   cd => [
221     {
222       'display' => 'cd->artist',
223       'name' => 'cd_fk_artist', 'index_name' => 'cd_idx_artist',
224       'selftable' => 'cd', 'foreigntable' => 'artist',
225       'selfcols'  => ['artist'], 'foreigncols' => ['artistid'],
226       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
227     },
228   ],
229
230   # Artist_undirected_map
231   artist_undirected_map => [
232     {
233       'display' => 'artist_undirected_map->artist for id1',
234       'name' => 'artist_undirected_map_fk_id1', 'index_name' => 'artist_undirected_map_idx_id1',
235       'selftable' => 'artist_undirected_map', 'foreigntable' => 'artist',
236       'selfcols'  => ['id1'], 'foreigncols' => ['artistid'],
237       on_delete => 'RESTRICT', on_update => 'CASCADE', deferrable => 1,
238     },
239     {
240       'display' => 'artist_undirected_map->artist for id2',
241       'name' => 'artist_undirected_map_fk_id2', 'index_name' => 'artist_undirected_map_idx_id2',
242       'selftable' => 'artist_undirected_map', 'foreigntable' => 'artist',
243       'selfcols'  => ['id2'], 'foreigncols' => ['artistid'],
244       on_delete => '', on_update => '', deferrable => 1,
245     },
246   ],
247
248   # Track
249   track => [
250     {
251       'display' => 'track->cd',
252       'name' => 'track_fk_cd', 'index_name' => 'track_idx_cd',
253       'selftable' => 'track', 'foreigntable' => 'cd',
254       'selfcols'  => ['cd'], 'foreigncols' => ['cdid'],
255       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
256     },
257   ],
258
259   # TreeLike
260   treelike => [
261     {
262       'display' => 'treelike->treelike for parent',
263       'name' => 'treelike_fk_parent', 'index_name' => 'treelike_idx_parent',
264       'selftable' => 'treelike', 'foreigntable' => 'treelike',
265       'selfcols'  => ['parent'], 'foreigncols' => ['id'],
266       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
267     },
268   ],
269
270   # TwoKeyTreeLike
271   twokeytreelike => [
272     {
273       'display' => 'twokeytreelike->twokeytreelike for parent1,parent2',
274       'name' => 'twokeytreelike_fk_parent1_parent2', 'index_name' => 'twokeytreelike_idx_parent1_parent2',
275       'selftable' => 'twokeytreelike', 'foreigntable' => 'twokeytreelike',
276       'selfcols'  => ['parent1', 'parent2'], 'foreigncols' => ['id1','id2'],
277       on_delete => '', on_update => '', deferrable => 1,
278     },
279   ],
280
281   # Tags
282   tags => [
283     {
284       'display' => 'tags->cd',
285       'name' => 'tags_fk_cd', 'index_name' => 'tags_idx_cd',
286       'selftable' => 'tags', 'foreigntable' => 'cd',
287       'selfcols'  => ['cd'], 'foreigncols' => ['cdid'],
288       on_delete => 'CASCADE', on_update => 'CASCADE', deferrable => 1,
289     },
290   ],
291
292   # Bookmark
293   bookmark => [
294     {
295       'display' => 'bookmark->link',
296       'name' => 'bookmark_fk_link', 'index_name' => 'bookmark_idx_link',
297       'selftable' => 'bookmark', 'foreigntable' => 'link',
298       'selfcols'  => ['link'], 'foreigncols' => ['id'],
299       on_delete => 'SET NULL', on_update => 'CASCADE', deferrable => 1,
300     },
301   ],
302   # ForceForeign
303   forceforeign => [
304     {
305       'display' => 'forceforeign->artist',
306       'name' => 'forceforeign_fk_artist', 'index_name' => 'forceforeign_idx_artist',
307       'selftable' => 'forceforeign', 'foreigntable' => 'artist',
308       'selfcols'  => ['artist'], 'foreigncols' => ['artistid'],
309       'noindex'  => 1,
310       on_delete => '', on_update => '', deferrable => 1,
311     },
312   ],
313 );
314
315 my %unique_constraints = (
316   # CD
317   cd => [
318     {
319       'display' => 'cd artist and title unique',
320       'name' => 'cd_artist_title',
321       'table' => 'cd', 'cols' => ['artist', 'title'],
322     },
323   ],
324
325   # Producer
326   producer => [
327     {
328       'display' => 'producer name unique',
329       'name' => 'prod_name', # explicit name
330       'table' => 'producer', 'cols' => ['name'],
331     },
332   ],
333
334   # TwoKeyTreeLike
335   twokeytreelike => [
336     {
337       'display' => 'twokeytreelike name unique',
338       'name' => 'tktlnameunique', # explicit name
339       'table' => 'twokeytreelike', 'cols'  => ['name'],
340     },
341   ],
342
343   # Employee
344 # Constraint is commented out in DBICTest/Schema/Employee.pm
345 #  employee => [
346 #    {
347 #      'display' => 'employee position and group_id unique',
348 #      'name' => 'position_group',
349 #      'table' => 'employee', cols => ['position', 'group_id'],
350 #    },
351 #  ],
352 );
353
354 my %indexes = (
355   artist => [
356     {
357       'fields' => ['name']
358     },
359   ],
360   track => [
361     {
362       'fields' => ['title']
363     }
364   ],
365 );
366
367 my $tschema = $translator->schema();
368 # Test that the $schema->sqlt_deploy_hook was called okay and that it removed
369 # the 'dummy' table
370 ok( !defined($tschema->get_table('dummy')), "Dummy table was removed by hook");
371
372 # Test that the Artist resultsource sqlt_deploy_hook was called okay and added
373 # an index
374 SKIP: {
375     skip ('Artist sqlt_deploy_hook is only called with an SQLite backend', 1)
376         if $schema->storage->sqlt_type ne 'SQLite';
377
378     ok( ( grep
379         { $_->name eq 'artist_name_hookidx' }
380         $tschema->get_table('artist')->get_indices
381     ), 'sqlt_deploy_hook fired within a resultsource');
382 }
383
384 # Test that nonexistent constraints are not found
385 my $constraint = get_constraint('FOREIGN KEY', 'cd', ['title'], 'cd', ['year']);
386 ok( !defined($constraint), 'nonexistent FOREIGN KEY constraint not found' );
387 $constraint = get_constraint('UNIQUE', 'cd', ['artist']);
388 ok( !defined($constraint), 'nonexistent UNIQUE constraint not found' );
389 $constraint = get_constraint('FOREIGN KEY', 'forceforeign', ['cd'], 'cd', ['cdid']);
390 ok( !defined($constraint), 'forced nonexistent FOREIGN KEY constraint not found' );
391
392 for my $expected_constraints (keys %fk_constraints) {
393   for my $expected_constraint (@{ $fk_constraints{$expected_constraints} }) {
394     my $desc = $expected_constraint->{display};
395     my $constraint = get_constraint(
396       'FOREIGN KEY',
397       $expected_constraint->{selftable}, $expected_constraint->{selfcols},
398       $expected_constraint->{foreigntable}, $expected_constraint->{foreigncols},
399     );
400     ok( defined($constraint), "FOREIGN KEY constraint matching `$desc' found" );
401     test_fk($expected_constraint, $constraint);
402   }
403 }
404
405 for my $expected_constraints (keys %unique_constraints) {
406   for my $expected_constraint (@{ $unique_constraints{$expected_constraints} }) {
407     my $desc = $expected_constraint->{display};
408     my $constraint = get_constraint(
409       'UNIQUE', $expected_constraint->{table}, $expected_constraint->{cols},
410     );
411     ok( defined($constraint), "UNIQUE constraint matching `$desc' found" );
412     test_unique($expected_constraint, $constraint);
413   }
414 }
415
416 for my $table_index (keys %indexes) {
417   for my $expected_index ( @{ $indexes{$table_index} } ) {
418     ok ( get_index($table_index, $expected_index), "Got a matching index on $table_index table");
419   }
420 }
421
422 # Returns the Constraint object for the specified constraint type, table and
423 # columns from the SQL::Translator schema, or undef if no matching constraint
424 # is found.
425 #
426 # NB: $type is either 'FOREIGN KEY' or 'UNIQUE'. In UNIQUE constraints the last
427 # two parameters are not used.
428 sub get_constraint {
429   my ($type, $table_name, $cols, $f_table, $f_cols) = @_;
430   $f_table ||= ''; # For UNIQUE constraints, reference_table is ''
431   $f_cols ||= [];
432
433   my $table = $tschema->get_table($table_name);
434
435   my %fields = map { $_ => 1 } @$cols;
436   my %f_fields = map { $_ => 1 } @$f_cols;
437
438   die "No $table_name" unless $table;
439  CONSTRAINT:
440   for my $constraint ( $table->get_constraints ) {
441     next unless $constraint->type eq $type;
442     next unless $constraint->reference_table eq $f_table;
443
444     my %rev_fields = map { $_ => 1 } $constraint->fields;
445     my %rev_f_fields = map { $_ => 1 } $constraint->reference_fields;
446
447     # Check that the given fields are a subset of the constraint's fields
448     for my $field ($constraint->fields) {
449       next CONSTRAINT unless $fields{$field};
450     }
451     if ($type eq 'FOREIGN KEY') {
452       for my $f_field ($constraint->reference_fields) {
453         next CONSTRAINT unless $f_fields{$f_field};
454       }
455     }
456
457     # Check that the constraint's fields are a subset of the given fields
458     for my $field (@$cols) {
459       next CONSTRAINT unless $rev_fields{$field};
460     }
461     if ($type eq 'FOREIGN KEY') {
462       for my $f_field (@$f_cols) {
463         next CONSTRAINT unless $rev_f_fields{$f_field};
464       }
465     }
466
467     return $constraint; # everything passes, found the constraint
468   }
469   return undef; # didn't find a matching constraint
470 }
471
472 sub get_index {
473   my ($table_name, $index) = @_;
474
475   my $table = $tschema->get_table($table_name);
476
477  CAND_INDEX:
478   for my $cand_index ( $table->get_indices ) {
479
480     next CAND_INDEX if $index->{name} && $cand_index->name ne $index->{name}
481                     || $index->{type} && $cand_index->type ne $index->{type};
482
483     my %idx_fields = map { $_ => 1 } $cand_index->fields;
484
485     for my $field ( @{ $index->{fields} } ) {
486       next CAND_INDEX unless $idx_fields{$field};
487     }
488
489     %idx_fields = map { $_ => 1 } @{$index->{fields}};
490     for my $field ( $cand_index->fields) {
491       next CAND_INDEX unless $idx_fields{$field};
492     }
493
494     return $cand_index;
495   }
496
497   return undef; # No matching idx
498 }
499
500 # Test parameters in a FOREIGN KEY constraint other than columns
501 sub test_fk {
502   my ($expected, $got) = @_;
503   my $desc = $expected->{display};
504   is( $got->name, $expected->{name},
505       "name parameter correct for '$desc'" );
506   is( $got->on_delete, $expected->{on_delete},
507       "on_delete parameter correct for '$desc'" );
508   is( $got->on_update, $expected->{on_update},
509       "on_update parameter correct for '$desc'" );
510   is( $got->deferrable, $expected->{deferrable},
511       "is_deferrable parameter correct for '$desc'" );
512
513   my $index = get_index( $got->table, { fields => $expected->{selfcols} } );
514
515   if ($expected->{noindex}) {
516       ok( !defined $index, "index doesn't for '$desc'" );
517   } else {
518       ok( defined $index, "index exists for '$desc'" );
519       is( $index->name, $expected->{index_name}, "index has correct name for '$desc'" );
520   }
521 }
522
523 sub test_unique {
524   my ($expected, $got) = @_;
525   my $desc = $expected->{display};
526   is( $got->name, $expected->{name},
527       "name parameter correct for '$desc'" );
528 }
529
530 done_testing;