Merge 'trunk' into 'replication_dedux'
[dbsrgits/DBIx-Class.git] / lib / SQL / Translator / Parser / DBIx / Class.pm
CommitLineData
75d07914 1package # hide from PAUSE
c0e7b4e5 2 SQL::Translator::Parser::DBIx::Class;
b02b20b5 3
4# AUTHOR: Jess Robinson
5
1d996af5 6# Some mistakes the fault of Matt S Trout
7
c385ecea 8# Others the fault of Ash Berlin
9
b02b20b5 10use strict;
11use warnings;
b7e303a8 12use vars qw($DEBUG @EXPORT_OK);
b02b20b5 13$DEBUG = 0 unless defined $DEBUG;
b02b20b5 14
15use Exporter;
16use Data::Dumper;
0da8b7da 17use Digest::SHA1 qw( sha1_hex );
b02b20b5 18use SQL::Translator::Utils qw(debug normalize_name);
19
20use base qw(Exporter);
21
22@EXPORT_OK = qw(parse);
23
24# -------------------------------------------------------------------
25# parse($tr, $data)
26#
880a1a0c 27# Note that $data, in the case of this parser, is not useful.
b02b20b5 28# We're working with DBIx::Class Schemas, not data streams.
29# -------------------------------------------------------------------
30sub parse {
499adf63 31 my ($tr, $data) = @_;
32 my $args = $tr->parser_args;
b7e303a8 33 my $dbicschema = $args->{'DBIx::Class::Schema'} || $args->{"DBIx::Schema"} ||$data;
34 $dbicschema ||= $args->{'package'};
499adf63 35 my $limit_sources = $args->{'sources'};
b02b20b5 36
b7e303a8 37 die 'No DBIx::Class::Schema' unless ($dbicschema);
38 if (!ref $dbicschema) {
39 eval "use $dbicschema;";
40 die "Can't load $dbicschema ($@)" if($@);
b02b20b5 41 }
42
43 my $schema = $tr->schema;
44 my $table_no = 0;
45
b7e303a8 46 $schema->name( ref($dbicschema) . " v" . ($dbicschema->VERSION || '1.x'))
47 unless ($schema->name);
38e48163 48
49 my %seen_tables;
50
b7e303a8 51 my @monikers = sort $dbicschema->sources;
499adf63 52 if ($limit_sources) {
53 my $ref = ref $limit_sources || '';
5bdf1b3d 54 die "'sources' parameter must be an array or hash ref" unless $ref eq 'ARRAY' || ref eq 'HASH';
499adf63 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
454a5a42 67 foreach my $moniker (sort @monikers)
b02b20b5 68 {
b7e303a8 69 my $source = $dbicschema->source($moniker);
b02b20b5 70
b7e303a8 71 # Its possible to have multiple DBIC source using same table
38e48163 72 next if $seen_tables{$source->name}++;
73
b02b20b5 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 {
d6c79cb3 81 # assuming column_info in dbic is the same as DBI (?)
b02b20b5 82 # data_type is a number, column_type is text?
83 my %colinfo = (
84 name => $col,
b02b20b5 85 size => 0,
86 is_auto_increment => 0,
87 is_foreign_key => 0,
88 is_nullable => 0,
89 %{$source->column_info($col)}
90 );
0009fa49 91 if ($colinfo{is_nullable}) {
92 $colinfo{default} = '' unless exists $colinfo{default};
93 }
b02b20b5 94 my $f = $table->add_field(%colinfo) || die $table->error;
95 }
96 $table->primary_key($source->primary_columns);
97
7b90bb13 98 my @primary = $source->primary_columns;
99 my %unique_constraints = $source->unique_constraints;
b7e303a8 100 foreach my $uniq (sort keys %unique_constraints) {
de60a93d 101 if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
7b90bb13 102 $table->add_constraint(
103 type => 'unique',
0da8b7da 104 name => _create_unique_symbol($uniq),
7b90bb13 105 fields => $unique_constraints{$uniq}
106 );
107 }
108 }
109
b02b20b5 110 my @rels = $source->relationships();
499adf63 111
112 my %created_FK_rels;
113
454a5a42 114 foreach my $rel (sort @rels)
b02b20b5 115 {
116 my $rel_info = $source->relationship_info($rel);
637ca936 117
637ca936 118 # Ignore any rel cond that isn't a straight hash
119 next unless ref $rel_info->{cond} eq 'HASH';
120
de60a93d 121 my $othertable = $source->related_source($rel);
122 my $rel_table = $othertable->name;
123
637ca936 124 # Get the key information, mapping off the foreign/self markers
89cf6a70 125 my @cond = keys(%{$rel_info->{cond}});
637ca936 126 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
89cf6a70 127
128 # Force the order of the referenced fields to be the same as
129 # ->add_columns method.
130 my $idx;
8871d4ad 131 my %other_columns_idx = map {$_ => ++$idx } $othertable->columns;
89cf6a70 132 @refkeys = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } @refkeys;
133
637ca936 134 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
135
136 if($rel_table)
75d07914 137 {
de60a93d 138 my $reverse_rels = $source->reverse_relationship_info($rel);
139 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
140
141 my $on_delete = '';
142 my $on_update = '';
143
144 if (defined $otherrelationship) {
145 $on_delete = $otherrelationship->{'attrs'}->{cascade_delete} ? 'CASCADE' : '';
146 $on_update = $otherrelationship->{'attrs'}->{cascade_copy} ? 'CASCADE' : '';
147 }
148
45f1a484 149 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
13de943d 150
499adf63 151 # Make sure we dont create the same foreign key constraint twice
152 my $key_test = join("\x00", @keys);
153
637ca936 154 #Decide if this is a foreign key based on whether the self
155 #items are our primary columns.
156
637ca936 157 # If the sets are different, then we assume it's a foreign key from
158 # us to another table.
3d618782 159 # OR: If is_foreign_key_constraint attr is explicity set (or set to false) on the relation
7b5d0b84 160 next if ( exists $created_FK_rels{$rel_table}->{$key_test} );
161 if ( exists $rel_info->{attrs}{is_foreign_key_constraint}) {
162 # not is this attr set to 0 but definitely if set to 1
163 next unless ($rel_info->{attrs}{is_foreign_key_constraint});
164 } else {
165 # not if might have
166 # next if ($rel_info->{attrs}{accessor} eq 'single' && exists $rel_info->{attrs}{join_type} && uc($rel_info->{attrs}{join_type}) eq 'LEFT');
167 # not sure about this one
168 next if $source->compare_relationship_keys(\@keys, \@primary);
169 }
170
171 $created_FK_rels{$rel_table}->{$key_test} = 1;
172 if (scalar(@keys)) {
173 $table->add_constraint(
0d865134 174 type => 'foreign_key',
0da8b7da 175 name => _create_unique_symbol($table->name
176 . '_fk_'
177 . join('_', @keys)),
0d865134 178 fields => \@keys,
179 reference_fields => \@refkeys,
180 reference_table => $rel_table,
181 on_delete => $on_delete,
28f21a8f 182 on_update => $on_update,
e394339b 183 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
7b5d0b84 184 );
0d865134 185
7b5d0b84 186 my $index = $table->add_index(
0da8b7da 187 name => _create_unique_symbol(join('_', @keys)),
0d865134 188 fields => \@keys,
189 type => 'NORMAL',
7b5d0b84 190 );
637ca936 191 }
b02b20b5 192 }
193 }
aaf2403d 194
195 if ($source->result_class->can('sqlt_deploy_hook')) {
196 $source->result_class->sqlt_deploy_hook($table);
197 }
b02b20b5 198 }
d6c79cb3 199
b7e303a8 200 if ($dbicschema->can('sqlt_deploy_hook')) {
201 $dbicschema->sqlt_deploy_hook($schema);
d6c79cb3 202 }
203
637ca936 204 return 1;
75d07914 205}
b02b20b5 206
0da8b7da 207# TODO - is there a reasonable way to pass configuration?
208# Default of 64 comes from mysql's limit.
209our $MAX_SYMBOL_LENGTH ||= 64;
210our $COLLISION_TAG_LENGTH ||= 8;
211
212# -------------------------------------------------------------------
213# $resolved_name = _create_unique_symbol($desired_name)
214#
215# If desired_name is really long, it will be truncated in a way that
216# has a high probability of leaving it unique.
217# -------------------------------------------------------------------
218sub _create_unique_symbol {
219 my $desired_name = shift;
220 return $desired_name if length $desired_name <= $MAX_SYMBOL_LENGTH;
de60a93d 221
0da8b7da 222 my $truncated_name = substr $desired_name, 0, $MAX_SYMBOL_LENGTH - $COLLISION_TAG_LENGTH - 1;
223
224 # Hex isn't the most space-efficient, but it skirts around allowed
225 # charset issues
226 my $digest = sha1_hex($desired_name);
227 my $collision_tag = substr $digest, 0, $COLLISION_TAG_LENGTH;
228
229 return $truncated_name
230 . '_'
231 . $collision_tag;
232}
233
2341;