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