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