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

filter: Statementstmt 0.0% 0 / 182 Branchbran 0.0% 0 / 102 Conditioncond 0.0% 0 / 63 MC/DCmcdc 0.0% 0 / 36 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 414 CC 52 SCAR 55.2
CC
52
Cov
0%
on_conflict
552.0
_query_components
272.0
limit
42.0
CRAP 250.5
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/SQLite/Query.pm
4 ## Version v0.4.1
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2019/06/16
8 ## Modified 2026/08/05
9 ## All rights reserved
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.##
13 ##----------------------------------------------------------------------------##
14 package DB::Object::SQLite::Query;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'DB::Object' );
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.1';
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( $self->database_object->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\"." ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
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__