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 SQL::Translator::Utils qw(debug normalize_name);
19 use base qw(Exporter);
21 @EXPORT_OK = qw(parse);
23 # -------------------------------------------------------------------
26 # setting parser_args => { add_fk_index => 0 } will prevent
27 # the auto-generation of an index for each FK.
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 # -------------------------------------------------------------------
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'};
39 die 'No DBIx::Class::Schema' unless ($dbicschema);
40 if (!ref $dbicschema) {
41 eval "use $dbicschema;";
42 die "Can't load $dbicschema ($@)" if($@);
45 my $schema = $tr->schema;
48 $schema->name( ref($dbicschema) . " v" . ($dbicschema->VERSION || '1.x'))
49 unless ($schema->name);
53 my @monikers = sort $dbicschema->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';
58 # limit monikers to those specified in
60 if ($ref eq 'ARRAY') {
61 $sources->{$_} = 1 for (@$limit_sources);
63 $sources = $limit_sources;
65 @monikers = grep { $sources->{$_} } @monikers;
69 foreach my $moniker (sort @monikers)
71 my $source = $dbicschema->source($moniker);
73 # Skip custom query sources
74 next if ref($source->name);
76 # Its possible to have multiple DBIC source using same table
77 next if $seen_tables{$source->name}++;
79 my $table = $schema->add_table(
80 name => $source->name,
82 ) || die $schema->error;
84 foreach my $col ($source->columns)
86 # assuming column_info in dbic is the same as DBI (?)
87 # data_type is a number, column_type is text?
91 is_auto_increment => 0,
94 %{$source->column_info($col)}
96 if ($colinfo{is_nullable}) {
97 $colinfo{default} = '' unless exists $colinfo{default};
99 my $f = $table->add_field(%colinfo) || die $table->error;
101 $table->primary_key($source->primary_columns);
103 my @primary = $source->primary_columns;
104 my %unique_constraints = $source->unique_constraints;
105 foreach my $uniq (sort keys %unique_constraints) {
106 if (!$source->compare_relationship_keys($unique_constraints{$uniq}, \@primary)) {
107 $table->add_constraint(
110 fields => $unique_constraints{$uniq}
115 my @rels = $source->relationships();
119 # global add_fk_index set in parser_args
120 my $add_fk_index = (exists $args->{add_fk_index} && ($args->{add_fk_index} == 0)) ? 0 : 1;
122 foreach my $rel (sort @rels)
124 my $rel_info = $source->relationship_info($rel);
126 # Ignore any rel cond that isn't a straight hash
127 next unless ref $rel_info->{cond} eq 'HASH';
129 my $othertable = $source->related_source($rel);
130 my $rel_table = $othertable->name;
132 my $reverse_rels = $source->reverse_relationship_info($rel);
133 my ($otherrelname, $otherrelationship) = each %{$reverse_rels};
135 # Force the order of @cond to match the order of ->add_columns
137 my %other_columns_idx = map {'foreign.'.$_ => ++$idx } $othertable->columns;
138 my @cond = sort { $other_columns_idx{$a} cmp $other_columns_idx{$b} } keys(%{$rel_info->{cond}});
140 # Get the key information, mapping off the foreign/self markers
141 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
142 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
144 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
147 #first it can be specified explicitly
148 if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
149 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
151 # it can not be multi
152 elsif ( $rel_info->{attrs}{accessor}
153 && $rel_info->{attrs}{accessor} eq 'multi' ) {
156 # if indeed single, check if all self.columns are our primary keys.
157 # this is supposed to indicate a has_one/might_have...
158 # where's the introspection!!?? :)
160 $fk_constraint = not $source->compare_relationship_keys(\@keys, \@primary);
164 for my $c (qw/delete update/) {
165 if (exists $rel_info->{attrs}{"on_$c"}) {
166 if ($fk_constraint) {
167 $cascade->{$c} = $rel_info->{attrs}{"on_$c"};
170 warn "SQLT attribute 'on_$c' was supplied for relationship '$moniker/$rel', which does not appear to be a foreign constraint. "
171 . "If you are sure that SQLT must generate a constraint for this relationship, add 'is_foreign_key_constraint => 1' to the attributes.\n";
174 elsif (defined $otherrelationship and $otherrelationship->{attrs}{$c eq 'update' ? 'cascade_copy' : 'cascade_delete'}) {
175 $cascade->{$c} = 'CASCADE';
181 # Constraints are added only if applicable
182 next unless $fk_constraint;
184 # Make sure we dont create the same foreign key constraint twice
185 my $key_test = join("\x00", @keys);
186 next if $created_FK_rels{$rel_table}->{$key_test};
188 my $is_deferrable = $rel_info->{attrs}{is_deferrable};
190 # global parser_args add_fk_index param can be overridden on the rel def
191 my $add_fk_index_rel = (exists $rel_info->{attrs}{add_fk_index}) ? $rel_info->{attrs}{add_fk_index} : $add_fk_index;
194 $created_FK_rels{$rel_table}->{$key_test} = 1;
196 $table->add_constraint(
197 type => 'foreign_key',
198 name => join('_', $table->name, 'fk', @keys),
200 reference_fields => \@refkeys,
201 reference_table => $rel_table,
202 on_delete => uc ($cascade->{delete} || ''),
203 on_update => uc ($cascade->{update} || ''),
204 (defined $is_deferrable ? ( deferrable => $is_deferrable ) : ()),
207 if ($add_fk_index_rel) {
208 my $index = $table->add_index(
209 name => join('_', $table->name, 'idx', @keys),
218 if ($source->result_class->can('sqlt_deploy_hook')) {
219 $source->result_class->sqlt_deploy_hook($table);
223 if ($dbicschema->can('sqlt_deploy_hook')) {
224 $dbicschema->sqlt_deploy_hook($schema);
234 SQL::Translator::Parser::DBIx::Class - Create a SQL::Translator schema
235 from a DBIx::Class::Schema instance
242 my $schema = MyApp::Schema->connect;
243 my $trans = SQL::Translator->new (
244 parser => 'SQL::Translator::Parser::DBIx::Class',
245 parser_args => { package => $schema },
246 producer => 'SQLite',
247 ) or die SQL::Translator->error;
248 my $out = $trans->translate() or die $trans->error;
252 C<SQL::Translator::Parser::DBIx::Class> reads a DBIx::Class schema,
253 interrogates the columns, and stuffs it all in an $sqlt_schema object.