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