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