probably works for adding extra sources; doing some testing without before caring
[dbsrgits/DBIx-Class-ResultSource-MultipleTableInheritance.git] / vdef
1 sub argify (@cols) {
2   map $_->new(%$_, name => '_'.$_->name), @cols;
3 }
4
5 sub body_cols ($source) {
6   grep $_->name ne 'id', $source->all_cols;
7 }
8
9 my @pk_col = ($table->col('id'));
10
11 my @sources = grep defined, $table, $super_view;
12
13 my @body_cols = map body_cols($_), @sources;
14
15 CREATE VIEW $view_name =>
16   SELECT {
17     (map $_->qualify, @pk_col),
18     @body_cols,
19   } FROM {
20     $super_view ? ($table->join($super_view)->using(@pk_col)) : $table
21   };
22
23 my ($now, $next) = grep defined, $super_view, $table;
24
25 CREATE FUNCTION "${view_name}_insert" =>
26   (argify @body_cols)
27   => RETURNS VOID => AS {
28     INSERT INTO { $now } (body_cols $now)
29       => VALUES (argify body_cols $now);
30     if ($next) {
31       INSERT INTO { $next } ($next->all_cols)
32         => VALUES {
33              $root_table->col('id')->sequence->currval,
34              argify body_cols $next
35            };
36     }
37   };
38
39 my $pk_eq = AND( map (expr { $_ == argify $_ }), @pk_col);
40
41 CREATE FUNCTION "${view_name}_update" =>
42   (argify @pk_col, @body_cols)
43   => RETURNS VOID => AS {
44     foreach my $s (@sources) {
45       UPDATE { $s } SET { map ($_ => argify $_), body_cols $s }
46         WHERE { $pk_eq };
47     }
48   };
49
50 CREATE FUNCTION "${view_name}_delete" =>
51   (argify @pk_col)
52   => RETURNS VOID => AS {
53     foreach my $s (@sources) {
54       DELETE FROM { $s } WHERE { $pk_eq };
55     }
56   };
57
58