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