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