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