1 package SQL::Translator::Parser::DBIx::Class;
3 # AUTHOR: Jess Robinson
5 # Some mistakes the fault of Matt S Trout
9 use vars qw($DEBUG $VERSION @EXPORT_OK);
10 $DEBUG = 0 unless defined $DEBUG;
11 $VERSION = sprintf "%d.%02d", q$Revision 1.0$ =~ /(\d+)\.(\d+)/;
15 use SQL::Translator::Utils qw(debug normalize_name);
17 use base qw(Exporter);
19 @EXPORT_OK = qw(parse);
21 # -------------------------------------------------------------------
24 # Note that $data, in the case of this parser, is unuseful.
25 # We're working with DBIx::Class Schemas, not data streams.
26 # -------------------------------------------------------------------
29 my $args = $tr->parser_args;
30 my $dbixschema = $args->{'DBIx::Schema'} || $data;
31 $dbixschema ||= $args->{'package'};
33 die 'No DBIx::Schema' unless ($dbixschema);
34 if (!ref $dbixschema) {
35 eval "use $dbixschema;";
36 die "Can't load $dbixschema ($@)" if($@);
39 my $schema = $tr->schema;
42 # print Dumper($dbixschema->registered_classes);
44 #foreach my $tableclass ($dbixschema->registered_classes)
45 foreach my $moniker ($dbixschema->sources)
47 #eval "use $tableclass";
48 #print("Can't load $tableclass"), next if($@);
49 my $source = $dbixschema->source($moniker);
51 my $table = $schema->add_table(
52 name => $source->name,
54 ) || die $schema->error;
56 foreach my $col ($source->columns)
58 # assuming column_info in dbix is the same as DBI (?)
59 # data_type is a number, column_type is text?
63 is_auto_increment => 0,
66 %{$source->column_info($col)}
68 if ($colinfo{is_nullable}) {
69 $colinfo{default} = '' unless exists $colinfo{default};
71 my $f = $table->add_field(%colinfo) || die $table->error;
73 $table->primary_key($source->primary_columns);
76 my @rels = $source->relationships();
77 foreach my $rel (@rels)
79 my $rel_info = $source->relationship_info($rel);
80 print "Accessor: $rel_info->{attrs}{accessor}\n";
81 next if(!exists $rel_info->{attrs}{accessor} ||
82 $rel_info->{attrs}{accessor} eq 'multi');
83 # Going by the accessor type isn't such a good idea (yes, I know
84 # I suggested it). I think the best way to tell if something's a
85 # foreign key constraint is to assume if it doesn't include our
86 # primaries then it is (dumb but it'll do). Ignore any rel cond
87 # that isn't a straight hash, but get both sets of keys in full
88 # so you don't barf on multi-primaries. Oh, and a dog-simple
89 # deploy method to chuck the results of this exercise at a db
91 # $schema->storage->dbh->do($_) for split(";\n", $sql);
92 # -- mst (03:42 local time, please excuse any mistakes)
93 my $rel_table = $rel_info->{class}->table();
94 my $cond = (keys (%{$rel_info->{cond}}))[0];
95 my ($refkey) = $cond =~ /^\w+\.(\w+)$/;
96 if($rel_table && $refkey)
98 $table->add_constraint(
99 type => 'foreign_key',
100 name => "fk_${rel}_id",
102 reference_fields => $refkey,
103 reference_table => $rel_table,