package GC::DB; use strict; BEGIN { our @CONNECTION; @CONNECTION = qw(dbi:Pg:dbname=gcdb Luser Guessnot) unless @CONNECTION; require Class::DBI::Loader; require Lingua::EN::Inflect; my $DEBUG = 0; my $l = Class::DBI::Loader->new(dsn => $CONNECTION[0], user => $CONNECTION[1], password => $CONNECTION[2], namespace => __PACKAGE__, ); my @classes = $l->classes; my @tables = $l->tables; my $dbh = $classes[0]->db_Main; ## add mixin of us for my $class (@classes) { no strict 'refs'; push @{$class . "::ISA"}, __PACKAGE__; } ## set up the has_a/has_many from the foreign keys my %class_of; @class_of{@tables} = @classes; Lingua::EN::Inflect::def_noun('paidto','paidtos'); # PL() gets this wrong my $has_a_many = sub { # no lexical subs yet! my ($table, $column, $other) = @_; my $table_class = $class_of{$table}; my $other_class = $class_of{$other}; warn sprintf("%s->has_a(%s => %s)\n", $table_class, $column, $other_class, ) if $DEBUG; $table_class->has_a($column => $other_class); my ($table_class_base) = $table_class =~ /.*::(.*)/ or die; my $plural = Lingua::EN::Inflect::PL(lc $table_class_base); warn sprintf("%s->has_many(%s => %s)\n", $other_class, $plural, $table_class, ) if $DEBUG; $other_class->has_many($plural => $table_class); }; ## deal with Pg inheritance my %inherits = ( payment => [qw(payment payment_cc payment_check payment_money_order payment_wire)], ); for my $table (@tables) { warn "$table:\n" if $DEBUG; if (my $sth = $dbh->foreign_key_info('','','','','',$table)) { for my $res (@{$sth->fetchall_arrayref({})}) { my $column = $res->{FK_COLUMN_NAME}; my $other = $res->{UK_TABLE_NAME}; my @tables = @{$inherits{$table} || [$table]}; my @others = @{$inherits{$other} || [$other]}; for my $table (@tables) { for my $other (@others) { $has_a_many->($table, $column, $other); } } } } } } ## other GC::DB::* things go here 1;