rule generation
[dbsrgits/DBIx-Class-ResultSource-MultipleTableInheritance.git] / lib / DBIx / Class / ResultSource / MultipleTableInheritance.pm
CommitLineData
876f6525 1package DBIx::Class::ResultSource::MultipleTableInheritance;
2
3use strict;
4use warnings;
5use parent qw(DBIx::Class::ResultSource::View);
876f6525 6use Method::Signatures::Simple;
7use Carp::Clan qw/^DBIx::Class/;
ca79850d 8use aliased 'DBIx::Class::ResultSource::Table';
7abe3af2 9use aliased 'DBIx::Class::ResultClass::HashRefInflator';
05fd2477 10use String::TT qw(strip tt);
92ebfc06 11use Scalar::Util qw(blessed);
ca79850d 12use namespace::autoclean;
70d56286 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
876f6525 29__PACKAGE__->mk_group_accessors(simple => qw(parent_source));
30
31method 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')) {
7abe3af2 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 }
876f6525 40 }
41 return $new;
42}
43
7abe3af2 44method schema (@args) {
45 my $ret = $self->next::method(@args);
46 if (@args) {
47 $self->_attach_additional_sources;
48 }
49 return $ret;
50}
51
876f6525 52method _attach_additional_sources () {
4d88a8d7 53 my $raw_name = $self->raw_source_name;
ca79850d 54 my $schema = $self->schema;
55
56 # if the raw source is already present we can assume we're done
57 return if grep { $_ eq $raw_name } $schema->sources;
4d88a8d7 58
ca79850d 59 # our parent should've been registered already actually due to DBIC
60 # attaching subclass sources later in load_namespaces
4d88a8d7 61
ca79850d 62 my $parent;
63 if ($self->parent_source) {
64 my $parent_name = $self->parent_source->name;
65 ($parent) =
66 grep { $_->name eq $parent_name }
67 map $schema->source($_), $schema->sources;
68 confess "Couldn't find attached source for parent $parent_name - did you use load_classes? This module is only compatible with load_namespaces"
69 unless $parent;
05fd2477 70 $self->parent_source($parent); # so our parent is the one in this schema
ca79850d 71 }
4d88a8d7 72
73 # create the raw table source
74
75 my $table = Table->new({ name => $self->raw_table_name });
76
ca79850d 77 # we don't need to add the PK cols explicitly if we're the root table
4d88a8d7 78 # since they'll get added below
79
ca79850d 80 if ($parent) {
81 my %join;
82 foreach my $pri ($self->primary_columns) {
83 my %info = %{$self->column_info($pri)};
84 delete @info{qw(is_auto_increment sequence auto_nextval)};
7abe3af2 85 $table->add_column($pri => \%info);
ca79850d 86 $join{"foreign.${pri}"} = "self.${pri}";
87 }
4d88a8d7 88 # have to use source name lookups rather than result class here
89 # because we don't actually have a result class on the raw sources
90 $table->add_relationship('parent', $parent->raw_source_name, \%join);
ca79850d 91 }
4d88a8d7 92
93 # add every column that's actually a concrete part of us
94
95 $table->add_columns(
96 map { ($_ => { %{$self->column_info($_)} }) }
97 grep { $self->column_info($_)->{originally_defined_in} eq $self->name }
98 $self->columns
99 );
ca79850d 100 $table->set_primary_key($self->primary_columns);
101 $schema->register_source($raw_name => $table);
102}
103
104method set_primary_key (@args) {
105 if ($self->parent_source) {
106 confess "Can't set primary key on a subclass";
107 }
108 return $self->next::method(@args);
876f6525 109}
110
4d88a8d7 111method raw_source_name () {
876f6525 112 my $base = $self->source_name;
05fd2477 113 confess "Can't generate raw source name for ${\$self->name} when we don't have a source_name"
876f6525 114 unless $base;
115 return 'Raw::'.$base;
116}
70d56286 117
4d88a8d7 118method raw_table_name () {
119 return '_'.$self->name;
120}
121
876f6525 122method add_columns (@args) {
123 my $ret = $self->next::method(@args);
124 $_->{originally_defined_in} ||= $self->name for values %{$self->_columns};
125 return $ret;
70d56286 126}
127
487f4489 128BEGIN {
129
130 # helper routines, constructed as anon subs so autoclean nukes them
131
132 use signatures;
133
134 *argify = sub (@names) {
135 map '_'.$_, @names;
136 };
137
138 *qualify_with = sub ($source, @names) {
92ebfc06 139 my $name = blessed($source) ? $source->name : $source;
140 map join('.', $name, $_), @names;
487f4489 141 };
142
143 *body_cols = sub ($source) {
144 my %pk; @pk{$source->primary_columns} = ();
145 map +{ %{$source->column_info($_)}, name => $_ },
146 grep !exists $pk{$_}, $source->columns;
147 };
148
149 *pk_cols = sub ($source) {
150 map +{ %{$source->column_info($_)}, name => $_ },
151 $source->primary_columns;
152 };
153
92ebfc06 154 *names_of = sub (@cols) { map $_->{name}, @cols };
487f4489 155
05fd2477 156 *function_body = sub ($name, $args, $body_parts) {
157 my $arglist = join(
158 ', ',
159 map '_'.join(' ', @{$_}{qw(name data_type)}),
160 @$args
161 );
162 my $body = join("\n", '', map " $_;", @$body_parts);
163 return strip tt q{
164 CREATE OR REPLACE FUNCTION [% name %]
165 ([% arglist %])
166 RETURNS VOID AS $function$
167 BEGIN
168 [%- body %]
169 END;
170 $function$ LANGUAGE plpgsql;
171 };
487f4489 172 };
487f4489 173}
174
05fd2477 175BEGIN {
176
177 use signatures;
178
179 *arg_hash = sub ($source) {
180 map +($_ => \(argify $_)), names_of body_cols $source;
181 };
92ebfc06 182
183 *rule_body = sub ($on, $to, $oldlist, $newlist) {
184 my $arglist = join(', ',
185 (qualify_with 'OLD', names_of @$oldlist),
186 (qualify_with 'NEW', names_of @$newlist),
187 );
188 $to = $to->name if blessed($to);
189 return strip tt q{
190 CREATE RULE _[% to %]_[% on %]_rule AS
191 ON [% on | upper %] TO [% to %]
192 DO INSTEAD (
193 SELECT _[% to %]_[% on %]([% arglist %])
194 );
195 };
196 };
05fd2477 197}
198
199method root_table () {
200 $self->parent_source
201 ? $self->parent_source->root_table
202 : $self->schema->source($self->raw_source_name)
203}
204
487f4489 205method view_definition () {
206 my $schema = $self->schema;
207 confess "Can't generate view without connected schema, sorry"
208 unless $schema && $schema->storage;
209 my $sqla = $schema->storage->sql_maker;
210 my @sources = my $table = $self->schema->source($self->raw_source_name);
211 my $super_view = $self->parent_source;
212 push(@sources, $super_view) if defined($super_view);
213 my @body_cols = map body_cols($_), @sources;
214 my @pk_cols = pk_cols $self;
92ebfc06 215
216 # SELECT statement
217
487f4489 218 my $select = $sqla->select(
219 ($super_view
220 ? ([ # FROM _tbl _tbl
221 { $table->name => $table->name },
222 [ # JOIN view view
223 { $super_view->name => $super_view->name },
224 # ON _tbl.id = view.id
225 { map +(qualify_with($super_view, $_), qualify_with($table, $_)),
226 names_of @pk_cols }
227 ]
228 ])
229 : ($table->name)),
230 [ (qualify_with $table, names_of @pk_cols), names_of @body_cols ],
05fd2477 231 ).';';
92ebfc06 232
05fd2477 233 my ($now, $next) = grep defined, $super_view, $table;
92ebfc06 234
235 # INSERT function
236
05fd2477 237 # NOTE: this assumes a single PK col called id with a sequence somewhere
238 # but nothing else -should- so fixing this should make everything work
239 my $insert_func =
240 function_body
241 $self->name.'_insert',
242 \@body_cols,
243 [
244 $sqla->insert( # INSERT INTO _tbl (foo, ...) VALUES (_foo, ...)
245 $now->name,
246 { arg_hash $now },
247 ),
248 ($next
249 ? $sqla->insert( # INSERT INTO super_view (id, ...)
250 # VALUES (currval('_root_tbl_id_seq'), ...)
251 $next->name,
252 {
253 (arg_hash $next),
254 id => \"currval('${\$self->root_table->name}_id_seq')",
255 }
256 )
257 : ()
258 )
259 ];
92ebfc06 260
05fd2477 261 # note - similar to arg_hash but not quite enough to share code sanely
262 my $pk_where = { # id = _id AND id2 = _id2 ...
263 map +($_ => \"= ${\argify $_}"), names_of @pk_cols
264 };
92ebfc06 265
266 # UPDATE function
267
05fd2477 268 my $update_func =
269 function_body
270 $self->name.'_update',
271 [ @pk_cols, @body_cols ],
272 [ map $sqla->update(
273 $_->name, # UPDATE foo
274 { arg_hash $_ }, # SET a = _a
275 $pk_where,
276 ), @sources
277 ];
92ebfc06 278
279 # DELETE function
280
05fd2477 281 my $delete_func =
282 function_body
283 $self->name.'_delete',
284 [ @pk_cols ],
285 [ map $sqla->delete($_->name, $pk_where), @sources ];
92ebfc06 286
287 my @rules = (
288 (rule_body insert => $self, [], \@body_cols),
289 (rule_body update => $self, \@pk_cols, \@body_cols),
290 (rule_body delete => $self, \@pk_cols, []),
291 );
292 return join("\n\n", $select, $insert_func, $update_func, $delete_func, @rules);
487f4489 293}
294
70d56286 2951;