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