fix sfunc names, basically works
[dbsrgits/DBIx-Class-ResultSource-MultipleTableInheritance.git] / lib / DBIx / Class / ResultSource / MultipleTableInheritance.pm
index 2c3fafe..832a51f 100644 (file)
@@ -8,6 +8,7 @@ use Carp::Clan qw/^DBIx::Class/;
 use aliased 'DBIx::Class::ResultSource::Table';
 use aliased 'DBIx::Class::ResultClass::HashRefInflator';
 use String::TT qw(strip tt);
+use Scalar::Util qw(blessed);
 use namespace::autoclean;
 
 # how this works:
@@ -25,7 +26,7 @@ use namespace::autoclean;
 #
 # deploying the postgres rules through SQLT may be a pain though.
 
-__PACKAGE__->mk_group_accessors(simple => qw(parent_source));
+__PACKAGE__->mk_group_accessors(simple => qw(parent_source additional_parents));
 
 method new ($class: @args) {
   my $new = $class->next::method(@args);
@@ -40,15 +41,50 @@ method new ($class: @args) {
   return $new;
 }
 
+method add_additional_parent ($source) {
+  my ($our_pk, $their_pk) = map {
+    join('|',sort $_->primary_columns)
+  } ($self, $source);
+
+  confess "Can't attach additional parent ${\$source->name} - it has different PKs ($their_pk versus our $our_pk)"
+    unless $their_pk eq $our_pk;
+  $self->additional_parents([
+    @{$self->additional_parents||[]}, $source
+  ]);
+  $self->add_columns(
+    map {
+      $_ => # put the extra key first to default it
+      { originally_defined_in => $source->name, %{$source->column_info($_)}, },
+    } grep !$self->has_column($_), $source->columns
+  );
+  foreach my $rel ($source->relationships) {
+    my $rel_info = $source->relationship_info($rel);
+    $self->add_relationship(
+      $rel, $rel_info->{source}, $rel_info->{cond},
+      # extra key first to default it
+      {originally_defined_in => $source->name, %{$rel_info->{attrs}}},
+    );
+  }
+}
+
 method schema (@args) {
   my $ret = $self->next::method(@args);
   if (@args) {
-    $self->_attach_additional_sources;
+    if ($self->parent_source) {
+      my $schema = $self->schema;
+      my $parent_name = $self->parent_source->name;
+      my ($parent) = 
+        grep { $_->name eq $parent_name }
+          map $schema->source($_), $schema->sources;
+      confess "Couldn't find attached source for parent $parent_name - did you use load_classes? This module is only compatible with load_namespaces"
+        unless $parent;
+      $self->parent_source($parent); # so our parent is the one in this schema
+    }
   }
   return $ret;
 }
 
-method _attach_additional_sources () {
+method attach_additional_sources () {
   my $raw_name = $self->raw_source_name;
   my $schema = $self->schema;
 
@@ -76,17 +112,26 @@ method _attach_additional_sources () {
   # we don't need to add the PK cols explicitly if we're the root table
   # since they'll get added below
 
+  my %pk_join;
+
   if ($parent) {
-    my %join;
     foreach my $pri ($self->primary_columns) {
       my %info = %{$self->column_info($pri)};
       delete @info{qw(is_auto_increment sequence auto_nextval)};
       $table->add_column($pri => \%info);
-      $join{"foreign.${pri}"} = "self.${pri}";
+      $pk_join{"foreign.${pri}"} = "self.${pri}";
     }
     # have to use source name lookups rather than result class here
     # because we don't actually have a result class on the raw sources
-    $table->add_relationship('parent', $parent->raw_source_name, \%join);
+    $table->add_relationship('parent', $parent->raw_source_name, \%pk_join);
+    $self->depends_on->{$parent->source_name} = 1;
+  }
+
+  foreach my $add (@{$self->additional_parents||[]}) {
+    $table->add_relationship(
+      'parent_'.$add->name, $add->source_name, \%pk_join
+    );
+    $self->depends_on->{$add->source_name} = 1;
   }
 
   # add every column that's actually a concrete part of us
@@ -97,6 +142,56 @@ method _attach_additional_sources () {
         $self->columns
   );
   $table->set_primary_key($self->primary_columns);
+
+  # we need to copy our rels to the raw object as well
+  # note that ->add_relationship on a source object doesn't create an
+  # accessor so we can leave that part in the attributes
+
+  # if the other side is a table then we need to copy any rels it has
+  # back to us, as well, so that they point at the raw table. if the
+  # other side is an MTI view then we need to create the rels to it to
+  # point at -its- raw table; we don't need to worry about backrels because
+  # it's going to run this method too (and its raw source might not exist
+  # yet so we can't, anyway)
+
+  foreach my $rel ($self->relationships) {
+    my $rel_info = $self->relationship_info($rel);
+
+    # if we got this from the superclass, -its- raw table will nail this.
+    # if we got it from an additional parent, it's its problem.
+    next unless $rel_info->{attrs}{originally_defined_in} eq $self->name;
+
+    my $f_source = $schema->source($rel_info->{source});
+
+    # __PACKAGE__ is correct here because subclasses should be caught
+
+    my $one_of_us = $f_source->isa(__PACKAGE__);
+
+    my $f_source_name = $f_source->${\
+                        ($one_of_us ? 'raw_source_name' : 'source_name')
+                      };
+    
+    $table->add_relationship(
+      '_'.$rel, $f_source_name, @{$rel_info}{qw(cond attrs)}
+    );
+
+    unless ($one_of_us) {
+      my $reverse = do {
+        # we haven't been registered yet, so reverse_ cries
+        # XXX this is evil and will probably break eventually
+        local @{$schema->source_registrations}
+               {map $self->$_, qw(source_name result_class)}
+          = ($self, $self);
+        $self->reverse_relationship_info($rel);
+      };
+      foreach my $rev_rel (keys %$reverse) {
+        $f_source->add_relationship(
+          '_raw_'.$rev_rel, $raw_name, @{$reverse->{$rev_rel}}{qw(cond attrs)}
+        );
+      }
+    }
+  }
+
   $schema->register_source($raw_name => $table);
 }
 
@@ -124,6 +219,13 @@ method add_columns (@args) {
   return $ret;
 }
 
+method add_relationship ($name, $f_source, $cond, $attrs) {
+  $self->next::method(
+    $name, $f_source, $cond,
+    { originally_defined_in => $self->name, %{$attrs||{}}, }
+  );
+}
+
 BEGIN {
 
   # helper routines, constructed as anon subs so autoclean nukes them
@@ -135,7 +237,8 @@ BEGIN {
   };
 
   *qualify_with = sub ($source, @names) {
-    map join('.', $source->name, $_), @names;
+    my $name = blessed($source) ? $source->name : $source;
+    map join('.', $name, $_), @names;
   };
 
   *body_cols = sub ($source) {
@@ -149,12 +252,12 @@ BEGIN {
       $source->primary_columns;
   };
 
-  *name_of = *names_of = sub (@cols) { map $_->{name}, @cols };
+  *names_of = sub (@cols) { map $_->{name}, @cols };
 
   *function_body = sub ($name, $args, $body_parts) {
     my $arglist = join(
       ', ',
-        map '_'.join(' ', @{$_}{qw(name data_type)}),
+        map "_${\$_->{name}} ${\uc($_->{data_type})}",
           @$args
     );
     my $body = join("\n", '', map "          $_;", @$body_parts);
@@ -168,7 +271,6 @@ BEGIN {
       $function$ LANGUAGE plpgsql;
     };
   };
-    
 }
 
 BEGIN {
@@ -178,6 +280,21 @@ BEGIN {
   *arg_hash = sub ($source) {
     map +($_ => \(argify $_)), names_of body_cols $source;
   };
+
+  *rule_body = sub ($on, $to, $oldlist, $newlist) {
+    my $arglist = join(', ',
+      (qualify_with 'OLD', names_of @$oldlist),
+      (qualify_with 'NEW', names_of @$newlist),
+    );
+    $to = $to->name if blessed($to);
+    return strip tt q{
+      CREATE RULE _[% to %]_[% on %]_rule AS
+        ON [% on | upper %] TO [% to %]
+        DO INSTEAD (
+          SELECT [% to %]_[% on %]([% arglist %])
+        );
+    };
+  };
 }
 
 method root_table () {
@@ -196,6 +313,9 @@ method view_definition () {
   push(@sources, $super_view) if defined($super_view);
   my @body_cols = map body_cols($_), @sources;
   my @pk_cols = pk_cols $self;
+
+  # SELECT statement
+
   my $select = $sqla->select(
     ($super_view
       ? ([   # FROM _tbl _tbl
@@ -210,7 +330,11 @@ method view_definition () {
       : ($table->name)),
     [ (qualify_with $table, names_of @pk_cols), names_of @body_cols ],
   ).';';
+
   my ($now, $next) = grep defined, $super_view, $table;
+
+  # INSERT function
+
   # NOTE: this assumes a single PK col called id with a sequence somewhere
   # but nothing else -should- so fixing this should make everything work
   my $insert_func =
@@ -234,10 +358,14 @@ method view_definition () {
           : ()
         )
       ];
+
   # note - similar to arg_hash but not quite enough to share code sanely
   my $pk_where = { # id = _id AND id2 = _id2 ...
     map +($_ => \"= ${\argify $_}"), names_of @pk_cols
   };
+
+  # UPDATE function
+
   my $update_func =
     function_body
       $self->name.'_update',
@@ -248,12 +376,21 @@ method view_definition () {
           $pk_where,
         ), @sources
       ];
+
+  # DELETE function
+
   my $delete_func =
     function_body
       $self->name.'_delete',
       [ @pk_cols ],
       [ map $sqla->delete($_->name, $pk_where), @sources ];
-  return join("\n\n", $select, $insert_func, $update_func, $delete_func);
+
+  my @rules = (
+    (rule_body insert => $self, [], \@body_cols),
+    (rule_body update => $self, \@pk_cols, \@body_cols),
+    (rule_body delete => $self, \@pk_cols, []),
+  );
+  return join("\n\n", $select, $insert_func, $update_func, $delete_func, @rules);
 }
 
 1;