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