fix condition extraction for new_result
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLMaker.pm
1 package DBIx::Class::SQLMaker;
2
3 use strict;
4 use warnings;
5
6 =head1 NAME
7
8 DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
9
10 =head1 DESCRIPTION
11
12 This module is a subclass of L<SQL::Abstract> and includes a number of
13 DBIC-specific workarounds, not yet suitable for inclusion into the
14 L<SQL::Abstract> core. It also provides all (and more than) the functionality
15 of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
16 more info.
17
18 Currently the enhancements to L<SQL::Abstract> are:
19
20 =over
21
22 =item * Support for C<JOIN> statements (via extended C<table/from> support)
23
24 =item * Support of functions in C<SELECT> lists
25
26 =item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
27
28 =item * Support of C<...FOR UPDATE> type of select statement modifiers
29
30 =item * The L</-ident> operator
31
32 =item * The L</-value> operator
33
34 =back
35
36 =cut
37
38 use base qw/
39   SQL::Abstract
40   DBIx::Class::SQLMaker::LimitDialects
41 /;
42 use mro 'c3';
43
44 use Module::Runtime qw(use_module);
45 use Sub::Name 'subname';
46 use DBIx::Class::Carp;
47 use DBIx::Class::Exception;
48 use Moo;
49 use namespace::clean;
50
51 has limit_dialect => (
52   is => 'rw', default => sub { 'LimitOffset' },
53   trigger => sub { shift->clear_renderer_class }
54 );
55
56 sub BUILD {
57   if ($_[0]->can('emulate_limit')) {
58     die <<EODIE;
59 The ancient and horrible emulate_limit method was deprecated for many moons.
60 Now, it is no more. Time to rewrite the code in ${\ref($_[0])}
61 EODIE
62   }
63 }
64
65 our %LIMIT_DIALECT_MAP = (
66   'GenericSubQ' => 'GenericSubquery',
67 );
68
69 sub mapped_limit_dialect {
70   my ($self) = @_;
71   my $unmapped = $self->limit_dialect;
72   $LIMIT_DIALECT_MAP{$unmapped}||$unmapped;
73 }
74
75 around _build_renderer_roles => sub {
76   my ($orig, $self) = (shift, shift);
77   return (
78     $self->$orig(@_),
79     'Data::Query::Renderer::SQL::Slice::'.$self->mapped_limit_dialect
80   );
81 };
82
83 # for when I need a normalized l/r pair
84 sub _quote_chars {
85   map
86     { defined $_ ? $_ : '' }
87     ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
88   ;
89 }
90
91 sub _build_converter_class {
92   Module::Runtime::use_module('DBIx::Class::SQLMaker::Converter')
93 }
94
95 # FIXME when we bring in the storage weaklink, check its schema
96 # weaklink and channel through $schema->throw_exception
97 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
98
99 BEGIN {
100   # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
101   # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
102   no warnings qw/redefine/;
103
104   *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
105     my($func) = (caller(1))[3];
106     carp "[$func] Warning: ", @_;
107   };
108
109   *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
110     my($func) = (caller(1))[3];
111     __PACKAGE__->throw_exception("[$func] Fatal: " . join ('',  @_));
112   };
113
114   # Current SQLA pollutes its namespace - clean for the time being
115   namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
116 }
117
118 # the "oh noes offset/top without limit" constant
119 # limited to 31 bits for sanity (and consistency,
120 # since it may be handed to the like of sprintf %u)
121 #
122 # Also *some* builds of SQLite fail the test
123 #   some_column BETWEEN ? AND ?: 1, 4294967295
124 # with the proper integer bind attrs
125 #
126 # Implemented as a method, since ::Storage::DBI also
127 # refers to it (i.e. for the case of software_limit or
128 # as the value to abuse with MSSQL ordered subqueries)
129 sub __max_int () { 0x7FFFFFFF };
130
131 # poor man's de-qualifier
132 sub _quote {
133   $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
134     ? $_[1] =~ / ([^\.]+) $ /x
135     : $_[1]
136   );
137 }
138
139 sub _where_op_NEST {
140   carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
141       .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
142   );
143
144   shift->next::method(@_);
145 }
146
147 around _converter_args => sub {
148   my ($orig, $self) = (shift, shift);
149   +{
150     %{$self->$orig(@_)},
151     name_sep => $self->name_sep,
152     limit_dialect => $self->mapped_limit_dialect,
153     slice_stability => { $self->renderer->slice_stability },
154     slice_subquery => { $self->renderer->slice_subquery },
155   }
156 };
157
158 # Handle limit-dialect selection
159 sub select {
160   my $self = shift;
161   my ($table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
162
163   my ($sql, @bind) = $self->next::method(@_);
164
165   $sql .= $self->_lock_select ($rs_attrs->{for})
166     if $rs_attrs->{for};
167
168   return wantarray ? ($sql, @bind) : $sql;
169 }
170
171 sub _assemble_binds {
172   my $self = shift;
173   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
174 }
175
176 my $for_syntax = {
177   update => 'FOR UPDATE',
178   shared => 'FOR SHARE',
179 };
180 sub _lock_select {
181   my ($self, $type) = @_;
182
183   my $sql;
184   if (ref($type) eq 'SCALAR') {
185     $sql = "FOR $$type";
186   }
187   else {
188     $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FO
189 R type '$type' requested" );
190   }
191
192   return " $sql";
193 }
194
195 sub _recurse_from {
196   scalar shift->_render_sqla(table => \@_);
197 }
198
199 1;
200
201 =head1 OPERATORS
202
203 =head2 -ident
204
205 Used to explicitly specify an SQL identifier. Takes a plain string as value
206 which is then invariably treated as a column name (and is being properly
207 quoted if quoting has been requested). Most useful for comparison of two
208 columns:
209
210     my %where = (
211         priority => { '<', 2 },
212         requestor => { -ident => 'submitter' }
213     );
214
215 which results in:
216
217     $stmt = 'WHERE "priority" < ? AND "requestor" = "submitter"';
218     @bind = ('2');
219
220 =head2 -value
221
222 The -value operator signals that the argument to the right is a raw bind value.
223 It will be passed straight to DBI, without invoking any of the SQL::Abstract
224 condition-parsing logic. This allows you to, for example, pass an array as a
225 column value for databases that support array datatypes, e.g.:
226
227     my %where = (
228         array => { -value => [1, 2, 3] }
229     );
230
231 which results in:
232
233     $stmt = 'WHERE array = ?';
234     @bind = ([1, 2, 3]);
235
236 =head1 AUTHORS
237
238 See L<DBIx::Class/CONTRIBUTORS>.
239
240 =head1 LICENSE
241
242 You may distribute this code under the same terms as Perl itself.
243
244 =cut