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