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