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