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