1 package # hide from PAUSE
2 SQL::Translator::Parser::DBIx::Class;
4 # AUTHOR: Jess Robinson
6 # Some mistakes the fault of Matt S Trout
8 # Others the fault of Ash Berlin
12 use vars qw($DEBUG @EXPORT_OK);
13 $DEBUG = 0 unless defined $DEBUG;
17 use Digest::SHA1 qw( sha1_hex );
18 use SQL::Translator::Utils qw(debug normalize_name);
20 use base qw(Exporter);
22 @EXPORT_OK = qw(parse);
24 # -------------------------------------------------------------------
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 # -------------------------------------------------------------------
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'};
37 die 'No DBIx::Class::Schema' unless ($dbicschema);
38 if (!ref $dbicschema) {
39 eval "use $dbicschema;";
40 die "Can't load $dbicschema ($@)" if($@);
43 my $schema = $tr->schema;
46 $schema->name( ref($dbicschema) . " v" . ($dbicschema->VERSION || '1.x'))
47 unless ($schema->name);
51 my @monikers = sort $dbicschema->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';
56 # limit monikers to those specified in
58 if ($ref eq 'ARRAY') {
59 $sources->{$_} = 1 for (@$limit_sources);
61 $sources = $limit_sources;
63 @monikers = grep { $sources->{$_} } @monikers;
67 foreach my $moniker (sort @monikers)
69 my $source = $dbicschema->source($moniker);
71 # Its possible to have multiple DBIC source using same table
72 next if $seen_tables{$source->name}++;
74 my $table = $schema->add_table(
75 name => $source->name,
77 ) || die $schema->error;
79 foreach my $col ($source->columns)
81 # assuming column_info in dbic is the same as DBI (?)
82 # data_type is a number, column_type is text?
86 is_auto_increment => 0,
89 %{$source->column_info($col)}
91 if ($colinfo{is_nullable}) {
92 $colinfo{default} = '' unless exists $colinfo{default};
94 my $f = $table->add_field(%colinfo) || die $table->error;
96 $table->primary_key($source->primary_columns);
98 my @primary = $source->primary_columns;
99 my %unique_constraints = $source->unique_constraints;
100 foreach my $uniq (sort keys %unique_constraints) {
101 if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
102 $table->add_constraint(
104 name => _create_unique_symbol($uniq),
105 fields => $unique_constraints{$uniq}
110 my @rels = $source->relationships();
114 foreach my $rel (sort @rels)
116 my $rel_info = $source->relationship_info($rel);
118 # Ignore any rel cond that isn't a straight hash
119 next unless ref $rel_info->{cond} eq 'HASH';
121 my $othertable = $source->related_source($rel);
122 my $rel_table = $othertable->name;
124 # Force the order of @cond to match the order of ->add_columns
126 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $othertable->columns;
127 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
129 # Get the key information, mapping off the foreign/self markers
130 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
131 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
135 my $reverse_rels = $source->reverse_relationship_info($rel);
136 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
141 if (defined $otherrelationship) {
142 $on_delete = $otherrelationship->{'attrs'}->{cascade_delete} ? 'CASCADE' : '';
143 $on_update = $otherrelationship->{'attrs'}->{cascade_copy} ? 'CASCADE' : '';
146 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
148 # Make sure we dont create the same foreign key constraint twice
149 my $key_test = join("\x00", @keys);
151 #Decide if this is a foreign key based on whether the self
152 #items are our primary columns.
154 # If the sets are different, then we assume it's a foreign key from
155 # us to another table.
156 # OR: If is_foreign_key_constraint attr is explicity set (or set to false) on the relation
157 next if ( exists $created_FK_rels{$rel_table}->{$key_test} );
158 if ( exists $rel_info->{attrs}{is_foreign_key_constraint}) {
159 # not is this attr set to 0 but definitely if set to 1
160 next unless ($rel_info->{attrs}{is_foreign_key_constraint});
163 # next if ($rel_info->{attrs}{accessor} eq 'single' && exists $rel_info->{attrs}{join_type} && uc($rel_info->{attrs}{join_type}) eq 'LEFT');
164 # not sure about this one
165 next if $source->compare_relationship_keys(\@keys, \@primary);
168 $created_FK_rels{$rel_table}->{$key_test} = 1;
170 $table->add_constraint(
171 type => 'foreign_key',
172 name => _create_unique_symbol($table->name
176 reference_fields => \@refkeys,
177 reference_table => $rel_table,
178 on_delete => $on_delete,
179 on_update => $on_update,
180 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
183 my $index = $table->add_index(
184 name => _create_unique_symbol(join('_', @keys)),
192 if ($source->result_class->can('sqlt_deploy_hook')) {
193 $source->result_class->sqlt_deploy_hook($table);
197 if ($dbicschema->can('sqlt_deploy_hook')) {
198 $dbicschema->sqlt_deploy_hook($schema);
204 # TODO - is there a reasonable way to pass configuration?
205 # Default of 64 comes from mysql's limit.
206 our $MAX_SYMBOL_LENGTH ||= 64;
207 our $COLLISION_TAG_LENGTH ||= 8;
209 # -------------------------------------------------------------------
210 # $resolved_name = _create_unique_symbol($desired_name)
212 # If desired_name is really long, it will be truncated in a way that
213 # has a high probability of leaving it unique.
214 # -------------------------------------------------------------------
215 sub _create_unique_symbol {
216 my $desired_name = shift;
217 return $desired_name if length $desired_name <= $MAX_SYMBOL_LENGTH;
219 my $truncated_name = substr $desired_name, 0, $MAX_SYMBOL_LENGTH - $COLLISION_TAG_LENGTH - 1;
221 # Hex isn't the most space-efficient, but it skirts around allowed
223 my $digest = sha1_hex($desired_name);
224 my $collision_tag = substr $digest, 0, $COLLISION_TAG_LENGTH;
226 return $truncated_name