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