Commit | Line | Data |
392cebac |
1 | package SQL::Translator::Parser::DBIx::Class; |
b02b20b5 |
2 | |
3 | # AUTHOR: Jess Robinson |
4 | |
1d996af5 |
5 | # Some mistakes the fault of Matt S Trout |
6 | |
c385ecea |
7 | # Others the fault of Ash Berlin |
8 | |
b02b20b5 |
9 | use strict; |
10 | use warnings; |
f9cc85ce |
11 | our ($DEBUG, $VERSION, @EXPORT_OK); |
4a9f6cdc |
12 | $VERSION = '1.10'; |
b02b20b5 |
13 | $DEBUG = 0 unless defined $DEBUG; |
ebed3aaf |
14 | |
b02b20b5 |
15 | use Exporter; |
b02b20b5 |
16 | use SQL::Translator::Utils qw(debug normalize_name); |
70c28808 |
17 | use DBIx::Class::Carp qw/^SQL::Translator|^DBIx::Class|^Try::Tiny/; |
18 | use DBIx::Class::Exception; |
7536c92b |
19 | use Scalar::Util 'blessed'; |
9780718f |
20 | use Try::Tiny; |
fd323bf1 |
21 | use namespace::clean; |
b02b20b5 |
22 | |
23 | use base qw(Exporter); |
24 | |
25 | @EXPORT_OK = qw(parse); |
26 | |
27 | # ------------------------------------------------------------------- |
28 | # parse($tr, $data) |
29 | # |
0e2c6809 |
30 | # setting parser_args => { add_fk_index => 0 } will prevent |
31 | # the auto-generation of an index for each FK. |
32 | # |
880a1a0c |
33 | # Note that $data, in the case of this parser, is not useful. |
b02b20b5 |
34 | # We're working with DBIx::Class Schemas, not data streams. |
35 | # ------------------------------------------------------------------- |
36 | sub parse { |
499adf63 |
37 | my ($tr, $data) = @_; |
38 | my $args = $tr->parser_args; |
b7e303a8 |
39 | my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data; |
40 | $dbicschema ||= $args->{'package'}; |
499adf63 |
41 | my $limit_sources = $args->{'sources'}; |
48850f9a |
42 | |
70c28808 |
43 | DBIx::Class::Exception->throw('No DBIx::Class::Schema') unless ($dbicschema); |
b7e303a8 |
44 | if (!ref $dbicschema) { |
5b9ecfcc |
45 | eval "require $dbicschema" |
70c28808 |
46 | or DBIx::Class::Exception->throw("Can't load $dbicschema: $@"); |
b02b20b5 |
47 | } |
48 | |
49 | my $schema = $tr->schema; |
50 | my $table_no = 0; |
51 | |
b1f9d92e |
52 | $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x')) |
b7e303a8 |
53 | unless ($schema->name); |
38e48163 |
54 | |
b7e303a8 |
55 | my @monikers = sort $dbicschema->sources; |
499adf63 |
56 | if ($limit_sources) { |
57 | my $ref = ref $limit_sources || ''; |
eb0bc670 |
58 | $dbicschema->throw_exception ("'sources' parameter must be an array or hash ref") |
59 | unless( $ref eq 'ARRAY' || ref eq 'HASH' ); |
499adf63 |
60 | |
fd323bf1 |
61 | # limit monikers to those specified in |
499adf63 |
62 | my $sources; |
63 | if ($ref eq 'ARRAY') { |
64 | $sources->{$_} = 1 for (@$limit_sources); |
65 | } else { |
66 | $sources = $limit_sources; |
67 | } |
68 | @monikers = grep { $sources->{$_} } @monikers; |
69 | } |
70 | |
71 | |
a7f4b74c |
72 | my(%table_monikers, %view_monikers); |
1d521afd |
73 | for my $moniker (@monikers){ |
74 | my $source = $dbicschema->source($moniker); |
5f5e87cf |
75 | if ( $source->isa('DBIx::Class::ResultSource::Table') ) { |
a7f4b74c |
76 | $table_monikers{$moniker}++; |
5f5e87cf |
77 | } elsif( $source->isa('DBIx::Class::ResultSource::View') ){ |
bccd177f |
78 | next if $source->is_virtual; |
a7f4b74c |
79 | $view_monikers{$moniker}++; |
1d521afd |
80 | } |
81 | } |
499adf63 |
82 | |
48850f9a |
83 | my %tables; |
a7f4b74c |
84 | foreach my $moniker (sort keys %table_monikers) |
b02b20b5 |
85 | { |
b7e303a8 |
86 | my $source = $dbicschema->source($moniker); |
48850f9a |
87 | my $table_name = $source->name; |
39be4120 |
88 | |
4678e9da |
89 | # FIXME - this isn't the right way to do it, but sqlt does not |
90 | # support quoting properly to be signaled about this |
a8fcfb9f |
91 | $table_name = $$table_name if ref $table_name eq 'SCALAR'; |
b02b20b5 |
92 | |
e3d5a547 |
93 | # It's possible to have multiple DBIC sources using the same table |
48850f9a |
94 | next if $tables{$table_name}; |
38e48163 |
95 | |
48850f9a |
96 | $tables{$table_name}{source} = $source; |
97 | my $table = $tables{$table_name}{object} = SQL::Translator::Schema::Table->new( |
98 | name => $table_name, |
b02b20b5 |
99 | type => 'TABLE', |
48850f9a |
100 | ); |
b02b20b5 |
101 | foreach my $col ($source->columns) |
102 | { |
d6c79cb3 |
103 | # assuming column_info in dbic is the same as DBI (?) |
b02b20b5 |
104 | # data_type is a number, column_type is text? |
105 | my %colinfo = ( |
106 | name => $col, |
b02b20b5 |
107 | size => 0, |
108 | is_auto_increment => 0, |
109 | is_foreign_key => 0, |
110 | is_nullable => 0, |
111 | %{$source->column_info($col)} |
112 | ); |
0009fa49 |
113 | if ($colinfo{is_nullable}) { |
114 | $colinfo{default} = '' unless exists $colinfo{default}; |
115 | } |
eb0bc670 |
116 | my $f = $table->add_field(%colinfo) |
117 | || $dbicschema->throw_exception ($table->error); |
b02b20b5 |
118 | } |
b02b20b5 |
119 | |
7b90bb13 |
120 | my @primary = $source->primary_columns; |
36e9e24f |
121 | |
122 | $table->primary_key(@primary) if @primary; |
123 | |
7b90bb13 |
124 | my %unique_constraints = $source->unique_constraints; |
b7e303a8 |
125 | foreach my $uniq (sort keys %unique_constraints) { |
6d0ee587 |
126 | if (!$source->_compare_relationship_keys($unique_constraints{$uniq}, \@primary)) { |
7b90bb13 |
127 | $table->add_constraint( |
128 | type => 'unique', |
a7e65bb5 |
129 | name => $uniq, |
7b90bb13 |
130 | fields => $unique_constraints{$uniq} |
131 | ); |
132 | } |
133 | } |
134 | |
b02b20b5 |
135 | my @rels = $source->relationships(); |
499adf63 |
136 | |
137 | my %created_FK_rels; |
48850f9a |
138 | |
2581038c |
139 | # global add_fk_index set in parser_args |
a7f4b74c |
140 | my $add_fk_index = (exists $args->{add_fk_index} && ! $args->{add_fk_index}) ? 0 : 1; |
499adf63 |
141 | |
454a5a42 |
142 | foreach my $rel (sort @rels) |
b02b20b5 |
143 | { |
a7f4b74c |
144 | |
b02b20b5 |
145 | my $rel_info = $source->relationship_info($rel); |
637ca936 |
146 | |
637ca936 |
147 | # Ignore any rel cond that isn't a straight hash |
148 | next unless ref $rel_info->{cond} eq 'HASH'; |
149 | |
5b9ecfcc |
150 | my $relsource = try { $source->related_source($rel) }; |
151 | unless ($relsource) { |
2ad0cbfb |
152 | carp "Ignoring relationship '$rel' - related resultsource '$rel_info->{class}' is not registered with this schema\n"; |
5b9ecfcc |
153 | next; |
154 | }; |
a7f4b74c |
155 | |
156 | # related sources might be excluded via a {sources} filter or might be views |
157 | next unless exists $table_monikers{$relsource->source_name}; |
158 | |
159 | my $rel_table = $relsource->name; |
4678e9da |
160 | |
161 | # FIXME - this isn't the right way to do it, but sqlt does not |
162 | # support quoting properly to be signaled about this |
163 | $rel_table = $$rel_table if ref $rel_table eq 'SCALAR'; |
de60a93d |
164 | |
e377d723 |
165 | my $reverse_rels = $source->reverse_relationship_info($rel); |
166 | my ($otherrelname, $otherrelationship) = each %{$reverse_rels}; |
167 | |
d1b264d3 |
168 | # Force the order of @cond to match the order of ->add_columns |
169 | my $idx; |
a7f4b74c |
170 | my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $relsource->columns; |
fd323bf1 |
171 | my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}}); |
48850f9a |
172 | |
637ca936 |
173 | # Get the key information, mapping off the foreign/self markers |
637ca936 |
174 | my @refkeys = map {/^\w+\.(\w+)$/} @cond; |
175 | my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond; |
176 | |
e377d723 |
177 | # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to) |
178 | my $fk_constraint; |
de60a93d |
179 | |
e377d723 |
180 | #first it can be specified explicitly |
181 | if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) { |
182 | $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint}; |
183 | } |
184 | # it can not be multi |
069e49b6 |
185 | elsif ( $rel_info->{attrs}{accessor} |
186 | && $rel_info->{attrs}{accessor} eq 'multi' ) { |
e377d723 |
187 | $fk_constraint = 0; |
188 | } |
189 | # if indeed single, check if all self.columns are our primary keys. |
190 | # this is supposed to indicate a has_one/might_have... |
191 | # where's the introspection!!?? :) |
192 | else { |
6d0ee587 |
193 | $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary); |
e377d723 |
194 | } |
de60a93d |
195 | |
e377d723 |
196 | my $cascade; |
197 | for my $c (qw/delete update/) { |
198 | if (exists $rel_info->{attrs}{"on_$c"}) { |
199 | if ($fk_constraint) { |
200 | $cascade->{$c} = $rel_info->{attrs}{"on_$c"}; |
201 | } |
db79c254 |
202 | elsif ( $rel_info->{attrs}{"on_$c"} ) { |
48850f9a |
203 | carp "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. " |
e377d723 |
204 | . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n"; |
205 | } |
206 | } |
207 | elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) { |
208 | $cascade->{$c} = 'CASCADE'; |
de60a93d |
209 | } |
e377d723 |
210 | } |
211 | |
cae467a7 |
212 | if($rel_table) { |
e377d723 |
213 | # Constraints are added only if applicable |
214 | next unless $fk_constraint; |
215 | |
216 | # Make sure we dont create the same foreign key constraint twice |
e3d5a547 |
217 | my $key_test = join("\x00", sort @keys); |
e377d723 |
218 | next if $created_FK_rels{$rel_table}->{$key_test}; |
de60a93d |
219 | |
48850f9a |
220 | if (scalar(@keys)) { |
48850f9a |
221 | $created_FK_rels{$rel_table}->{$key_test} = 1; |
13de943d |
222 | |
48850f9a |
223 | my $is_deferrable = $rel_info->{attrs}{is_deferrable}; |
224 | |
a7f4b74c |
225 | # calculate dependencies: do not consider deferrable constraints and |
226 | # self-references for dependency calculations |
48850f9a |
227 | if (! $is_deferrable and $rel_table ne $table_name) { |
228 | $tables{$table_name}{foreign_table_deps}{$rel_table}++; |
229 | } |
7b5d0b84 |
230 | |
7b5d0b84 |
231 | $table->add_constraint( |
cae467a7 |
232 | type => 'foreign_key', |
233 | name => join('_', $table_name, 'fk', @keys), |
234 | fields => \@keys, |
235 | reference_fields => \@refkeys, |
236 | reference_table => $rel_table, |
237 | on_delete => uc ($cascade->{delete} || ''), |
238 | on_update => uc ($cascade->{update} || ''), |
239 | (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()), |
7b5d0b84 |
240 | ); |
48850f9a |
241 | |
242 | # global parser_args add_fk_index param can be overridden on the rel def |
243 | my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index; |
244 | |
c49ff507 |
245 | # Check that we do not create an index identical to the PK index |
246 | # (some RDBMS croak on this, and it generally doesn't make much sense) |
247 | # NOTE: we do not sort the key columns because the order of |
5930bfc2 |
248 | # columns is important for indexes and two indexes with the |
249 | # same cols but different order are allowed and sometimes |
250 | # needed |
c49ff507 |
251 | next if join("\x00", @keys) eq join("\x00", @primary); |
48850f9a |
252 | |
2581038c |
253 | if ($add_fk_index_rel) { |
0e2c6809 |
254 | my $index = $table->add_index( |
5930bfc2 |
255 | name => join('_', $table_name, 'idx', @keys), |
256 | fields => \@keys, |
257 | type => 'NORMAL', |
258 | ); |
0e2c6809 |
259 | } |
260 | } |
b02b20b5 |
261 | } |
262 | } |
48850f9a |
263 | |
b02b20b5 |
264 | } |
d6c79cb3 |
265 | |
48850f9a |
266 | # attach the tables to the schema in dependency order |
267 | my $dependencies = { |
268 | map { $_ => _resolve_deps ($_, \%tables) } (keys %tables) |
269 | }; |
9485509b |
270 | |
48850f9a |
271 | for my $table (sort |
272 | { |
273 | keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} } |
274 | || |
275 | $a cmp $b |
276 | } |
277 | (keys %tables) |
278 | ) { |
279 | $schema->add_table ($tables{$table}{object}); |
280 | $tables{$table}{source} -> _invoke_sqlt_deploy_hook( $tables{$table}{object} ); |
48850f9a |
281 | |
7adc2091 |
282 | # the hook might have already removed the table |
283 | if ($schema->get_table($table) && $table =~ /^ \s* \( \s* SELECT \s+/ix) { |
5b9ecfcc |
284 | carp <<'EOW'; |
a8fcfb9f |
285 | |
7adc2091 |
286 | Custom SQL through ->name(\'( SELECT ...') is DEPRECATED, for more details see |
287 | "Arbitrary SQL through a custom ResultSource" in DBIx::Class::Manual::Cookbook |
288 | or http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod |
39be4120 |
289 | |
7adc2091 |
290 | EOW |
39be4120 |
291 | |
7adc2091 |
292 | # remove the table as there is no way someone might want to |
293 | # actually deploy this |
294 | $schema->drop_table ($table); |
39be4120 |
295 | } |
296 | } |
48850f9a |
297 | |
298 | my %views; |
51b31bbe |
299 | my @views = map { $dbicschema->source($_) } keys %view_monikers; |
9485509b |
300 | |
c418c5cc |
301 | my $view_dependencies = { |
302 | map { |
a8cbaf38 |
303 | $_ => _resolve_deps( $dbicschema->source($_), \%view_monikers ) |
c418c5cc |
304 | } ( keys %view_monikers ) |
305 | }; |
51b31bbe |
306 | |
307 | my @view_sources = |
308 | sort { |
c418c5cc |
309 | keys %{ $view_dependencies->{ $a->source_name } || {} } <=> |
310 | keys %{ $view_dependencies->{ $b->source_name } || {} } |
51b31bbe |
311 | || $a->source_name cmp $b->source_name |
312 | } |
313 | map { $dbicschema->source($_) } |
314 | keys %view_monikers; |
1999a918 |
315 | |
943538a0 |
316 | foreach my $source (@view_sources) |
1d521afd |
317 | { |
48850f9a |
318 | my $view_name = $source->name; |
4678e9da |
319 | |
320 | # FIXME - this isn't the right way to do it, but sqlt does not |
321 | # support quoting properly to be signaled about this |
322 | $view_name = $$view_name if ref $view_name eq 'SCALAR'; |
48850f9a |
323 | |
1d521afd |
324 | # Skip custom query sources |
48850f9a |
325 | next if ref $view_name; |
1d521afd |
326 | |
327 | # Its possible to have multiple DBIC source using same table |
48850f9a |
328 | next if $views{$view_name}++; |
1d521afd |
329 | |
ab7e74aa |
330 | $dbicschema->throw_exception ("view $view_name is missing a view_definition") |
331 | unless $source->view_definition; |
8f1617e2 |
332 | |
48850f9a |
333 | my $view = $schema->add_view ( |
334 | name => $view_name, |
1d521afd |
335 | fields => [ $source->columns ], |
f534e33b |
336 | $source->view_definition ? ( 'sql' => $source->view_definition ) : () |
eb0bc670 |
337 | ) || $dbicschema->throw_exception ($schema->error); |
a99b214b |
338 | |
339 | $source->_invoke_sqlt_deploy_hook($view); |
1d521afd |
340 | } |
341 | |
48850f9a |
342 | |
b7e303a8 |
343 | if ($dbicschema->can('sqlt_deploy_hook')) { |
344 | $dbicschema->sqlt_deploy_hook($schema); |
d6c79cb3 |
345 | } |
346 | |
637ca936 |
347 | return 1; |
75d07914 |
348 | } |
b02b20b5 |
349 | |
48850f9a |
350 | # |
351 | # Quick and dirty dependency graph calculator |
352 | # |
353 | sub _resolve_deps { |
a8cbaf38 |
354 | my ( $question, $answers, $seen ) = @_; |
c418c5cc |
355 | my $ret = {}; |
51b31bbe |
356 | $seen ||= {}; |
a8cbaf38 |
357 | my @deps; |
51b31bbe |
358 | |
359 | # copy and bump all deps by one (so we can reconstruct the chain) |
360 | my %seen = map { $_ => $seen->{$_} + 1 } ( keys %$seen ); |
6c97a902 |
361 | if ( blessed($question) |
362 | && $question->isa('DBIx::Class::ResultSource::View') ) |
363 | { |
a8cbaf38 |
364 | $seen{ $question->result_class } = 1; |
365 | @deps = keys %{ $question->{deploy_depends_on} }; |
366 | } |
367 | else { |
368 | $seen{$question} = 1; |
369 | @deps = keys %{ $answers->{$question}{foreign_table_deps} }; |
370 | } |
371 | |
372 | for my $dep (@deps) { |
51b31bbe |
373 | if ( $seen->{$dep} ) { |
374 | return {}; |
375 | } |
a8cbaf38 |
376 | my $next_dep; |
51b31bbe |
377 | |
6c97a902 |
378 | if ( blessed($question) |
379 | && $question->isa('DBIx::Class::ResultSource::View') ) |
380 | { |
381 | no warnings 'uninitialized'; |
a8cbaf38 |
382 | my ($next_dep_source_name) = |
6c97a902 |
383 | grep { |
384 | $question->schema->source($_)->result_class eq $dep |
385 | && !( $question->schema->source($_) |
386 | ->isa('DBIx::Class::ResultSource::Table') ) |
387 | } @{ [ $question->schema->sources ] }; |
388 | return {} unless $next_dep_source_name; |
a8cbaf38 |
389 | $next_dep = $question->schema->source($next_dep_source_name); |
390 | } |
391 | else { |
392 | $next_dep = $dep; |
393 | } |
394 | my $subdeps = _resolve_deps( $next_dep, $answers, \%seen ); |
395 | $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps ); |
51b31bbe |
396 | ++$ret->{$dep}; |
397 | } |
398 | return $ret; |
399 | } |
400 | |
0da8b7da |
401 | 1; |
7232ce07 |
402 | |
403 | =head1 NAME |
404 | |
405 | SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema |
406 | from a DBIx::Class::Schema instance |
407 | |
408 | =head1 SYNOPSIS |
409 | |
f26d4b95 |
410 | ## Via DBIx::Class |
411 | use MyApp::Schema; |
412 | my $schema = MyApp::Schema->connect("dbi:SQLite:something.db"); |
413 | $schema->create_ddl_dir(); |
414 | ## or |
415 | $schema->deploy(); |
416 | |
417 | ## Standalone |
7232ce07 |
418 | use MyApp::Schema; |
419 | use SQL::Translator; |
d4daee7b |
420 | |
7232ce07 |
421 | my $schema = MyApp::Schema->connect; |
422 | my $trans = SQL::Translator->new ( |
423 | parser => 'SQL::Translator::Parser::DBIx::Class', |
37cb0de1 |
424 | parser_args => { |
425 | package => $schema, |
cae467a7 |
426 | add_fk_index => 0, |
37cb0de1 |
427 | sources => [qw/ |
428 | Artist |
429 | CD |
430 | /], |
431 | }, |
7232ce07 |
432 | producer => 'SQLite', |
433 | ) or die SQL::Translator->error; |
434 | my $out = $trans->translate() or die $trans->error; |
435 | |
436 | =head1 DESCRIPTION |
437 | |
f26d4b95 |
438 | This class requires L<SQL::Translator> installed to work. |
439 | |
7232ce07 |
440 | C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema, |
441 | interrogates the columns, and stuffs it all in an $sqlt_schema object. |
442 | |
faaba25f |
443 | Its primary use is in deploying database layouts described as a set |
db2b2eb6 |
444 | of L<DBIx::Class> classes, to a database. To do this, see |
445 | L<DBIx::Class::Schema/deploy>. |
f26d4b95 |
446 | |
447 | This can also be achieved by having DBIx::Class export the schema as a |
448 | set of SQL files ready for import into your database, or passed to |
449 | other machines that need to have your application installed but don't |
db2b2eb6 |
450 | have SQL::Translator installed. To do this see |
451 | L<DBIx::Class::Schema/create_ddl_dir>. |
f26d4b95 |
452 | |
cae467a7 |
453 | =head1 PARSER OPTIONS |
454 | |
455 | =head2 add_fk_index |
456 | |
457 | Create an index for each foreign key. |
ad91ed74 |
458 | Enabled by default, as having indexed foreign key columns is normally the |
459 | sensible thing to do. |
cae467a7 |
460 | |
461 | =head2 sources |
462 | |
463 | =over 4 |
464 | |
f0ac764e |
465 | =item Arguments: \@class_names |
cae467a7 |
466 | |
467 | =back |
ad91ed74 |
468 | |
469 | Limit the amount of parsed sources by supplying an explicit list of source names. |
cae467a7 |
470 | |
7232ce07 |
471 | =head1 SEE ALSO |
472 | |
f26d4b95 |
473 | L<SQL::Translator>, L<DBIx::Class::Schema> |
7232ce07 |
474 | |
17621379 |
475 | =head1 AUTHORS |
7232ce07 |
476 | |
17621379 |
477 | See L<DBIx::Class/CONTRIBUTORS>. |
7232ce07 |
478 | |
827a808f |
479 | =head1 LICENSE |
7232ce07 |
480 | |
827a808f |
481 | You may distribute this code under the same terms as Perl itself. |
7232ce07 |
482 | |
827a808f |
483 | =cut |