added some perldoc
[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 # 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->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     foreach my $moniker (sort @monikers)
70     {
71         my $source = $dbicschema->source($moniker);
72
73         # Its possible to have multiple DBIC source using same table
74         next if $seen_tables{$source->name}++;
75
76         my $table = $schema->add_table(
77                                        name => $source->name,
78                                        type => 'TABLE',
79                                        ) || die $schema->error;
80         my $colcount = 0;
81         foreach my $col ($source->columns)
82         {
83             # assuming column_info in dbic is the same as DBI (?)
84             # data_type is a number, column_type is text?
85             my %colinfo = (
86               name => $col,
87               size => 0,
88               is_auto_increment => 0,
89               is_foreign_key => 0,
90               is_nullable => 0,
91               %{$source->column_info($col)}
92             );
93             if ($colinfo{is_nullable}) {
94               $colinfo{default} = '' unless exists $colinfo{default};
95             }
96             my $f = $table->add_field(%colinfo) || die $table->error;
97         }
98         $table->primary_key($source->primary_columns);
99
100         my @primary = $source->primary_columns;
101         my %unique_constraints = $source->unique_constraints;
102         foreach my $uniq (sort keys %unique_constraints) {
103             if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
104                 $table->add_constraint(
105                             type             => 'unique',
106                             name             => $uniq,
107                             fields           => $unique_constraints{$uniq}
108                 );
109             }
110         }
111
112         my @rels = $source->relationships();
113
114         my %created_FK_rels;
115
116         foreach my $rel (sort @rels)
117         {
118             my $rel_info = $source->relationship_info($rel);
119
120             # Ignore any rel cond that isn't a straight hash
121             next unless ref $rel_info->{cond} eq 'HASH';
122
123             my $othertable = $source->related_source($rel);
124             my $rel_table = $othertable->name;
125
126             # Get the key information, mapping off the foreign/self markers
127             my @cond = keys(%{$rel_info->{cond}});
128             my @refkeys = map {/^\w+\.(\w+)$/} @cond;
129             my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
130
131             if($rel_table)
132             {
133                 my $reverse_rels = $source->reverse_relationship_info($rel);
134                 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
135
136                 my $on_delete = '';
137                 my $on_update = '';
138
139                 if (defined $otherrelationship) {
140                     $on_delete = $otherrelationship->{'attrs'}->{cascade_delete} ? 'CASCADE' : '';
141                     $on_update = $otherrelationship->{'attrs'}->{cascade_copy} ? 'CASCADE' : '';
142                 }
143
144                 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
145
146                 # Make sure we dont create the same foreign key constraint twice
147                 my $key_test = join("\x00", @keys);
148
149                 #Decide if this is a foreign key based on whether the self
150                 #items are our primary columns.
151
152                 # If the sets are different, then we assume it's a foreign key from
153                 # us to another table.
154                 # OR: If is_foreign_key_constraint attr is explicity set (or set to false) on the relation
155                 next if ( exists $created_FK_rels{$rel_table}->{$key_test} );
156                 if ( exists $rel_info->{attrs}{is_foreign_key_constraint}) {
157                   # not is this attr set to 0 but definitely if set to 1
158                   next unless ($rel_info->{attrs}{is_foreign_key_constraint});
159                 } else {
160                   # not if might have
161                   # next if ($rel_info->{attrs}{accessor} eq 'single' && exists $rel_info->{attrs}{join_type} && uc($rel_info->{attrs}{join_type}) eq 'LEFT');
162                   # not sure about this one
163                   next if $source->compare_relationship_keys(\@keys, \@primary);
164                 }
165
166                 $created_FK_rels{$rel_table}->{$key_test} = 1;
167                 if (scalar(@keys)) {
168                   $table->add_constraint(
169                                     type             => 'foreign_key',
170                                     name             => join('_', $table->name, 'fk', @keys),
171                                     fields           => \@keys,
172                                     reference_fields => \@refkeys,
173                                     reference_table  => $rel_table,
174                                     on_delete        => $on_delete,
175                                     on_update        => $on_update,
176                                     (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
177                   );
178                     
179                   unless (exists $args->{add_fk_index} && ($args->{add_fk_index} == 0)) {
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                 
190         if ($source->result_class->can('sqlt_deploy_hook')) {
191           $source->result_class->sqlt_deploy_hook($table);
192         }
193     }
194
195     if ($dbicschema->can('sqlt_deploy_hook')) {
196       $dbicschema->sqlt_deploy_hook($schema);
197     }
198
199     return 1;
200 }
201
202 1;