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