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