remember to add the mixin class to our superclasses
[dbsrgits/DBIx-Class-ResultSource-MultipleTableInheritance.git] / lib / DBIx / Class / ResultSource / MultipleTableInheritance.pm
1 package DBIx::Class::ResultSource::MultipleTableInheritance;
2
3 use strict;
4 use warnings;
5 use parent qw(DBIx::Class::ResultSource::View);
6 use Method::Signatures::Simple;
7 use Carp::Clan qw/^DBIx::Class/;
8 use aliased 'DBIx::Class::ResultSource::Table';
9 use aliased 'DBIx::Class::ResultClass::HashRefInflator';
10 use String::TT qw(strip tt);
11 use Scalar::Util qw(blessed);
12 use namespace::autoclean;
13
14 # how this works:
15 #
16 # On construction, we hook $self->result_class->result_source_instance
17 # if present to get the superclass' source object
18
19 # When attached to a schema, we need to add sources to that schema with
20 # appropriate relationships for the foreign keys so the concrete tables
21 # get generated
22 #
23 # We also generate our own view definition using this class' concrete table
24 # and the view for the superclass, and stored procedures for the insert,
25 # update and delete operations on this view.
26 #
27 # deploying the postgres rules through SQLT may be a pain though.
28
29 __PACKAGE__->mk_group_accessors(simple => qw(parent_source additional_parents));
30
31 method new ($class: @args) {
32   my $new = $class->next::method(@args);
33   my $rc = $new->result_class;
34   if (my $meth = $rc->can('result_source_instance')) {
35     my $source = $rc->$meth;
36     if ($source->result_class ne $new->result_class
37         && $new->result_class->isa($source->result_class)) {
38       $new->parent_source($source);
39     }
40   }
41   return $new;
42 }
43
44 method add_additional_parent ($source) {
45   my ($our_pk, $their_pk) = map {
46     join('|',sort $_->primary_columns)
47   } ($self, $source);
48
49   confess "Can't attach additional parent ${\$source->name} - it has different PKs ($their_pk versus our $our_pk)"
50     unless $their_pk eq $our_pk;
51   $self->additional_parents([
52     @{$self->additional_parents||[]}, $source
53   ]);
54   $self->add_columns(
55     map {
56       $_ => # put the extra key first to default it
57       { originally_defined_in => $source->name, %{$source->column_info($_)}, },
58     } grep !$self->has_column($_), $source->columns
59   );
60   foreach my $rel ($source->relationships) {
61     my $rel_info = $source->relationship_info($rel);
62     $self->add_relationship(
63       $rel, $rel_info->{source}, $rel_info->{cond},
64       # extra key first to default it
65       {originally_defined_in => $source->name, %{$rel_info->{attrs}}},
66     );
67   }
68   { no strict 'refs';
69     push(@{$self->result_class.'::ISA'}, $source->result_class);
70   }
71 }
72
73 method _source_by_name ($name) {
74   my $schema = $self->schema;
75   my ($source) = 
76     grep { $_->name eq $name }
77       map $schema->source($_), $schema->sources;
78   confess "Couldn't find attached source for parent $name - did you use load_classes? This module is only compatible with load_namespaces"
79     unless $source;
80   return $source;
81 }
82
83 method schema (@args) {
84   my $ret = $self->next::method(@args);
85   if (@args) {
86     if ($self->parent_source) {
87       my $parent_name = $self->parent_source->name;
88       $self->parent_source($self->_source_by_name($parent_name));
89     }
90     $self->additional_parents([
91       map { $self->_source_by_name($_->name) }
92       @{$self->additional_parents||[]}
93     ]);
94   }
95   return $ret;
96 }
97
98 method attach_additional_sources () {
99   my $raw_name = $self->raw_source_name;
100   my $schema = $self->schema;
101
102   # if the raw source is already present we can assume we're done
103   return if grep { $_ eq $raw_name } $schema->sources;
104
105   # our parent should've been registered already actually due to DBIC
106   # attaching subclass sources later in load_namespaces
107
108   my $parent;
109   if ($self->parent_source) {
110       my $parent_name = $self->parent_source->name;
111     ($parent) = 
112       grep { $_->name eq $parent_name }
113         map $schema->source($_), $schema->sources;
114     confess "Couldn't find attached source for parent $parent_name - did you use load_classes? This module is only compatible with load_namespaces"
115       unless $parent;
116     $self->parent_source($parent); # so our parent is the one in this schema
117   }
118
119   # create the raw table source
120
121   my $table = Table->new({ name => $self->raw_table_name });
122
123   # we don't need to add the PK cols explicitly if we're the root table
124   # since they'll get added below
125
126   my %pk_join;
127
128   if ($parent) {
129     foreach my $pri ($self->primary_columns) {
130       my %info = %{$self->column_info($pri)};
131       delete @info{qw(is_auto_increment sequence auto_nextval)};
132       $table->add_column($pri => \%info);
133       $pk_join{"foreign.${pri}"} = "self.${pri}";
134     }
135     # have to use source name lookups rather than result class here
136     # because we don't actually have a result class on the raw sources
137     $table->add_relationship('parent', $parent->raw_source_name, \%pk_join);
138     $self->depends_on->{$parent->source_name} = 1;
139   }
140
141   foreach my $add (@{$self->additional_parents||[]}) {
142     $table->add_relationship(
143       'parent_'.$add->name, $add->source_name, \%pk_join
144     );
145     $self->depends_on->{$add->source_name} = 1;
146   }
147
148   # add every column that's actually a concrete part of us
149
150   $table->add_columns(
151     map { ($_ => { %{$self->column_info($_)} }) }
152       grep { $self->column_info($_)->{originally_defined_in} eq $self->name }
153         $self->columns
154   );
155   $table->set_primary_key($self->primary_columns);
156
157   # we need to copy our rels to the raw object as well
158   # note that ->add_relationship on a source object doesn't create an
159   # accessor so we can leave that part in the attributes
160
161   # if the other side is a table then we need to copy any rels it has
162   # back to us, as well, so that they point at the raw table. if the
163   # other side is an MTI view then we need to create the rels to it to
164   # point at -its- raw table; we don't need to worry about backrels because
165   # it's going to run this method too (and its raw source might not exist
166   # yet so we can't, anyway)
167
168   foreach my $rel ($self->relationships) {
169     my $rel_info = $self->relationship_info($rel);
170
171     # if we got this from the superclass, -its- raw table will nail this.
172     # if we got it from an additional parent, it's its problem.
173     next unless $rel_info->{attrs}{originally_defined_in} eq $self->name;
174
175     my $f_source = $schema->source($rel_info->{source});
176
177     # __PACKAGE__ is correct here because subclasses should be caught
178
179     my $one_of_us = $f_source->isa(__PACKAGE__);
180
181     my $f_source_name = $f_source->${\
182                         ($one_of_us ? 'raw_source_name' : 'source_name')
183                       };
184     
185     $table->add_relationship(
186       '_'.$rel, $f_source_name, @{$rel_info}{qw(cond attrs)}
187     );
188
189     unless ($one_of_us) {
190       my $reverse = do {
191         # we haven't been registered yet, so reverse_ cries
192         # XXX this is evil and will probably break eventually
193         local @{$schema->source_registrations}
194                {map $self->$_, qw(source_name result_class)}
195           = ($self, $self);
196         $self->reverse_relationship_info($rel);
197       };
198       foreach my $rev_rel (keys %$reverse) {
199         $f_source->add_relationship(
200           '_raw_'.$rev_rel, $raw_name, @{$reverse->{$rev_rel}}{qw(cond attrs)}
201         );
202       }
203     }
204   }
205
206   $schema->register_source($raw_name => $table);
207 }
208
209 method set_primary_key (@args) {
210   if ($self->parent_source) {
211     confess "Can't set primary key on a subclass";
212   }
213   return $self->next::method(@args);
214 }
215
216 method raw_source_name () {
217   my $base = $self->source_name;
218   confess "Can't generate raw source name for ${\$self->name} when we don't have a source_name"
219     unless $base;
220   return 'Raw::'.$base;
221 }
222
223 method raw_table_name () {
224   return '_'.$self->name;
225 }
226
227 method add_columns (@args) {
228   my $ret = $self->next::method(@args);
229   $_->{originally_defined_in} ||= $self->name for values %{$self->_columns};
230   return $ret;
231 }
232
233 method add_relationship ($name, $f_source, $cond, $attrs) {
234   $self->next::method(
235     $name, $f_source, $cond,
236     { originally_defined_in => $self->name, %{$attrs||{}}, }
237   );
238 }
239
240 BEGIN {
241
242   # helper routines, constructed as anon subs so autoclean nukes them
243
244   use signatures;
245
246   *argify = sub (@names) {
247     map '_'.$_, @names;
248   };
249
250   *qualify_with = sub ($source, @names) {
251     my $name = blessed($source) ? $source->name : $source;
252     map join('.', $name, $_), @names;
253   };
254
255   *body_cols = sub ($source) {
256     my %pk; @pk{$source->primary_columns} = ();
257     map +{ %{$source->column_info($_)}, name => $_ },
258       grep !exists $pk{$_}, $source->columns;
259   };
260
261   *pk_cols = sub ($source) {
262     map +{ %{$source->column_info($_)}, name => $_ },
263       $source->primary_columns;
264   };
265
266   *names_of = sub (@cols) { map $_->{name}, @cols };
267
268   *function_body = sub ($name, $args, $body_parts) {
269     my $arglist = join(
270       ', ',
271         map "_${\$_->{name}} ${\uc($_->{data_type})}",
272           @$args
273     );
274     my $body = join("\n", '', map "          $_;", @$body_parts);
275     return strip tt q{
276       CREATE OR REPLACE FUNCTION [% name %]
277         ([% arglist %])
278         RETURNS VOID AS $function$
279         BEGIN
280           [%- body %]
281         END;
282       $function$ LANGUAGE plpgsql;
283     };
284   };
285 }
286
287 BEGIN {
288
289   use signatures;
290
291   *arg_hash = sub ($source) {
292     map +($_ => \(argify $_)), names_of body_cols $source;
293   };
294
295   *rule_body = sub ($on, $to, $oldlist, $newlist) {
296     my $arglist = join(', ',
297       (qualify_with 'OLD', names_of @$oldlist),
298       (qualify_with 'NEW', names_of @$newlist),
299     );
300     $to = $to->name if blessed($to);
301     return strip tt q{
302       CREATE RULE _[% to %]_[% on %]_rule AS
303         ON [% on | upper %] TO [% to %]
304         DO INSTEAD (
305           SELECT [% to %]_[% on %]([% arglist %])
306         );
307     };
308   };
309 }
310
311 method root_table () {
312   $self->parent_source
313     ? $self->parent_source->root_table
314     : $self->schema->source($self->raw_source_name)
315 }
316
317 method view_definition () {
318   my $schema = $self->schema;
319   confess "Can't generate view without connected schema, sorry"
320     unless $schema && $schema->storage;
321   my $sqla = $schema->storage->sql_maker;
322   my $table = $self->schema->source($self->raw_source_name);
323   my $super_view = $self->parent_source;
324   my @all_parents = my @other_parents = @{$self->additional_parents||[]};
325   push(@all_parents, $super_view) if defined($super_view);
326   my @sources = ($table, @all_parents);
327   my @body_cols = map body_cols($_), @sources;
328   my @pk_cols = pk_cols $self;
329
330   # SELECT statement
331
332   my $am_root = !($super_view || @other_parents);
333
334   my $select = $sqla->select(
335     ($am_root
336       ? ($table->name)
337       : ([   # FROM _tbl _tbl
338            { $table->name => $table->name },
339            map {
340              my $parent = $_;
341              [ # JOIN view view
342                { $parent->name => $parent->name },
343                # ON _tbl.id = view.id
344                { map +(qualify_with($parent, $_), qualify_with($table, $_)),
345                    names_of @pk_cols }
346              ]
347            } @all_parents
348          ])
349       ),
350     [ (qualify_with $table, names_of @pk_cols), names_of @body_cols ],
351   ).';';
352
353   my ($now, @next) = grep defined, $super_view, $table, @other_parents;
354
355   # INSERT function
356
357   # NOTE: this assumes a single PK col called id with a sequence somewhere
358   # but nothing else -should- so fixing this should make everything work
359   my $insert_func =
360     function_body
361       $self->name.'_insert',
362       \@body_cols,
363       [
364         $sqla->insert( # INSERT INTO tbl/super_view (foo, ...) VALUES (_foo, ...)
365           $now->name,
366           { arg_hash $now },
367         ),
368         (map {
369           $sqla->insert( # INSERT INTO parent (id, ...)
370                          #   VALUES (currval('_root_tbl_id_seq'), ...)
371             $_->name,
372             {
373               (arg_hash $_),
374               id => \"currval('${\$self->root_table->name}_id_seq')",
375             }
376           )
377         } @next)
378       ];
379
380   # note - similar to arg_hash but not quite enough to share code sanely
381   my $pk_where = { # id = _id AND id2 = _id2 ...
382     map +($_ => \"= ${\argify $_}"), names_of @pk_cols
383   };
384
385   # UPDATE function
386
387   my $update_func =
388     function_body
389       $self->name.'_update',
390       [ @pk_cols, @body_cols ],
391       [ map $sqla->update(
392           $_->name, # UPDATE foo
393           { arg_hash $_ }, # SET a = _a
394           $pk_where,
395         ), @sources
396       ];
397
398   # DELETE function
399
400   my $delete_func =
401     function_body
402       $self->name.'_delete',
403       [ @pk_cols ],
404       [ map $sqla->delete($_->name, $pk_where), @sources ];
405
406   my @rules = (
407     (rule_body insert => $self, [], \@body_cols),
408     (rule_body update => $self, \@pk_cols, \@body_cols),
409     (rule_body delete => $self, \@pk_cols, []),
410   );
411   return join("\n\n", $select, $insert_func, $update_func, $delete_func, @rules);
412 }
413
414 1;