File: SQLA2Passthrough.pm

package info (click to toggle)
libsql-abstract-perl 2.000001-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 744 kB
  • sloc: perl: 3,443; makefile: 8
file content (209 lines) | stat: -rw-r--r-- 5,348 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package DBIx::Class::SQLMaker::Role::SQLA2Passthrough;

use strict;
use warnings;
use Exporter 'import';

our @EXPORT = qw(on);

sub on (&) {
  my ($on) = @_;
  sub {
    my ($args) = @_;
    $args->{self_resultsource}
         ->schema->storage->sql_maker
         ->expand_join_condition(
             $on->($args),
             $args
           );
  }
}

use Role::Tiny;

around select => sub {
  my ($orig, $self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;

  $fields = \[ $self->render_expr({ -list => [
    grep defined,
    map +(ref($_) eq 'HASH'
          ? do {
              my %f = %$_;
              my $as = delete $f{-as};
              my ($f, $rhs) = %f;
              my $func = +{ ($f =~ /^-/ ? $f : "-${f}") => $rhs };
              ($as
                ? +{ -op => [ 'as', $func, { -ident => [ $as ] } ] }
                : $func)
            }
          : $_), ref($fields) eq 'ARRAY' ? @$fields : $fields
  ] }, -ident) ];

  if (my $gb = $rs_attrs->{group_by}) {
    $rs_attrs = {
      %$rs_attrs,
      group_by => \[ $self->render_expr({ -list => $gb }, -ident) ]
    };
  }
  $self->$orig($table, $fields, $where, $rs_attrs, $limit, $offset);
};

sub expand_join_condition {
  my ($self, $cond, $args) = @_;
  my ($type, %known) = do {
    if (my $obj = $args->{self_result_object}) {
      (self => $obj->get_columns)
    } elsif (my $val = $args->{foreign_values}) {
      (foreign => %$val)
    } else {
      ('')
    }
  };
  my $maybe = $type ? 1 : 0;
  my $outside;
  my $wrap = sub {
    my ($orig) = @_;
    $outside = $orig;
    sub {
      my $res = $orig->(@_);
      my ($name, $col) = @{$res->{-ident}};
      if ($name eq 'self' or $name eq 'foreign') {
        if ($type eq $name) {
          $maybe = 0 unless exists $known{$col};
        }
        return { -ident => [ $args->{"${name}_alias"}, $col ] };
      }
      return $res;
    };
  };
  my $sqla = $self->clone->wrap_op_expander(ident => $wrap);
  my $aqt = $sqla->expand_expr($cond, -ident);
  return $aqt unless $maybe;
  my $inner_wrap = sub {
    my $res = $outside->(@_);
    my ($name, $col) = @{$res->{-ident}};
    if ($name eq 'self' or $name eq 'foreign') {
      if ($type eq $name) {
        return { -bind => [ $args->{"${name}_alias"}.'.'.$col, $known{$col} ] };
      }
      return { -ident => [ $args->{"${name}_alias"}, $col ] };
    }
    return $res;
  };
  $sqla->op_expander(ident => $inner_wrap);
  my $inner_aqt = $self->_collapsify($sqla->expand_expr($cond, -ident));
  return ($aqt, $inner_aqt);
}

sub _collapsify {
  my ($self, $aqt) = @_;
  return $aqt unless my @opargs = @{$aqt->{-op}};
  my ($logop, @args) = @opargs;
  return $aqt unless $logop eq 'and';
  my %collapsed = map {
    my $q = $_;
    return $aqt unless my @opargs = @{$q->{-op}};
    my ($op, $lhs, @rest) = @opargs;
    return $aqt unless my @ident = @{$lhs->{-ident}};
    (join('.', @ident), { $op => \@rest });
  } @args;
  return \%collapsed;
}

1;

__END__

=head1 NAME

DBIx::Class::SQLMaker::Role::SQLA2Passthrough - A test of future possibilities

=head1 SYNOPSIS

=over 4

=item * select and group_by options are processed using the richer SQLA2 code

=item * expand_join_condition is provided to more easily express rich joins

=back

See C<examples/sqla2passthrough.pl> for a small amount of running code.

=head1 SETUP

  (on_connect_call => sub {
     my ($storage) = @_;
     $storage->sql_maker
             ->with::roles('DBIx::Class::SQLMaker::Role::SQLA2Passthrough');
  })

=head2 expand_join_condition

  __PACKAGE__->has_many(minions => 'Blah::Person' => sub {
    my ($args) = @_;
    $args->{self_resultsource}
         ->schema->storage->sql_maker
         ->expand_join_condition(
             $args
           );
  });

=head2 on

  __PACKAGE__->has_many(minions => 'Blah::Person' => on {
    { 'self.group_id' => 'foreign.group_id',
      'self.rank' => { '>', 'foreign.rank' } }
  });

Or with ParameterizedJoinHack,

  __PACKAGE__->parameterized_has_many(
      priority_tasks => 'MySchema::Result::Task',
      [['min_priority'] => sub {
          my $args = shift;
          return +{
              "$args->{foreign_alias}.owner_id" => {
                  -ident => "$args->{self_alias}.id",
              },
              "$args->{foreign_alias}.priority" => {
                  '>=' => $_{min_priority},
              },
          };
      }],
  );

becomes

  __PACKAGE__->parameterized_has_many(
      priority_tasks => 'MySchema::Result::Task',
      [['min_priority'] => on {
        { 'foreign.owner_id' => 'self.id',
          'foreign.priority' => { '>=', { -value => $_{min_priority} } } }
      }]
  );

Note that foreign/self can appear in such a condition on either side, BUT
if you want L<DBIx::Class> to be able to use a join-less version you must
ensure that the LHS is all foreign columns, i.e.

  on {
    +{
      'foreign.x' => 'self.x',
      'self.y' => { -between => [ 'foreign.y1', 'foreign.y2' ] }
    }
  }

is completely valid but DBIC will insist on doing a JOIN even if you
have a fully populated row object to call C<search_related> on - to avoid
the spurious JOIN, you must specify it with explicit LHS foreign cols as:

  on {
    +{
      'foreign.x' => 'self.x',
      'foreign.y1' => { '<=', 'self.y' },
      'foreign.y2' => { '>=', 'self.y' },
    }
  }

=cut