Introduce ad hoc requirements and add skip_without method to optdeps
[dbsrgits/DBIx-Class.git] / t / 99dbic_sqlt_parser.t
1 use DBIx::Class::Optional::Dependencies -skip_all_without => 'deploy';
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Warn;
8 use Test::Exception;
9 use Scalar::Util ();
10
11 use lib qw(t/lib);
12 use DBICTest;
13 use DBIx::Class::_Util 'sigwarn_silencer';
14
15 # Test for SQLT-related leaks
16 {
17   my $s = DBICTest::Schema->clone;
18
19   my @schemas = (
20     create_schema ({ schema => $s }),
21     create_schema ({ args => { parser_args => { dbic_schema => $s } } }),
22   );
23
24   for my $parser_args_key (qw(
25     DBIx::Class::Schema
26     DBIx::Schema
27     package
28   )) {
29     warnings_exist {
30       push @schemas, create_schema({
31         args => { parser_args => { $parser_args_key => $s } }
32       });
33     } qr/\Qparser_args => {\E.+?is deprecated.+\Q@{[__FILE__]}/,
34     "deprecated crazy parser_arg '$parser_args_key' warned";
35   }
36
37   Scalar::Util::weaken ($s);
38
39   ok (!$s, 'Schema not leaked');
40
41   isa_ok ($_, 'SQL::Translator::Schema', "SQLT schema object $_ produced")
42     for @schemas;
43 }
44
45 # make sure classname-style works
46 lives_ok { isa_ok (create_schema ({ schema => 'DBICTest::Schema' }), 'SQL::Translator::Schema', 'SQLT schema object produced') };
47
48 # make sure a connected instance passed via $args does not get the $dbh improperly serialized
49 SKIP: {
50
51   DBIx::Class::Optional::Dependencies->skip_without( 'YAML>=0' );
52
53   lives_ok {
54
55     my $s = DBICTest->init_schema(no_populate => 1);
56     ok ($s->storage->connected, '$schema instance connected');
57
58     # roundtrip through YAML
59     my $yaml_rt_schema = SQL::Translator->new(
60       parser => 'SQL::Translator::Parser::YAML'
61     )->translate(
62       data => SQL::Translator->new(
63         parser_args => { dbic_schema => $s },
64         parser => 'SQL::Translator::Parser::DBIx::Class',
65         producer => 'SQL::Translator::Producer::YAML',
66       )->translate
67     );
68
69     isa_ok ( $yaml_rt_schema, 'SQL::Translator::Schema', 'SQLT schema object produced after YAML roundtrip');
70
71     ok ($s->storage->connected, '$schema instance still connected');
72   }
73
74   eval <<'EOE' or die $@;
75   END {
76     # we are in END - everything remains global
77     #
78     $^W = 1;  # important, otherwise DBI won't trip the next fail()
79     $SIG{__WARN__} = sub {
80       fail "Unexpected global destruction warning"
81         if $_[0] =~ /is not a DBI/;
82       warn @_;
83     };
84   }
85 EOE
86
87 }
88
89 my $schema = DBICTest->init_schema( no_deploy => 1 );
90
91 # Dummy was yanked out by the sqlt hook test
92 # CustomSql tests the horrific/deprecated ->name(\$sql) hack
93 # YearXXXXCDs are views
94 #
95 my @sources = grep
96   { $_ !~ /^ (?: Dummy | CustomSql | Year\d{4}CDs ) $/x }
97   $schema->sources
98 ;
99
100 my $idx_exceptions = {
101     'Artwork'       => -1,
102     'ForceForeign'  => -1,
103     'LinerNotes'    => -1,
104     'TwoKeys'       => -1, # TwoKeys has the index turned off on the rel def
105 };
106
107 {
108   my $sqlt_schema = create_schema({ schema => $schema, args => { parser_args => { } } });
109
110   foreach my $source_name (@sources) {
111     my $table = get_table($sqlt_schema, $schema, $source_name);
112
113     my $fk_count = scalar(grep { $_->type eq 'FOREIGN KEY' } $table->get_constraints);
114     $fk_count += $idx_exceptions->{$source_name} || 0;
115     my @indices = $table->get_indices;
116
117     my $index_count = scalar(@indices);
118     is($index_count, $fk_count, "correct number of indices for $source_name with no args");
119
120     for my $index (@indices) {
121         my $source = $schema->source($source_name);
122         my $pk_test = join("\x00", $source->primary_columns);
123         my $idx_test = join("\x00", $index->fields);
124         isnt ( $pk_test, $idx_test, "no additional index for the primary columns exists in $source_name");
125     }
126   }
127 }
128
129 {
130   my $sqlt_schema = create_schema({ schema => $schema, args => { parser_args => { add_fk_index => 1 } } });
131
132   foreach my $source_name (@sources) {
133     my $table = get_table($sqlt_schema, $schema, $source_name);
134
135     my $fk_count = scalar(grep { $_->type eq 'FOREIGN KEY' } $table->get_constraints);
136     $fk_count += $idx_exceptions->{$source_name} || 0;
137     my @indices = $table->get_indices;
138     my $index_count = scalar(@indices);
139     is($index_count, $fk_count, "correct number of indices for $source_name with add_fk_index => 1");
140   }
141 }
142
143 {
144   my $sqlt_schema = create_schema({ schema => $schema, args => { parser_args => { add_fk_index => 0 } } });
145
146   foreach my $source (@sources) {
147     my $table = get_table($sqlt_schema, $schema, $source);
148
149     my @indices = $table->get_indices;
150     my $index_count = scalar(@indices);
151     is($index_count, 0, "correct number of indices for $source with add_fk_index => 0");
152   }
153 }
154
155 {
156     {
157         package # hide from PAUSE
158             DBICTest::Schema::NoViewDefinition;
159
160         use base qw/DBICTest::BaseResult/;
161
162         __PACKAGE__->table_class('DBIx::Class::ResultSource::View');
163         __PACKAGE__->table('noviewdefinition');
164
165         1;
166     }
167
168     my $schema_invalid_view = $schema->clone;
169     $schema_invalid_view->register_class('NoViewDefinition', 'DBICTest::Schema::NoViewDefinition');
170
171     throws_ok { create_schema({ schema => $schema_invalid_view }) }
172         qr/view noviewdefinition is missing a view_definition/,
173         'parser detects views with a view_definition';
174 }
175
176 lives_ok (sub {
177   my $sqlt_schema = create_schema ({
178     schema => $schema,
179     args => {
180       parser_args => {
181         sources => ['CD']
182       },
183     },
184   });
185
186   is_deeply (
187     [$sqlt_schema->get_tables ],
188     ['cd'],
189     'sources limitng with relationships works',
190   );
191
192 });
193
194 {
195   package DBICTest::PartialSchema;
196
197   use base qw/DBIx::Class::Schema/;
198
199   __PACKAGE__->load_classes(
200     { 'DBICTest::Schema' => [qw/
201       CD
202       Track
203       Tag
204       Producer
205       CD_to_Producer
206     /]}
207   );
208 }
209
210 {
211   my $partial_schema = DBICTest::PartialSchema->connect(DBICTest->_database);
212
213   lives_ok (sub {
214     my $sqlt_schema = do {
215
216       local $SIG{__WARN__} = sigwarn_silencer(
217         qr/Ignoring relationship .+ related resultsource .+ is not registered with this schema/
218       );
219
220       create_schema({ schema => $partial_schema });
221     };
222
223     my @tables = $sqlt_schema->get_tables;
224
225     is_deeply (
226       [sort map { $_->name } @tables],
227       [qw/cd cd_to_producer producer tags track/],
228       'partial dbic schema parsing ok',
229     );
230
231     # the primary key is currently unnamed in sqlt - adding below
232     my %constraints_for_table = (
233       producer =>       [qw/prod_name                                                         /],
234       tags =>           [qw/tagid_cd tagid_cd_tag tags_fk_cd tags_tagid_tag tags_tagid_tag_cd /],
235       track =>          [qw/track_cd_position track_cd_title track_fk_cd                      /],
236       cd =>             [qw/cd_artist_title cd_fk_single_track                                /],
237       cd_to_producer => [qw/cd_to_producer_fk_cd cd_to_producer_fk_producer                   /],
238     );
239
240     for my $table (@tables) {
241       my $tablename = $table->name;
242       my @constraints = $table->get_constraints;
243       is_deeply (
244         [ sort map { $_->name } @constraints ],
245
246         # the primary key (present on all loaded tables) is currently named '' in sqlt
247         # subject to future changes
248         [ '', @{$constraints_for_table{$tablename}} ],
249
250         "constraints of table '$tablename' ok",
251       );
252     }
253   }, 'partial schema tests successful');
254 }
255
256 {
257   my $cd_rsrc = $schema->source('CD');
258   $cd_rsrc->name(\'main.cd');
259
260   my $sqlt_schema = create_schema(
261     { schema => $schema },
262     args => { ignore_constraint_names => 0, ignore_index_names => 0 }
263   );
264
265   foreach my $source_name (qw(CD)) {
266     my $table = get_table($sqlt_schema, $schema, $source_name);
267     ok(
268       !(grep {$_->name =~ m/main\./} $table->get_indices),
269       'indices have periods stripped out'
270     );
271     ok(
272       !(grep {$_->name =~ m/main\./} $table->get_constraints),
273       'constraints have periods stripped out'
274     );
275   }
276 }
277
278 done_testing;
279
280 sub create_schema {
281   my $args = shift;
282
283   my $additional_sqltargs = $args->{args} || {};
284
285   my $sqltargs = {
286     add_drop_table => 1,
287     ignore_constraint_names => 1,
288     ignore_index_names => 1,
289     %{$additional_sqltargs}
290   };
291
292   my $sqlt = SQL::Translator->new( $sqltargs );
293
294   $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
295   return $sqlt->translate(
296     $args->{schema} ? ( data => $args->{schema} ) : ()
297   ) || die $sqlt->error;
298 }
299
300 sub get_table {
301     my ($sqlt_schema, $schema, $source) = @_;
302
303     my $table_name = $schema->source($source)->from;
304     $table_name    = $$table_name if ref $table_name;
305
306     return $sqlt_schema->get_table($table_name);
307 }