1 package # hide from PAUSE
2 SQL::Translator::Parser::DBIx::Class;
4 # AUTHOR: Jess Robinson
6 # Some mistakes the fault of Matt S Trout
10 use vars qw($DEBUG $VERSION @EXPORT_OK);
11 $DEBUG = 0 unless defined $DEBUG;
12 $VERSION = sprintf "%d.%02d", q$Revision 1.0$ =~ /(\d+)\.(\d+)/;
16 use SQL::Translator::Utils qw(debug normalize_name);
18 use base qw(Exporter);
20 @EXPORT_OK = qw(parse);
22 # -------------------------------------------------------------------
25 # Note that $data, in the case of this parser, is not useful.
26 # We're working with DBIx::Class Schemas, not data streams.
27 # -------------------------------------------------------------------
30 my $args = $tr->parser_args;
31 my $dbixschema = $args->{'DBIx::Schema'} || $data;
32 $dbixschema ||= $args->{'package'};
34 die 'No DBIx::Schema' unless ($dbixschema);
35 if (!ref $dbixschema) {
36 eval "use $dbixschema;";
37 die "Can't load $dbixschema ($@)" if($@);
40 my $schema = $tr->schema;
43 # print Dumper($dbixschema->registered_classes);
45 #foreach my $tableclass ($dbixschema->registered_classes)
46 foreach my $moniker ($dbixschema->sources)
48 #eval "use $tableclass";
49 #print("Can't load $tableclass"), next if($@);
50 my $source = $dbixschema->source($moniker);
52 my $table = $schema->add_table(
53 name => $source->name,
55 ) || die $schema->error;
57 foreach my $col ($source->columns)
59 # assuming column_info in dbix is the same as DBI (?)
60 # data_type is a number, column_type is text?
64 is_auto_increment => 0,
67 %{$source->column_info($col)}
69 if ($colinfo{is_nullable}) {
70 $colinfo{default} = '' unless exists $colinfo{default};
72 my $f = $table->add_field(%colinfo) || die $table->error;
74 $table->primary_key($source->primary_columns);
76 my @rels = $source->relationships();
77 foreach my $rel (@rels)
79 my $rel_info = $source->relationship_info($rel);
81 my $rel_table = $source->related_source($rel)->name;
83 # Ignore any rel cond that isn't a straight hash
84 next unless ref $rel_info->{cond} eq 'HASH';
86 # Get the key information, mapping off the foreign/self markers
87 my @cond = keys(%{$rel_info->{cond}});
88 my @refkeys = map {/^\w+\.(\w+)$/} @cond;
89 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} @cond;
94 #Decide if this is a foreign key based on whether the self
95 #items are our primary columns.
97 # Make sure every self key is in the primary key list
99 foreach my $key (@keys) {
101 foreach my $prim ($source->primary_columns) {
110 # Make sure every primary key column is in the self keys
112 foreach my $prim ($source->primary_columns) {
114 foreach my $key (@keys) {
124 # if $found then the two sets are equal.
126 # If the sets are different, then we assume it's a foreign key from
127 # us to another table.
129 $table->add_constraint(
130 type => 'foreign_key',
131 name => "fk_$keys[0]",
133 reference_fields => \@refkeys,
134 reference_table => $rel_table,