blib/lib/DB/Object/SQLite/Query.pm untested

filter: Statementstmt 0.0% 0 / 182 Branchbran 0.0% 0 / 100 Conditioncond 0.0% 0 / 63 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 376 CC 51 SCAR 54.9
CC
51
Cov
0%
on_conflict
552.0
_query_components
240.0
limit
42.0
CRAP 243.2
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/SQLite/Query.pm
4 ## Version v0.4.0
5 ## Copyright(c) 2023 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2019/06/16
8 ## Modified 2026/03/22
9 ## All rights reserved
10 ##
11 ##
12 ## This program is free software; you can redistribute it and/or modify it
13 ## under the same terms as Perl itself.
14 ##----------------------------------------------------------------------------
15 package DB::Object::SQLite::Query;
16 BEGIN
17 {
18 use strict;
19 use warnings;
20 use parent qw( DB::Object::Query );
21 use vars qw( $VERSION $DEBUG $EXCEPTION_CLASS );
22 use Wanted;
23 our $DEBUG = 0;
24 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
25 our $VERSION = 'v0.4.0';
26 };
27  
28 use strict;
29 use warnings;
30  
31 sub init
32 {
33 my $self = shift( @_ );
34 $self->{having} = '';
35 $self->{_init_strict_use_sub} = 1;
36 $self->{_exception_class} = $EXCEPTION_CLASS;
37 $self->SUPER::init( @_ ) || return( $self->pass_error );
38 $self->{binded_having} = [];
39 $self->{query_reset_keys} = [qw( alias binded binded_values binded_where binded_limit binded_group binded_having binded_order from_unixtime group_by limit local _on_conflict on_conflict order_by reverse sorted unix_timestamp where )];
40 return( $self );
41 }
42  
43 sub binded_having { return( shift->_set_get( 'binded_having', @_ ) ); }
44  
45 sub format_from_epoch
46 {
47 my $self = shift( @_ );
48 my $opts = {};
49 $opts = shift( @_ ) if( scalar( @_ ) == 1 && $self->_is_hash( $_[0] => 'strict' ) );
50 if( $opts->{bind} )
51 {
52 return( "DATETIME(?, 'unixepoch', 'localtime')" );
53 }
54 else
55 {
56 return( sprintf( "DATETIME(%s, 'unixepoch', 'localtime')", $opts->{value} ) );
57 }
58 }
59  
60 sub format_to_epoch
61 {
62 my $self = shift( @_ );
63 my $opts = {};
64 $opts = shift( @_ ) if( scalar( @_ ) == 1 && $self->_is_hash( $_[0] => 'strict' ) );
65 if( $opts->{bind} )
66 {
67 return( "STRFTIME('%s',?)" );
68 }
69 else
70 {
71 return( sprintf( "STRFTIME('%%s','%s')", $opts->{quote} ? "'" . $opts->{value} . "'" : $opts->{value} ) );
72 }
73 }
74  
75 # _having is in DB::Object::Query
76 # sub having { return( shift->_having( @_ ) ); }
77 sub having { return( shift->_where_having( 'having', 'having', @_ ) ); }
78  
79 # <https://sqlite.org/lang_select.html#limitoffset>
80 # <https://sqlite.org/lang_delete.html>
81 # <https://sqlite.org/lang_update.html>
82 sub limit
83 {
84 my $self = shift( @_ );
85 my $limit = $self->{limit};
86 if( @_ )
87 {
88 # Returns a DB::Object::Query::Clause
89 $limit = $self->_process_limit( @_ ) ||
90 return( $self->pass_error );
91  
92 if( CORE::length( $limit->metadata->limit // '' ) )
93 {
94 $limit->generic( CORE::length( $limit->metadata->offset // '' ) ? 'LIMIT ? OFFSET ?' : 'LIMIT ?' );
95 # %s works for integer, and also for numbered placeholders like $1 or ?1, or regular placeholder like ?
96 $limit->value(
97 CORE::length( $limit->metadata->offset // '' )
98 ? CORE::sprintf( 'LIMIT %s OFFSET %s', $limit->metadata->limit, $limit->metadata->offset )
99 : CORE::sprintf( 'LIMIT %s', $limit->metadata->limit )
100 );
101 }
102 }
103  
104 if( !$limit && want( 'OBJECT' ) )
105 {
106 return( $self->new_null( type => 'object' ) );
107 }
108 return( $limit );
109 }
110  
111 # This implementation in SQLite is essentially identical to PostgreSQL
112 # INSERT INTO vocabulary(word) VALUES('jovial')
113 # ON CONFLICT(word) DO UPDATE SET count=count+1;
114 #
115 # INSERT INTO phonebook(name,phonenumber) VALUES('Alice','704-555-1212')
116 # ON CONFLICT(name) DO UPDATE SET phonenumber=excluded.phonenumber;
117 #
118 #
119 # INSERT INTO phonebook2(name,phonenumber,validDate)
120 # VALUES('Alice','704-555-1212','2018-05-08')
121 # ON CONFLICT(name) DO UPDATE SET
122 # phonenumber=excluded.phonenumber,
123 # validDate=excluded.validDate
124 # WHERE excluded.validDate>phonebook2.validDate;
125 # https://www.sqlite.org/lang_upsert.html
126 # $q->on_conflict({
127 # target => 'id',
128 # action => 'nothing',
129 # action => 'update',
130 # fields => { a => 'some value', b => 'some other' },
131 # });
132 sub on_conflict
133 {
134 my $self = shift( @_ );
135 my $opts = {};
136 $self->{_on_conflict} = {} if( ref( $self->{_on_conflict} ) ne 'HASH' );
137 if( @_ )
138 {
139 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
140 my $ver = $tbl_o->database_object->version;
141 if( version->parse( $ver ) < version->parse( '3.24.0' ) )
142 {
143 return( $self->error( "SQLite version is $ver, but version 3.24.0 of 2018-06-04 or higher is required to use this on conflict clause." ) );
144 }
145 $opts = $self->_get_args_as_hash( @_ );
146 my $hash = {};
147 my @comp = ( 'ON CONFLICT' );
148 if( $opts->{target} )
149 {
150 $hash->{target} = $opts->{target};
151 # Example: ON CONFLICT ON CONSTRAINT customers_name_key DO NOTHING;
152 if( $hash->{target} =~ /^(on[[:blank:]]+constraint)(.*?)$/i )
153 {
154 $hash->{target} = "\U$1\E$2";
155 push( @comp, $hash->{target} );
156 }
157 # a reference to a scalar was provided, so we set the value as is
158 elsif( ref( $hash->{target} ) eq 'SCALAR' )
159 {
160 push( @comp, $$hash->{target} );
161 }
162 elsif( $self->_is_array( $hash->{target} ) )
163 {
164 push( @comp, sprintf( '(%s)', join( ',', @{$hash->{target}} ) ) );
165 }
166 else
167 {
168 push( @comp, sprintf( '(%s)', $hash->{target} ) );
169 }
170 }
171 # https://www.postgresql.org/docs/10/sql-insert.html#SQL-ON-CONFLICT
172 elsif( $opts->{action} ne 'nothing' )
173 {
174 return( $self->error( "No target was specified for the on conflict clause." ) );
175 }
176  
177 if( $opts->{where} )
178 {
179 $hash->{where} = $opts->{where};
180 push( @comp, 'WHERE ' . $opts->{where} );
181 }
182  
183 # action => update
184 if( $opts->{action} )
185 {
186 if( $opts->{action} eq 'update' )
187 {
188 $hash->{action} = $opts->{action};
189 # return( $self->error( "No fields to update was provided for on conflict do update" ) ) if( !$opts->{fields} );
190 # No fields provided, so we take it from the initial insert and build the update list instead
191 if( !$opts->{fields} )
192 {
193 # The insert will have triggered a getdefault() which stores the parameters into a _args object fields
194 # my $f_ref = $self->{ '_args' };
195 # $opts->{inherited_fields} = $self->format_update( $f_ref );
196 $self->{_on_conflict_callback} = sub
197 {
198 my $f_ref = $self->{_args};
199 $self->is_upsert(1);
200 my $inherited_fields = $self->format_update( $f_ref );
201 push( @comp, 'DO UPDATE SET' );
202 push( @comp, $inherited_fields );
203 $hash->{query} = join( ' ', @comp );
204 $self->{_on_conflict} = $hash;
205 $self->{on_conflict} = join( ' ', @comp );
206 # Usable only once
207 CORE::delete( $self->{_on_conflict_callback} );
208 };
209 # Return empty, not undef; undef is error
210 return( '' );
211 }
212 return( $self->error( "Fields property to update for on conflict do update clause is not a hash reference nor an array of fields." ) ) if( !$self->_is_hash( $opts->{fields} => 'strict' ) && !$self->_is_array( $opts->{fields} ) && !$self->{_on_conflict_callback} );
213 if( $self->_is_hash( $opts->{fields} => 'strict' ) )
214 {
215 return( $self->error( "Fields property to update for on conflict do update clause contains no fields!" ) ) if( !scalar( keys( %{$opts->{fields}} ) ) );
216 }
217 elsif( $self->_is_array( $opts->{fields} ) )
218 {
219 return( $self->error( "Fields property to update for on conflict do update clause contains no fields!" ) ) if( !scalar( @{$opts->{fields}} ) );
220 }
221  
222 if( $self->_is_array( $opts->{fields} ) )
223 {
224 my $this = $opts->{fields};
225 my $new = {};
226 foreach my $f ( @$this )
227 {
228 $new->{ $f } = \( 'EXCLUDED.' . $f );
229 }
230 $opts->{fields} = $new;
231 }
232 # Here the user will use the special table 'excluded'
233 $hash->{fields} = $opts->{fields};
234  
235 my $q = [];
236  
237 foreach my $k ( sort( keys( %{$opts->{fields}} ) ) )
238 {
239 push( @$q, sprintf( '%s = %s', $k, ref( $opts->{fields}->{ $k } ) eq 'SCALAR' ? ${$opts->{fields}->{ $k }} : $tbl_o->database_object->quote( $opts->{fields}->{ $k } ) ) );
240 }
241 if( scalar( @$q ) )
242 {
243 push( @comp, 'DO UPDATE SET' );
244 push( @comp, join( ", ", @$q ) );
245 }
246 else
247 {
248 return( $self->error( "A on conflict do update clause was specified, but I could not get a list of fields to update." ) );
249 }
250 }
251 elsif( $opts->{action} eq 'nothing' || $opts->{action} eq 'ignore' )
252 {
253 $hash->{action} = $opts->{action};
254 push( @comp, 'DO NOTHING' );
255 }
256 else
257 {
258 return( $self->error( "Unknown action '$opts->{action}' for on conflict clause." ) );
259 }
260 }
261 else
262 {
263 return( $self->error( "No action was specified for the on conflict clause." ) );
264 }
265 $hash->{query} = join( ' ', @comp );
266 $self->{_on_conflict} = $hash;
267 $self->{on_conflict} = $self->new_clause({ value => join( ' ', @comp ) });
268 }
269 # We are being called possibly by _query_components
270 # If we have a callback, we execute it
271 if( $self->{_on_conflict_callback} && !scalar( @_ ) )
272 {
273 # This will use the insert components set up to format our on conflict clause properly
274 # The callback is needed, because the query formatting occurs after the calling of our method on_conflict()
275 $self->{_on_conflict_callback}->();
276 }
277 return( $self->{on_conflict} );
278 }
279  
280 sub reset
281 {
282 my $self = shift( @_ );
283 if( !$self->{query_reset} )
284 {
285 my $keys = [qw( alias binded binded_values binded_where binded_limit binded_group binded_having binded_order from_unixtime group_by limit local _on_conflict on_conflict order_by reverse sorted unix_timestamp where )];
286 CORE::delete( @$self{ @$keys } );
287 $self->{query_reset}++;
288 $self->{enhance} = 1;
289 }
290 return( $self );
291 }
292  
293 sub reset_bind
294 {
295 my $self = shift( @_ );
296 my @f = qw( binded binded_where binded_group binded_having binded_order binded_limit );
297 foreach my $field ( @f )
298 {
299 $self->{ $field } = [];
300 }
301 return( $self );
302 }
303  
304 # Supported by SQLite since 3.35.0 (2021-03-12)
305 # <https://www.sqlite.org/lang_returning.html>
306 sub returning
307 {
308 my $self = shift( @_ );
309 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
310 if( @_ )
311 {
312 my $pg_version = $self->database_object->version;
313 return( $self->error( "Cannot use returning for PostgreSQL version lower than 3.35.0 (released on 2021-03-12). This server version is: $pg_version" ) ) if( $pg_version < '3.35.0' );
314 # It could be a field name or a wildcard
315 return( $self->error( "A reference was provided (", ref( $_[0] ), "), but I was expecting a string, which could be a field name or even a star (*) indicating all fields." ) ) if( ref( $_[0] ) );
316 $self->{returning} = $self->new_clause({ value => shift( @_ ) });
317 }
318 # return( wantarray() ? () : undef() ) if( !$self->{returning} );
319 # return( wantarray() ? ( $self->{returning} ) : "RETURNING $self->{returning}" );
320 return( $self->{returning} );
321 }
322  
323 # Inherited from DB::Object::Query
324 # sub update
325  
326 sub _query_components
327 {
328 my $self = shift( @_ );
329 my $type = ( @_ > 0 && lc( shift( @_ ) ) ) || $self->_query_type() || return( $self->error( "You must specify a query type: select, insert, update or delete" ) );
330 my $opts = $self->_get_args_as_hash( @_ );
331 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
332 my( $where, $group, $having, $sort, $order, $limit, $returning, $on_conflict );
333 $where = $self->where();
334 $limit = $self->limit();
335 $returning = $self->returning;
336 $on_conflict = $self->on_conflict;
337 if( $type eq 'select' )
338 {
339 $group = $self->group();
340 $having = $self->having();
341 $sort = $self->reverse() ? 'DESC' : $self->sort() ? 'ASC' : '';
342 $order = $self->order();
343 $limit = $self->limit();
344 }
345 elsif( $type eq 'update' || $type eq 'delete' )
346 {
347 if( $tbl_o->can_update_delete_limit )
348 {
349 $limit = $self->limit();
350 }
351 }
352 my @query = ();
353 push( @query, "WHERE $where" ) if( $where && $type ne 'insert' );
354 push( @query, "GROUP BY $group" ) if( $group );
355 push( @query, "HAVING $having" ) if( $having );
356 push( @query, "ORDER BY $order" ) if( $order );
357 push( @query, $sort ) if( $sort && $order);
358 push( @query, $limit ) if( $limit );
359 if( $on_conflict )
360 {
361 if( $type eq 'insert' )
362 {
363 push( @query, $on_conflict );
364 }
365 else
366 {
367 warn( "The SQLite ON CONFLICT clause is only supported for INSERT queries. Your query was of type \"$type\".\n" );
368 }
369 }
370 # Supported as of 3.35.0 (2021-03-12)
371 push( @query, "RETURNING $returning" ) if( $returning && ( $type eq 'insert' || $type eq 'update' || $type eq 'delete' ) );
372 return( \@query );
373 }
374  
375 1;
376 # NOTE: POD
377 __END__
378  
379 =encoding utf-8
380  
381 =head1 NAME
382  
383 DB::Object::SQLite::Query - SQLite Query Object
384  
385 =head1 SYNOPSIS
386  
387 my $q = DB::Object::SQLite::Query->new;
388  
389 =head1 VERSION
390  
391 v0.4.0
392  
393 =head1 DESCRIPTION
394  
395 This is a SQLite specific query object.
396  
397 =head1 METHODS
398  
399 =head2 binded_having
400  
401 Sets or gets the array object (L<Module::Generic::Array>) for the binded value in C<HAVING> clauses.
402  
403 =head2 format_from_epoch
404  
405 This takes the parameters I<bind> and I<value> and returns a formatted C<DATETIME(?, 'unixepoch', 'localtime')> expression.
406  
407 =head2 format_to_epoch
408  
409 This takes the parameters I<bind>, I<value> and I<quote> and returns a formatted expression C<STRFTIME('%s',?)> to returns the epoch value out of the given field.
410  
411 =head2 having
412  
413 Calls L<DB::Object::Query/_where_having> to build a C<having> clause.
414  
415 See L<SQLite documentation for more information|https://www.sqlite.org/lang_select.html>
416  
417 =head2 limit
418  
419 Build a new L<DB::Object::Query::Clause> clause object by calling L</_process_limit> and return it.
420  
421 See L<SQLite documentation for more information|https://sqlite.org/limits.html>
422  
423 =head2 on_conflict
424  
425 Provided with some options and this will build a C<ON CONFLICT> clause (L<DB::Object::Query::Clause>). This is only available for SQLite version 3.35.0 released on 2021-03-12 or above.
426  
427 =over 4
428  
429 =item * C<action>
430  
431 Valid value can be C<nothing> and in which case, nothing will be done by the database upon conflict.
432  
433 INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH')
434 ON CONFLICT (did) DO NOTHING;
435  
436 or
437  
438 INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design')
439 ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;
440  
441 Value can also be C<ignore> instructing the database to simply ignore conflict.
442  
443 If the value is C<update>, then this will set a callback routine to format an update statement using L<DB::Object::Query/format_update>
444  
445 If the original C<insert> or C<update> uses placeholders, then the C<DO UPDATE> will also use the same placeholders and the L<DB::Object::Statement> object will act accordingly when being provided the binded values. That is, it will double them to allocate those binded value also for the C<DO UPDATE> part of the query.
446  
447 The callback will be called by L<DB::Object::Query/insert> or L<DB::Object::Query/update>, because the L</on_conflict> relies on query columns being previously set.
448  
449 =item * C<fields>
450  
451 An array (or array object) of fields to use with I<action> set to C<update>
452  
453 $q->on_conflict({
454 target => 'name',
455 action => 'update,
456 fields => [qw( first_name last_name )],
457 });
458  
459 This will turn the C<DO UPDATE> prepending each field with the special keyword C<EXCLUDED>
460  
461 INSERT INTO distributors (did, dname)
462 VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
463 ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;
464  
465 =item * C<target>
466  
467 Target can be a table column.
468  
469 $q->on_conflict({
470 target => 'name',
471 action => 'ignore',
472 });
473  
474 or it can also be a constraint name:
475  
476 $q->on_conflict({
477 target => 'on constraint my_table_idx_name',
478 action => 'ignore',
479 });
480  
481 Value for I<target> can also be a scalar reference and it will be used as-is
482  
483 $q->on_conflict({
484 target => \'on constraint my_table_idx_name',
485 action => 'ignore',
486 });
487  
488 Value for I<target> can also be an array or array object (like L<Module::Generic::Array>) and the array will be joined using a comma.
489  
490 If no I<target> argument was provided, then I<action> must be set to C<nothing> or this will return an error.
491  
492 =item * C<where>
493  
494 You can also provide a C<WHERE> expression in the conflict and it will be added literally.
495  
496 $q->on_conflict({
497 target => 'did',
498 action => 'ignore',
499 where => 'is_active',
500 });
501  
502 INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International')
503 ON CONFLICT (did) WHERE is_active DO NOTHING;
504  
505 =back
506  
507 See L<SQLite documentation for more information|https://www.sqlite.org/lang_upsert.html>.
508  
509 =head2 reset
510  
511 If the object property C<query_reset> is not already set, this will remove the following properties from the current query object, set L<DB::Object::Query/enhance> to true and return the query object.
512  
513 Properties removed are: alias local binded binded_values binded_where binded_limit binded_group binded_having binded_order where limit group_by order_by reverse from_unixtime unix_timestamp sorted
514  
515 =head2 reset_bind
516  
517 Reset all the following object properties to an anonymous array: binded binded_where binded_group binded_having binded_order binded_limit
518  
519 =head2 returning
520  
521 This feature is available with SQLite version 3.35.0 or above, otherwise an error is returned.
522  
523 It expects a string that is used to build the C<RETURNING> clause.
524  
525 # will instruct the database to return all the table columns
526 $q->returning( '*' );
527  
528 or
529  
530 $q->returning( 'id' );
531  
532 But don't pass a reference:
533  
534 $q->returning( [qw( id name age )] );
535  
536 It returns a new L<DB::Object::SQLite::Query::Clause> object.
537  
538 See L<SQLite documentation for more information|https://www.sqlite.org/lang_returning.html>
539  
540 =head2 _query_components
541  
542 This is called by the various query methods like L<DB::Object::Query/select>, L<DB::Object::Query/insert>, L<DB::Object::Query/update>, L<DB::Object::Query/delete>
543  
544 It will get the various query components (group, having, sort, order, limit) that have been set and add them formatted to an array that is returned.
545  
546 This version of L</_query_components> exists here to provide PostgreSQL specific implementation. See also the generic one in L<DB::Object::Query/_query_components>
547  
548 =head1 SEE ALSO
549  
550 L<perl>
551  
552 =head1 AUTHOR
553  
554 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
555  
556 =head1 COPYRIGHT & LICENSE
557  
558 Copyright (c) 2019-2021 DEGUEST Pte. Ltd.
559  
560 You can use, copy, modify and redistribute this package and associated
561 files under the same terms as Perl itself.
562  
563 =cut