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