Merge 'trunk' into 'replication_dedux'
[dbsrgits/DBIx-Class.git] / lib / SQL / Translator / Parser / DBIx / Class.pm
1 package # hide from PAUSE
2     SQL::Translator::Parser::DBIx::Class;
3
4 # AUTHOR: Jess Robinson
5
6 # Some mistakes the fault of Matt S Trout
7
8 # Others the fault of Ash Berlin
9
10 use strict;
11 use warnings;
12 use vars qw($DEBUG @EXPORT_OK);
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 # Note that $data, in the case of this parser, is not useful.
27 # We're working with DBIx::Class Schemas, not data streams.
28 # -------------------------------------------------------------------
29 sub parse {
30     my ($tr, $data)   = @_;
31     my $args          = $tr->parser_args;
32     my $dbicschema    = $args->{'DBIx::Class::Schema'} ||  $args->{"DBIx::Schema"} ||$data;
33     $dbicschema     ||= $args->{'package'};
34     my $limit_sources = $args->{'sources'};
35     
36     die 'No DBIx::Class::Schema' unless ($dbicschema);
37     if (!ref $dbicschema) {
38       eval "use $dbicschema;";
39       die "Can't load $dbicschema ($@)" if($@);
40     }
41
42     my $schema      = $tr->schema;
43     my $table_no    = 0;
44
45     $schema->name( ref($dbicschema) . " v" . ($dbicschema->VERSION || '1.x'))
46       unless ($schema->name);
47
48     my %seen_tables;
49
50     my @monikers = sort $dbicschema->sources;
51     if ($limit_sources) {
52         my $ref = ref $limit_sources || '';
53         die "'sources' parameter must be an array or hash ref" unless $ref eq 'ARRAY' || ref eq 'HASH';
54
55         # limit monikers to those specified in 
56         my $sources;
57         if ($ref eq 'ARRAY') {
58             $sources->{$_} = 1 for (@$limit_sources);
59         } else {
60             $sources = $limit_sources;
61         }
62         @monikers = grep { $sources->{$_} } @monikers;
63     }
64
65
66     foreach my $moniker (sort @monikers)
67     {
68         my $source = $dbicschema->source($moniker);
69
70         # Its possible to have multiple DBIC source using same table
71         next if $seen_tables{$source->name}++;
72
73         my $table = $schema->add_table(
74                                        name => $source->name,
75                                        type => 'TABLE',
76                                        ) || die $schema->error;
77         my $colcount = 0;
78         foreach my $col ($source->columns)
79         {
80             # assuming column_info in dbic is the same as DBI (?)
81             # data_type is a number, column_type is text?
82             my %colinfo = (
83               name => $col,
84               size => 0,
85               is_auto_increment => 0,
86               is_foreign_key => 0,
87               is_nullable => 0,
88               %{$source->column_info($col)}
89             );
90             if ($colinfo{is_nullable}) {
91               $colinfo{default} = '' unless exists $colinfo{default};
92             }
93             my $f = $table->add_field(%colinfo) || die $table->error;
94         }
95         $table->primary_key($source->primary_columns);
96
97         my @primary = $source->primary_columns;
98         my %unique_constraints = $source->unique_constraints;
99         foreach my $uniq (sort keys %unique_constraints) {
100             if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
101                 $table->add_constraint(
102                             type             => 'unique',
103                             name             => $uniq,
104                             fields           => $unique_constraints{$uniq}
105                 );
106             }
107         }
108
109         my @rels = $source->relationships();
110
111         my %created_FK_rels;
112
113         foreach my $rel (sort @rels)
114         {
115             my $rel_info = $source->relationship_info($rel);
116
117             # Ignore any rel cond that isn't a straight hash
118             next unless ref $rel_info->{cond} eq 'HASH';
119
120             my $othertable = $source->related_source($rel);
121             my $rel_table = $othertable->name;
122
123             # Force the order of @cond to match the order of ->add_columns
124             my $idx;
125             my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $othertable->columns;            
126             my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}}); 
127       
128             # Get the key information, mapping off the foreign/self markers
129             my @refkeys = map {/^\w+\.(\w+)$/} @cond;
130             my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
131
132             if($rel_table)
133             {
134                 my $reverse_rels = $source->reverse_relationship_info($rel);
135                 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
136
137                 my $on_delete = '';
138                 my $on_update = '';
139
140                 if (defined $otherrelationship) {
141                     $on_delete = $otherrelationship->{'attrs'}->{cascade_delete} ? 'CASCADE' : '';
142                     $on_update = $otherrelationship->{'attrs'}->{cascade_copy} ? 'CASCADE' : '';
143                 }
144
145                 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
146
147                 # Make sure we dont create the same foreign key constraint twice
148                 my $key_test = join("\x00", @keys);
149
150                 #Decide if this is a foreign key based on whether the self
151                 #items are our primary columns.
152
153                 # If the sets are different, then we assume it's a foreign key from
154                 # us to another table.
155                 # OR: If is_foreign_key_constraint attr is explicity set (or set to false) on the relation
156                 next if ( exists $created_FK_rels{$rel_table}->{$key_test} );
157                 if ( exists $rel_info->{attrs}{is_foreign_key_constraint}) {
158                   # not is this attr set to 0 but definitely if set to 1
159                   next unless ($rel_info->{attrs}{is_foreign_key_constraint});
160                 } else {
161                   # not if might have
162                   # next if ($rel_info->{attrs}{accessor} eq 'single' && exists $rel_info->{attrs}{join_type} && uc($rel_info->{attrs}{join_type}) eq 'LEFT');
163                   # not sure about this one
164                   next if $source->compare_relationship_keys(\@keys, \@primary);
165                 }
166
167                 $created_FK_rels{$rel_table}->{$key_test} = 1;
168                 if (scalar(@keys)) {
169                   $table->add_constraint(
170                                     type             => 'foreign_key',
171                                     name             => join('_', $table->name, 'fk', @keys),
172                                     fields           => \@keys,
173                                     reference_fields => \@refkeys,
174                                     reference_table  => $rel_table,
175                                     on_delete        => $on_delete,
176                                     on_update        => $on_update,
177                                     (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
178                   );
179                     
180                   my $index = $table->add_index(
181                                     name   => join('_', $table->name, 'idx', @keys),
182                                     fields => \@keys,
183                                     type   => 'NORMAL',
184                   );
185                 }
186             }
187         }
188
189         if ($source->result_class->can('sqlt_deploy_hook')) {
190           $source->result_class->sqlt_deploy_hook($table);
191         }
192     }
193
194     if ($dbicschema->can('sqlt_deploy_hook')) {
195       $dbicschema->sqlt_deploy_hook($schema);
196     }
197
198     return 1;
199 }
200
201 1;