Make sure pg test can restart after half-way failures
[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);
17
18use base qw(Exporter);
19
20@EXPORT_OK = qw(parse);
21
22# -------------------------------------------------------------------
23# parse($tr, $data)
24#
0e2c6809 25# setting parser_args => { add_fk_index => 0 } will prevent
26# the auto-generation of an index for each FK.
27#
880a1a0c 28# Note that $data, in the case of this parser, is not useful.
b02b20b5 29# We're working with DBIx::Class Schemas, not data streams.
30# -------------------------------------------------------------------
31sub parse {
499adf63 32 my ($tr, $data) = @_;
33 my $args = $tr->parser_args;
b7e303a8 34 my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data;
35 $dbicschema ||= $args->{'package'};
499adf63 36 my $limit_sources = $args->{'sources'};
b02b20b5 37
b7e303a8 38 die 'No DBIx::Class::Schema' unless ($dbicschema);
39 if (!ref $dbicschema) {
40 eval "use $dbicschema;";
41 die "Can't load $dbicschema ($@)" if($@);
b02b20b5 42 }
43
44 my $schema = $tr->schema;
45 my $table_no = 0;
46
b1f9d92e 47 $schema->name( ref($dbicschema) . " v" . ($dbicschema->schema_version || '1.x'))
b7e303a8 48 unless ($schema->name);
38e48163 49
50 my %seen_tables;
51
b7e303a8 52 my @monikers = sort $dbicschema->sources;
499adf63 53 if ($limit_sources) {
54 my $ref = ref $limit_sources || '';
5bdf1b3d 55 die "'sources' parameter must be an array or hash ref" 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
1d521afd 79 foreach my $moniker (sort @table_monikers)
b02b20b5 80 {
b7e303a8 81 my $source = $dbicschema->source($moniker);
90c11f68 82
83 # Skip custom query sources
84 next if ref($source->name);
b02b20b5 85
b7e303a8 86 # Its possible to have multiple DBIC source using same table
38e48163 87 next if $seen_tables{$source->name}++;
88
b02b20b5 89 my $table = $schema->add_table(
90 name => $source->name,
91 type => 'TABLE',
92 ) || die $schema->error;
93 my $colcount = 0;
94 foreach my $col ($source->columns)
95 {
d6c79cb3 96 # assuming column_info in dbic is the same as DBI (?)
b02b20b5 97 # data_type is a number, column_type is text?
98 my %colinfo = (
99 name => $col,
b02b20b5 100 size => 0,
101 is_auto_increment => 0,
102 is_foreign_key => 0,
103 is_nullable => 0,
104 %{$source->column_info($col)}
105 );
0009fa49 106 if ($colinfo{is_nullable}) {
107 $colinfo{default} = '' unless exists $colinfo{default};
108 }
b02b20b5 109 my $f = $table->add_field(%colinfo) || die $table->error;
110 }
111 $table->primary_key($source->primary_columns);
112
7b90bb13 113 my @primary = $source->primary_columns;
114 my %unique_constraints = $source->unique_constraints;
b7e303a8 115 foreach my $uniq (sort keys %unique_constraints) {
de60a93d 116 if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
7b90bb13 117 $table->add_constraint(
118 type => 'unique',
a7e65bb5 119 name => $uniq,
7b90bb13 120 fields => $unique_constraints{$uniq}
121 );
122 }
123 }
124
b02b20b5 125 my @rels = $source->relationships();
499adf63 126
127 my %created_FK_rels;
2581038c 128
129 # global add_fk_index set in parser_args
130 my $add_fk_index = (exists $args->{add_fk_index} && ($args->{add_fk_index} == 0)) ? 0 : 1;
499adf63 131
454a5a42 132 foreach my $rel (sort @rels)
b02b20b5 133 {
134 my $rel_info = $source->relationship_info($rel);
637ca936 135
637ca936 136 # Ignore any rel cond that isn't a straight hash
137 next unless ref $rel_info->{cond} eq 'HASH';
138
de60a93d 139 my $othertable = $source->related_source($rel);
140 my $rel_table = $othertable->name;
141
e377d723 142 my $reverse_rels = $source->reverse_relationship_info($rel);
143 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
144
d1b264d3 145 # Force the order of @cond to match the order of ->add_columns
146 my $idx;
147 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $othertable->columns;
148 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
149
637ca936 150 # Get the key information, mapping off the foreign/self markers
637ca936 151 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
152 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
153
e377d723 154 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
155 my $fk_constraint;
de60a93d 156
e377d723 157 #first it can be specified explicitly
158 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
159 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
160 }
161 # it can not be multi
069e49b6 162 elsif ( $rel_info->{attrs}{accessor}
163 && $rel_info->{attrs}{accessor} eq 'multi' ) {
e377d723 164 $fk_constraint = 0;
165 }
166 # if indeed single, check if all self.columns are our primary keys.
167 # this is supposed to indicate a has_one/might_have...
168 # where's the introspection!!?? :)
169 else {
170 $fk_constraint = not $source->compare_relationship_keys(\@keys, \@primary);
171 }
de60a93d 172
e377d723 173 my $cascade;
174 for my $c (qw/delete update/) {
175 if (exists $rel_info->{attrs}{"on_$c"}) {
176 if ($fk_constraint) {
177 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
178 }
179 else {
180 warn "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
181 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
182 }
183 }
184 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
185 $cascade->{$c} = 'CASCADE';
de60a93d 186 }
e377d723 187 }
188
189 if($rel_table)
190 {
191 # Constraints are added only if applicable
192 next unless $fk_constraint;
193
194 # Make sure we dont create the same foreign key constraint twice
195 my $key_test = join("\x00", @keys);
196 next if $created_FK_rels{$rel_table}->{$key_test};
de60a93d 197
45f1a484 198 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
2581038c 199
200 # global parser_args add_fk_index param can be overridden on the rel def
201 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
13de943d 202
7b5d0b84 203
204 $created_FK_rels{$rel_table}->{$key_test} = 1;
205 if (scalar(@keys)) {
206 $table->add_constraint(
0d865134 207 type => 'foreign_key',
a7e65bb5 208 name => join('_', $table->name, 'fk', @keys),
0d865134 209 fields => \@keys,
210 reference_fields => \@refkeys,
211 reference_table => $rel_table,
555b3385 212 on_delete => uc ($cascade->{delete} || ''),
213 on_update => uc ($cascade->{update} || ''),
e394339b 214 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
7b5d0b84 215 );
0d865134 216
2581038c 217 if ($add_fk_index_rel) {
0e2c6809 218 my $index = $table->add_index(
219 name => join('_', $table->name, 'idx', @keys),
220 fields => \@keys,
221 type => 'NORMAL',
222 );
223 }
224 }
b02b20b5 225 }
226 }
0e2c6809 227
880c075b 228 $source->_invoke_sqlt_deploy_hook($table);
b02b20b5 229 }
d6c79cb3 230
1d521afd 231 foreach my $moniker (sort @view_monikers)
232 {
233 my $source = $dbicschema->source($moniker);
234 # Skip custom query sources
235 next if ref($source->name);
236
237 # Its possible to have multiple DBIC source using same table
238 next if $seen_tables{$source->name}++;
239
47344132 240 my $view = $schema->add_view(
1d521afd 241 name => $source->name,
242 fields => [ $source->columns ],
f534e33b 243 $source->view_definition ? ( 'sql' => $source->view_definition ) : ()
1d521afd 244 );
245 if ($source->result_class->can('sqlt_deploy_hook')) {
47344132 246 $source->result_class->sqlt_deploy_hook($view);
1d521afd 247 }
a99b214b 248
249 $source->_invoke_sqlt_deploy_hook($view);
1d521afd 250 }
251
b7e303a8 252 if ($dbicschema->can('sqlt_deploy_hook')) {
253 $dbicschema->sqlt_deploy_hook($schema);
d6c79cb3 254 }
255
637ca936 256 return 1;
75d07914 257}
b02b20b5 258
0da8b7da 2591;
7232ce07 260
261=head1 NAME
262
263SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
264from a DBIx::Class::Schema instance
265
266=head1 SYNOPSIS
267
f26d4b95 268 ## Via DBIx::Class
269 use MyApp::Schema;
270 my $schema = MyApp::Schema->connect("dbi:SQLite:something.db");
271 $schema->create_ddl_dir();
272 ## or
273 $schema->deploy();
274
275 ## Standalone
7232ce07 276 use MyApp::Schema;
277 use SQL::Translator;
278
279 my $schema = MyApp::Schema->connect;
280 my $trans = SQL::Translator->new (
281 parser => 'SQL::Translator::Parser::DBIx::Class',
282 parser_args => { package => $schema },
283 producer => 'SQLite',
284 ) or die SQL::Translator->error;
285 my $out = $trans->translate() or die $trans->error;
286
287=head1 DESCRIPTION
288
f26d4b95 289This class requires L<SQL::Translator> installed to work.
290
7232ce07 291C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
292interrogates the columns, and stuffs it all in an $sqlt_schema object.
293
f26d4b95 294It's primary use is in deploying database layouts described as a set
db2b2eb6 295of L<DBIx::Class> classes, to a database. To do this, see
296L<DBIx::Class::Schema/deploy>.
f26d4b95 297
298This can also be achieved by having DBIx::Class export the schema as a
299set of SQL files ready for import into your database, or passed to
300other machines that need to have your application installed but don't
db2b2eb6 301have SQL::Translator installed. To do this see
302L<DBIx::Class::Schema/create_ddl_dir>.
f26d4b95 303
7232ce07 304=head1 SEE ALSO
305
f26d4b95 306L<SQL::Translator>, L<DBIx::Class::Schema>
7232ce07 307
308=head1 AUTHORS
309
310Jess Robinson
311
312Matt S Trout
313
314Ash Berlin