Constraint/index name fix from rdj
[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 Digest::SHA1 qw( sha1_hex );
18 use SQL::Translator::Utils qw(debug normalize_name);
19
20 use base qw(Exporter);
21
22 @EXPORT_OK = qw(parse);
23
24 # -------------------------------------------------------------------
25 # parse($tr, $data)
26 #
27 # Note that $data, in the case of this parser, is not useful.
28 # We're working with DBIx::Class Schemas, not data streams.
29 # -------------------------------------------------------------------
30 sub parse {
31     my ($tr, $data)   = @_;
32     my $args          = $tr->parser_args;
33     my $dbicschema    = $args->{'DBIx::Class::Schema'} ||  $args->{"DBIx::Schema"} ||$data;
34     $dbicschema     ||= $args->{'package'};
35     my $limit_sources = $args->{'sources'};
36     
37     die 'No DBIx::Class::Schema' unless ($dbicschema);
38     if (!ref $dbicschema) {
39       eval "use $dbicschema;";
40       die "Can't load $dbicschema ($@)" if($@);
41     }
42
43     my $schema      = $tr->schema;
44     my $table_no    = 0;
45
46     $schema->name( ref($dbicschema) . " v" . ($dbicschema->VERSION || '1.x'))
47       unless ($schema->name);
48
49     my %seen_tables;
50
51     my @monikers = sort $dbicschema->sources;
52     if ($limit_sources) {
53         my $ref = ref $limit_sources || '';
54         die "'sources' parameter must be an array or hash ref" unless $ref eq 'ARRAY' || ref eq 'HASH';
55
56         # limit monikers to those specified in 
57         my $sources;
58         if ($ref eq 'ARRAY') {
59             $sources->{$_} = 1 for (@$limit_sources);
60         } else {
61             $sources = $limit_sources;
62         }
63         @monikers = grep { $sources->{$_} } @monikers;
64     }
65
66
67     foreach my $moniker (sort @monikers)
68     {
69         my $source = $dbicschema->source($moniker);
70
71         # Its possible to have multiple DBIC source using same table
72         next if $seen_tables{$source->name}++;
73
74         my $table = $schema->add_table(
75                                        name => $source->name,
76                                        type => 'TABLE',
77                                        ) || die $schema->error;
78         my $colcount = 0;
79         foreach my $col ($source->columns)
80         {
81             # assuming column_info in dbic is the same as DBI (?)
82             # data_type is a number, column_type is text?
83             my %colinfo = (
84               name => $col,
85               size => 0,
86               is_auto_increment => 0,
87               is_foreign_key => 0,
88               is_nullable => 0,
89               %{$source->column_info($col)}
90             );
91             if ($colinfo{is_nullable}) {
92               $colinfo{default} = '' unless exists $colinfo{default};
93             }
94             my $f = $table->add_field(%colinfo) || die $table->error;
95         }
96         $table->primary_key($source->primary_columns);
97
98         my @primary = $source->primary_columns;
99         foreach my $field (@primary) {
100           my $index = $table->add_index(
101                                         name   => $field,
102                                         fields => [$field],
103                                         type   => 'NORMAL',
104                                        );
105         }
106         my %unique_constraints = $source->unique_constraints;
107         foreach my $uniq (sort keys %unique_constraints) {
108             if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
109                 $table->add_constraint(
110                             type             => 'unique',
111                             name             => _create_unique_symbol($uniq),
112                             fields           => $unique_constraints{$uniq}
113                 );
114
115                my $index = $table->add_index(
116                             name   => _create_unique_symbol(join('_', @{$unique_constraints{$uniq}})),
117                             fields => $unique_constraints{$uniq},
118                             type   => 'NORMAL',
119                );
120
121             }
122         }
123
124         my @rels = $source->relationships();
125
126         my %created_FK_rels;
127
128         foreach my $rel (sort @rels)
129         {
130             my $rel_info = $source->relationship_info($rel);
131
132             # Ignore any rel cond that isn't a straight hash
133             next unless ref $rel_info->{cond} eq 'HASH';
134
135             my $othertable = $source->related_source($rel);
136             my $rel_table = $othertable->name;
137
138             # Get the key information, mapping off the foreign/self markers
139             my @cond = keys(%{$rel_info->{cond}});
140             my @refkeys = map {/^\w+\.(\w+)$/} @cond;
141             my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
142
143             if($rel_table)
144             {
145                 my $reverse_rels = $source->reverse_relationship_info($rel);
146                 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
147
148                 my $on_delete = '';
149                 my $on_update = '';
150
151                 if (defined $otherrelationship) {
152                     $on_delete = $otherrelationship->{'attrs'}->{cascade_delete} ? 'CASCADE' : '';
153                     $on_update = $otherrelationship->{'attrs'}->{cascade_copy} ? 'CASCADE' : '';
154                 }
155
156                 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
157
158                 # Make sure we dont create the same foreign key constraint twice
159                 my $key_test = join("\x00", @keys);
160
161                 #Decide if this is a foreign key based on whether the self
162                 #items are our primary columns.
163
164                 # If the sets are different, then we assume it's a foreign key from
165                 # us to another table.
166                 # OR: If is_foreign_key_constraint attr is explicity set (or set to false) on the relation
167                 next if ( exists $created_FK_rels{$rel_table}->{$key_test} );
168                 if ( exists $rel_info->{attrs}{is_foreign_key_constraint}) {
169                   # not is this attr set to 0 but definitely if set to 1
170                   next unless ($rel_info->{attrs}{is_foreign_key_constraint});
171                 } else {
172                   # not if might have
173                   # next if ($rel_info->{attrs}{accessor} eq 'single' && exists $rel_info->{attrs}{join_type} && uc($rel_info->{attrs}{join_type}) eq 'LEFT');
174                   # not sure about this one
175                   next if $source->compare_relationship_keys(\@keys, \@primary);
176                 }
177
178                 $created_FK_rels{$rel_table}->{$key_test} = 1;
179                 if (scalar(@keys)) {
180                   $table->add_constraint(
181                                     type             => 'foreign_key',
182                                     name             => _create_unique_symbol($table->name
183                                                                             . '_fk_'
184                                                                             . join('_', @keys)),
185                                     fields           => \@keys,
186                                     reference_fields => \@refkeys,
187                                     reference_table  => $rel_table,
188                                     on_delete        => $on_delete,
189                                     on_update        => $on_update,
190                                     (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
191                   );
192                     
193                   my $index = $table->add_index(
194                                     name   => _create_unique_symbol(join('_', @keys)),
195                                     fields => \@keys,
196                                     type   => 'NORMAL',
197                   );
198                 }
199             }
200         }
201
202         if ($source->result_class->can('sqlt_deploy_hook')) {
203           $source->result_class->sqlt_deploy_hook($table);
204         }
205     }
206
207     if ($dbicschema->can('sqlt_deploy_hook')) {
208       $dbicschema->sqlt_deploy_hook($schema);
209     }
210
211     return 1;
212 }
213
214 # TODO - is there a reasonable way to pass configuration?
215 # Default of 64 comes from mysql's limit.
216 our $MAX_SYMBOL_LENGTH    ||= 64;
217 our $COLLISION_TAG_LENGTH ||= 8;
218
219 # -------------------------------------------------------------------
220 # $resolved_name = _create_unique_symbol($desired_name)
221 #
222 # If desired_name is really long, it will be truncated in a way that
223 # has a high probability of leaving it unique.
224 # -------------------------------------------------------------------
225 sub _create_unique_symbol {
226     my $desired_name = shift;
227     return $desired_name if length $desired_name <= $MAX_SYMBOL_LENGTH;
228
229     my $truncated_name = substr $desired_name, 0, $MAX_SYMBOL_LENGTH - $COLLISION_TAG_LENGTH - 1;
230
231     # Hex isn't the most space-efficient, but it skirts around allowed
232     # charset issues
233     my $digest = sha1_hex($desired_name);
234     my $collision_tag = substr $digest, 0, $COLLISION_TAG_LENGTH;
235
236     return $truncated_name
237          . '_'
238          . $collision_tag;
239 }
240
241 1;