blib/lib/DB/Object/Statement.pm untested

filter: Statementstmt 0.0% 0 / 847 Branchbran 0.0% 0 / 422 Conditioncond 0.0% 0 / 426 MC/DCmcdc 0.0% 0 / 234 Subroutinesub 0.0% 0 / 73 Podpod 0.0% 0 / 56 totaltotal 0.0% 0 / 2058 CC 212 SCAR 72.9
CC
212
Cov
0%
join
3782.0
execute
3192.0
fetchall_arrayref
182.0
CRAP 1469.8
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Statement.pm
4 ## Version v0.9.3
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
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 ## This package's purpose is to automatically terminate the statement object and
15 ## separate them from the connection object (DB::Object).
16 ## Connection object last longer than statement objects
17 ##----------------------------------------------------------------------------
18 package DB::Object::Statement;
19 BEGIN
20 {
21 use strict;
22 use warnings;
23 warnings::register_categories( 'DB::Object' );
24 use parent qw( DB::Object );
25 use vars qw( $VERSION $DEBUG $EXCEPTION_CLASS );
26 use Scalar::Util ();
27 use Class::Struct qw( struct );
28 use Wanted;
29 our $DEBUG = 0;
30 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
31 our $VERSION = 'v0.9.3';
32 };
33  
34 use strict;
35 use warnings;
36  
37 sub init
38 {
39 my $self = shift( @_ );
40 $self->{_exception_class} = $EXCEPTION_CLASS;
41 $self->Module::Generic::init( @_ ) || return( $self->pass_error );
42 return( $self );
43 }
44  
45 sub as_string
46 {
47 my $self = shift( @_ );
48 # my $q = $self->_query_object_current;
49 # used by select, insert, update, delete to flag that we need to reformat the query
50 $self->{as_string}++;
51 if( my $qo = $self->query_object )
52 {
53 $qo->final(1);
54 }
55 # return( $self->{sth}->{Statement} );
56 # Same:
57 # return( $q->as_string );
58 return( $self->{query} );
59 }
60  
61 sub attach
62 {
63 my $self = shift( @_ );
64 my $dbo = shift( @_ ) ||
65 return( $self->error( "No DB::Object object was provided." ) );
66 my $base_class = $self->base_class;
67 unless( $self->_is_a( $dbo => $base_class ) )
68 {
69 return( $self->error( "Value provided is not a ${base_class} object." ) );
70 }
71 $self->database_object( $dbo ) || return( $self->pass_error );
72 if( my $tbl = $self->table_object )
73 {
74 if( $self->_is_a( $tbl => "${base_class}::Tables" ) )
75 {
76 $self->_load_class( "${base_class}::Tables" ) || return( $self->pass_error );
77 $tbl->attach( $dbo );
78 }
79 else
80 {
81 warn( "Table object found (", $self->_str_val( $tbl ), ") in this statement object is actually not a table object (${base_class}::Tables) !" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
82 $self->table_object( undef );
83 }
84 }
85 if( my $qo = $self->query_object )
86 {
87 unless( $self->_is_a( $qo => "${base_class}::Query" ) )
88 {
89 die( "Query object found (", $self->_str_val( $qo ), ") in this statement object is actually not a query object (${base_class}::Query) !" );
90 }
91 $self->_load_class( "${base_class}::Query" ) || return( $self->pass_error );
92 $qo->attach( $dbo );
93 }
94 return( $self );
95 }
96  
97 sub bind_param
98 {
99 my $self = shift( @_ );
100 my( $pack, $file, $line ) = caller();
101 my $sub = ( caller(1) )[3];
102 $self->{pack} = $pack;
103 $self->{file} = $file;
104 $self->{line} = $line;
105 $self->{sub} = $sub;
106 my $rc = eval
107 {
108 $self->{sth}->bind_param( @_ );
109 };
110 if( $@ )
111 {
112 my $err = $self->errstr();
113 $err =~ s/ at line \d+.*$//;
114 # printf( STDERR "%s in %s at line %d within sub '%s'.\n", $err, $self->{file}, $self->{line}, $self->{sub} );
115 # exit(1);
116 return( $self->error( $err ) );
117 }
118 elsif( $rc )
119 {
120 return( $rc );
121 }
122 else
123 {
124 my $err = $@ = $self->{sth}->errstr() || "Unknown error while binding parameters to query.";
125 return( $self->error( $err ) );
126 }
127 }
128  
129 sub commit
130 {
131 my $self = shift( @_ );
132 if( $self->{sth} && $self->param( 'autocommit' ) )
133 {
134 my $sth = $self->prepare( 'COMMIT' ) || return( $self->pass_error );
135 $sth->execute() || return( $self->error( "An error occurred while executing query: ", $sth->error ) );
136 $sth->finish();
137 }
138 return( $self );
139 }
140  
141 sub database_object { return( shift->_set_get_object_without_init( 'dbo', 'DB::Object', @_ ) ); }
142  
143 sub distinct
144 {
145 my $self = shift( @_ );
146 my $query = $self->{query} ||
147 return( $self->error( "No query to set as to be ignored." ) );
148  
149 my $type = uc( ( $query =~ /^\s*(\S+)\s+/ )[0] );
150 # ALTER for table alteration statements (DB::Object::Tables
151 my @allowed = qw( SELECT );
152 my $allowed = CORE::join( '|', @allowed );
153 if( !scalar( grep{ /^$type$/i } @allowed ) )
154 {
155 return( $self->error( "You may not flag statement of type \U$type\E to be distinct:\n$query" ) );
156 }
157 # Incompatible. Do not bother going further
158 return( $self ) if( $query =~ /^\s*(?:$allowed)\s+(?:DISTINCT|DISTINCTROW|ALL)\s+/i );
159  
160 $query =~ s/^(\s*)($allowed)(\s+)/$1$2 DISTINCT /;
161 # my $sth = $self->prepare( $query ) ||
162 # $self->{ 'query' } = $query;
163 # saving parameters to bind later on must have been done previously
164 my $sth = $self->_cache_this( $query ) ||
165 return( $self->error( "Error while preparing new ignored query:\n$query" ) );
166 if( !defined( wantarray() ) )
167 {
168 $sth->execute() ||
169 return( $self->error( "Error while executing new ignored query:\n$query" ) );
170 }
171 return( $sth );
172 }
173  
174 sub dump
175 {
176 my $self = shift( @_ );
177 my $file = shift( @_ );
178 if( $file )
179 {
180 # Used to be handled by SQL server
181 # my $query = $self->as_string();
182 # $query =~ s/(\s+FROM\s+)/ INTO OUTFILE '$file'$1/;
183 # my $sth = $self->prepare( $query ) ||
184 # return( $self->error( "Error while preparing query to dump result on select:\n$query" ) );
185 # $sth->execute() ||
186 # return( $self->error( "Error while executing query to dump result on select:\n$query" ) );
187 $self->_load_class( 'DateTime::Lite' ) || return( $self->pass_error );
188 my $fields = $self->{_fields};
189 my @header = sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields );
190 # new_file is inherited from Module::Generic
191 $file = $self->new_file( $file );
192 my $io = $file->open( '>', { binmode => 'utf8' }) ||
193 return( $self->error( "Unable to open file '$file' in write mode: ", $file->error ) );
194 my $date = DateTime::Lite->now;
195 my $table = $self->{table};
196 $io->printf( "## Generated on %s for table $table\n", $date->strftime( '%c' ) );
197 $io->print( "## ", CORE::join( "\t", @header ), "\n" );
198 my @data = ();
199 while( @data = $self->fetchrow() )
200 {
201 print( $io CORE::join( "\t", @data ), "\n" );
202 }
203 $io->close;
204 $self->finish;
205 return( $self );
206 }
207 elsif( exists( $self->{sth} ) )
208 {
209 # my $fields = $self->{ '_fields' };
210 my @fields = @{ $self->{sth}->FETCH( 'NAME' ) };
211 my $max = 0;
212 # foreach my $field ( keys( %$fields ) )
213 foreach my $field ( @fields )
214 {
215 $max = length( $field ) if( length( $field ) > $max );
216 }
217 my $template = '';
218 ## foreach my $field ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) )
219 foreach my $field ( @fields )
220 {
221 $template .= "$field" . ( '.' x ( $max - length( $field ) ) ) . ": %s\n";
222 }
223 $template .= "\n";
224 my @data = ();
225 while( @data = $self->fetchrow() )
226 {
227 printf( STDERR $template, @data );
228 }
229 $self->finish;
230 return( $self );
231 }
232 else
233 {
234 return( $self->error( "No query to dump." ) );
235 }
236 }
237  
238 sub exec { return( shift->execute( @_ ) ); }
239  
240 sub execute
241 {
242 my $self = shift( @_ );
243 my @args = @_;
244 # Resolve caller context only when needed for error reporting or debug.
245 # Calling caller() unconditionally on every execute() is expensive.
246 if( $self->debug || !$self->{pack} )
247 {
248 my( $pack, $file, $line ) = caller();
249 my $sub = ( caller(1) )[3];
250 # What we want is to get the point from where we were originatly called
251 my $class = 'DB::Object';
252 if( substr( $pack, 0, length( $class ) ) eq $class )
253 {
254 for( my $i = 1; $i < 5; $i++ )
255 {
256 ( $pack, $file, $line ) = caller( $i );
257 $sub = ( caller( $i + 1 ) )[3];
258 last if( substr( $pack, 0, length( $class ) ) ne $class );
259 }
260 }
261 $self->{pack} = $pack;
262 $self->{file} = $file;
263 $self->{line} = $line;
264 $self->{sub} = $sub;
265 }
266 $self->{executed}++;
267 my $q = $self->query_object;
268 $q->final(1) if( $q );
269 my @binded = ();
270 my @binded_types = ();
271 # Boolean used so we do not automatically change a string litteral into an array if
272 # the number of types and values are not the same, as it would lead to undesirable results.
273 my $bind_mismatch = 0;
274 my $el;
275 # As a rule, if the first placeholder is a numbered one, then all are, because we cannot mix numbered placeholder and non-numbered ones.
276 my $use_numbered_placeholders = ( ( $q && $q->elements->first->is_numbered ) ? 1 : 0 );
277 if( $q &&
278 ( $el = $q->elements ) &&
279 $el->types->length )
280 {
281 my $types = $q->binded_types_as_param;
282 @binded_types = @$types;
283 }
284  
285 if( defined( $el ) )
286 {
287 }
288  
289 # Get the values to bind
290 if( $q && $self->{bind} )
291 {
292 if( @_ &&
293 (
294 # hash reference
295 ( @_ == 1 && $self->_is_hash( $_[0] => 'strict' ) ) ||
296 # key => value pairs
297 ( !( @_ % 2 ) && ref( $_[0] ) ne 'HASH' )
298 )
299 )
300 {
301 my $vals = {};
302 if( $self->_is_hash( $_[0] => 'strict' ) )
303 {
304 $vals = shift( @_ );
305 }
306 else
307 {
308 $vals = { @_ };
309 }
310 # This is the list of fields as they appear in the order in insert or update query
311 # Knowing their order of appearance is key so we can bind follow-on values to them
312 my $sorted = $q->sorted;
313 foreach my $f ( @$sorted )
314 {
315 if( !CORE::exists( $vals->{ $f } ) )
316 {
317 push( @binded, undef() );
318 }
319 # The value may be defined or not, or may be zero length long
320 else
321 {
322 push( @binded, $vals->{ $f } );
323 }
324 }
325 }
326 elsif( @_ )
327 {
328 push( @binded, @_ );
329 }
330 else
331 {
332 # my $binded_values = $q->binded;
333 my $binded_values = $q->elements->values;
334 push( @binded, @$binded_values ) if( scalar( @$binded_values ) );
335 }
336 }
337  
338 @binded = @_ if( !@binded && @_ );
339 @binded = () if( !@binded );
340 if( $q && $q->is_upsert )
341 {
342 if( !$use_numbered_placeholders &&
343 scalar( @binded_types ) > scalar( @binded ) )
344 {
345 CORE::push( @binded, @binded );
346 }
347 }
348  
349 if( scalar( @_ ) )
350 {
351 my $temp = {};
352 my $el;
353 $el = $q->elements->elements if( $q && $q->elements );
354 local $" = ', ';
355 for( my $i = 0; $i < scalar( @args ); $i++ )
356 {
357 # { $some_value => 'varchar' }
358 if( ref( $_[$i] ) eq 'HASH' &&
359 scalar( keys( %{$_[$i]} ) ) == 1 &&
360 $self->database_object->datatype_to_constant( [values( %{$_[$i]} )]->[0] ) )
361 {
362 my $constant = $self->database_object->datatype_to_constant( [values( %{$_[$i]} )]->[0] );
363 $temp->{$i} = { type => $constant, value => [keys( %{$_[$i]} )]->[0] };
364 }
365 elsif( ref( $_[$i] ) eq 'HASH' &&
366 scalar( keys( %{$_[$i]} ) ) == 1 &&
367 # e.g. DBI::SQL_VARCHAR or DBI::SQL_INTEGER
368 DBI->can( "SQL_" . uc( [values( %{$_[$i]} )]->[0] ) ) )
369 {
370 my $constant = DBI->can( "SQL_" . uc( [values( %{$_[$i]} )]->[0] ) );
371 $temp->{$i} = { type => $constant->(), value => [keys( %{$_[$i]} )]->[0] };
372 }
373 }
374  
375 # The user has chosen to override any datatype computed and be explicit.
376 if( scalar( keys( %$temp ) ) == scalar( @_ ) )
377 {
378 # @binded = @_;
379 @binded_types = ();
380 @binded = ();
381 foreach my $i ( sort( keys( %$temp ) ) )
382 {
383 push( @binded_types, $temp->{ $i }->{type} );
384 push( @binded, $temp->{ $i }->{value} );
385 }
386 }
387 elsif( scalar( keys( %$temp ) ) )
388 {
389 foreach my $i ( sort( keys( %$temp ) ) )
390 {
391 CORE::splice( @binded_types, $i, 1, $temp->{ $i }->{type} );
392 $binded[$i] = $temp->{ $i }->{value};
393 }
394 }
395 }
396  
397 if( $q && scalar( @binded ) != scalar( @binded_types ) )
398 {
399 # Flag we use a bit below
400 $bind_mismatch++;
401 warn( sprintf( "Warning: total %d bound values does not match the total %d bound types ('%s')! Check the code for query $self->{sth}->{Statement}", scalar( @binded ), scalar( @binded_types ), CORE::join( "','", map{ ref( $_ ) eq 'HASH' ? $self->Module::Generic::dump( $_ ) : $_ } @binded_types ) ) ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
402 # Cancel it, because it will create problems
403 @binded_types = ();
404 }
405  
406 # If there are any array object of some sort provided, make sure they are transformed into a regular array so DBD::Ph can then transform it into a Postgres array.
407 for( my $i = 0; $i < scalar( @binded ); $i++ )
408 {
409 next if( !defined( $binded[$i] ) );
410 my $elem;
411 if( defined( $el ) &&
412 !$bind_mismatch &&
413 ( $elem = $el->elements->[$i] ) &&
414 defined( $elem ) &&
415 $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) )
416 {
417 }
418  
419 if( defined( $el ) &&
420 !$bind_mismatch &&
421 ( $elem = $el->elements->[$i] ) &&
422 defined( $elem ) &&
423 $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) &&
424 $elem->fo->is_array &&
425 !$self->_is_array( $binded[$i] ) &&
426 defined( $binded[$i] ) )
427 {
428 $binded[$i] = $self->_is_number( $binded[$i] ) ? [$binded[$i]] : [$self->database_object->quote( $binded[$i] )];
429 }
430 elsif( defined( $el ) &&
431 !$bind_mismatch &&
432 ( $elem = $el->elements->[$i] ) &&
433 defined( $elem ) &&
434 $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) &&
435 ( ( $elem->fo->type // '' ) eq 'jsonb' || ( $elem->fo->type // '' ) eq 'json' ) &&
436 $self->_is_hash( $binded[$i] => 'strict' ) )
437 {
438 # try-catch
439 local $@;
440 my $json = eval
441 {
442 $self->new_json->encode( $binded[$i] );
443 };
444 if( $@ )
445 {
446 warn( "Error trying to encode hash value ", $binded[$i], ": $@" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
447 }
448 else
449 {
450 $binded[$i] = $json;
451 }
452 }
453 # If the value provided is a DateTime::Lite object without a formatter, we transform the given value into a ISO8601 datetime string
454 elsif( defined( $el ) &&
455 !$bind_mismatch &&
456 ( $elem = $el->elements->[$i] ) &&
457 defined( $elem ) &&
458 $self->_is_a( $elem->fo => 'DB::Object::Fields::Field' ) &&
459 ( ( $elem->fo->type // '' ) =~ /^(date|timestamp)/i || $elem->fo->datatype->alias->grep( qr/^(date|timestamp)/i )->length ) &&
460 defined( $binded[$i] ) &&
461 $self->_is_a( $binded[$i] => [qw( DateTime DateTime::Lite )] ) &&
462 # There is no formatter, or it is set to a Unix timestamp
463 ( !$binded[$i]->formatter || ( $binded[$i]->stringify // '' ) =~ /^\d+$/ ) )
464 {
465 $binded[$i] = $binded[$i]->iso8601;
466 }
467  
468 # The value is an array object, but not a simple array, so we need to convert it
469 # or else the driver will not understand nor accept it.
470 if( $self->_is_array( $binded[$i] ) &&
471 ref( $binded[$i] ) ne 'ARRAY' )
472 {
473 $binded[$i] = [@{$binded[$i]}];
474 }
475 elsif( $self->_is_a( $binded[$i] => [qw( DateTime::Lite DateTime )] ) )
476 {
477 $binded[$i] = $binded[$i]->iso8601;
478 }
479 elsif( $self->_is_object( $binded[$i] ) &&
480 overload::Overloaded( $binded[$i] ) &&
481 overload::Method( $binded[$i], '""' ) )
482 {
483 no warnings 'uninitialized';
484 my $v = "$binded[$i]";
485 $binded[$i] = defined( $v ) ? $v : undef;
486 }
487 # Will work well with Module::Generic::Hash
488 elsif( $self->_is_hash( $binded[$i] ) &&
489 $self->_can( $binded[$i], 'as_json' ) )
490 {
491 $binded[$i] = $binded[$i]->as_json;
492 }
493 elsif( $self->_is_hash( $binded[$i] => 'strict' ) )
494 {
495 # try-catch
496 local $@;
497 my $json = eval
498 {
499 $self->new_json->encode( $binded[$i] );
500 };
501 if( $@ )
502 {
503 warn( "Error trying to encode hash value ", $binded[$i], ": $@" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
504 }
505 else
506 {
507 $binded[$i] = $json;
508 }
509 }
510 }
511  
512 local $_;
513 my $rv = eval
514 {
515 local( $SIG{ALRM} ) = sub{ die( "Timeout while processing query $self->{sth}->{Statement}\n" ) };
516 for( my $i = 0; $i < scalar( @binded ); $i++ )
517 {
518 # Stringify the binded value if it is a stringifyable object.
519 if( ref( $binded[$i] ) &&
520 $self->_is_object( $binded[$i] ) &&
521 overload::Overloaded( $binded[$i] ) &&
522 overload::Method( $binded[$i], '""' ) )
523 {
524 $binded[$i] .= '';
525 }
526  
527 my $data_type = $binded_types[ $i ];
528 if( CORE::length( $data_type ) && $self->_is_hash( $data_type ) )
529 {
530 $self->{sth}->bind_param( $i + 1, $binded[ $i ], $data_type );
531 }
532 else
533 {
534 $self->{sth}->bind_param( $i + 1, $binded[ $i ] );
535 }
536 }
537 $self->{sth}->execute();
538 };
539 my $error = $@;
540 $error ||= $self->{sth}->errstr if( !$rv );
541 if( $q )
542 {
543 # Only reset the table's query object if this is NOT a cached/reused joined statement.
544 # For joined statements, the query object ($q_source) is permanently attached to the
545 # statement handle and resetting the table creates a new ~500KB query object on every
546 # execute() that is never freed (the old one is orphaned). The reset serves to prepare
547 # the table for a fresh query after a one-shot select(), which is not the case here.
548 # A joined statement is identified by having join_tables populated.
549 # For a joined statement that is reused in a loop (exec() called multiple times),
550 # calling reset() on any of the tables is wasteful: it creates a new ~500KB query
551 # object for every single exec() call, and those objects are never freed because the
552 # allocator retains the arena pages. The reset was designed for one-shot select()
553 # usage, not for reused prepared statements. Skip it entirely for joined statements.
554 if( $q->join_tables->length == 0 )
555 {
556 $q->table_object->reset;
557 }
558 }
559 my $tie = $self->{tie} || {};
560 # Maybe it is time to bind SQL result to possible provided perl variables?
561 if( !$error && %$tie )
562 {
563 my $order = $self->{tie_order};
564 my $sth = $self->{sth};
565 for( my $i = 0; $i < @$order; $i++ )
566 {
567 my $pos = $i + 1;
568 my $val = $order->[ $i ];
569 if( exists( $tie->{ $val } ) && ref( $tie->{ $val } ) eq 'SCALAR' )
570 {
571 $sth->bind_col( $pos, $tie->{ $val } );
572 }
573 }
574 }
575 if( $error )
576 {
577 if( $error =~ / at (\S+\s)?line \d+.*$/ )
578 {
579 $error =~ s/ at (\S+\s)?line \d+.*$//s;
580 }
581 # $err .= ":\n\"$self->{ 'query' }\"";
582 # $error .= ":\n\"$self->{sth}->{Statement}\"";
583 $error = "Error while trying to execute query $self->{sth}->{Statement}: $error";
584 if( $self->fatal() )
585 {
586 die( "$error in $self->{file} at line $self->{line} within sub $self->{sub}\n" );
587 }
588 else
589 {
590 # return( $self->error( "$err in $self->{ 'file' } at line $self->{ 'line' } within sub $self->{ 'sub' }" ) );
591 return( $self->error( $error ) );
592 }
593 }
594 elsif( $self->{sth}->errstr() )
595 {
596 return( $self->error( "Error while trying to execute query $self->{sth}->{Statement}: ", $self->{sth}->errstr ) );
597 }
598 # Clear any error, since this query statement may be re-used
599 $self->clear_error;
600  
601 # User wants an object for chaining like:
602 # $sth->exec( 'some value' )->fetchrow;
603 if( want( 'OBJECT' ) )
604 {
605 return( $self );
606 }
607 elsif( $rv )
608 {
609 return( $rv );
610 }
611 # For void context too
612 else
613 {
614 return(1);
615 }
616 }
617  
618 sub executed
619 {
620 my $self = shift( @_ );
621 # For hand made query to avoid clash when executing generic routine such as fetchall_arrayref...
622 return( 1 ) if( !exists( $self->{query} ) );
623 return( exists( $self->{executed} ) && $self->{executed} );
624 }
625  
626 sub fetchall_arrayref($@)
627 {
628 my $self = shift( @_ );
629 my $slice = shift( @_ ) || [];
630 my $dbo = $self->database_object;
631 my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" );
632 if( !$self->executed() )
633 {
634 $self->execute() || return;
635 }
636 # Ensure we set the cache of field names and types. We will need them to post process the query results with _convert_datetime2object()
637 # This is necessary for MySQL whose object lose that information, while the PostgreSQL or SQLite driver keep the information.
638 my $need_post_processing = ( ( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object ) ? 1 : 0 );
639 if( $need_post_processing )
640 {
641 $self->_cache_field_names;
642 $self->_cache_field_types;
643 }
644 # $self->_cleanup();
645 my $mode = ref( $slice );
646 my @rows;
647 my $row;
648 if( $mode eq 'ARRAY' )
649 {
650 if( @$slice )
651 {
652 push( @rows, [ @{$row}[ @$slice ] ] ) while( $row = $sth->fetch() );
653 }
654 else
655 {
656 push( @rows, [ @$row ] ) while( $row = $sth->fetch );
657 }
658 }
659 elsif( $mode eq 'HASH' )
660 {
661 my @o_keys = keys( %$slice );
662 if( @o_keys )
663 {
664 # my %i_names = map{ ( lc( $_ ) => $_ ) } @{ $sth->FETCH( 'NAME' ) };
665 # my @i_keys = map{ $i_names{ lc( $_ ) } } @o_keys;
666 my $i_keys = $self->field_names_lc;
667 while( $row = $sth->fetchrow_hashref() )
668 {
669 my %hash;
670 @hash{ @o_keys } = @{$row}{ @$i_keys };
671 push( @rows, \%hash );
672 }
673 }
674 else
675 {
676 push( @rows, $row ) while( $row = $sth->fetchrow_hashref() );
677 }
678 }
679 else
680 {
681 warn( "fetchall_arrayref($mode) invalid" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
682 }
683  
684 if( !scalar( @rows ) && $sth->err )
685 {
686 $self->error({ code => $sth->err, message => $sth->errstr });
687 }
688 # return( \@rows );
689 return( \@rows ) if( !$need_post_processing );
690 my $data = \@rows;
691 $data = $self->_convert_json2hash({ statement => $sth, data => $data }) if( $dbo->auto_decode_json );
692 $data = $self->_convert_datetime2object({ statement => $sth, data => $data }) if( $dbo->auto_convert_datetime_to_object );
693 return( $data );
694 }
695  
696 sub fetchcol($;$)
697 {
698 my $self = shift( @_ );
699 # @arr = $sth->fetchcol( $col_number );
700 my $col_num = shift( @_ );
701 my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" );
702 if( !$self->executed() )
703 {
704 $self->execute() || return( $self->pass_error );
705 }
706 # $self->_cleanup();
707 # return( $h->fetchcol( $COL_NUM ) );
708 my @col;
709 # $self->dataseek( 0 );
710 my $ref;
711 while( $ref = $self->{sth}->fetchrow_arrayref() )
712 {
713 push( @col, $ref->[ $col_num ] );
714 }
715 if( !defined( $ref ) && $sth->err )
716 {
717 $self->error({ code => $sth->err, message => $sth->errstr });
718 }
719 return( @col );
720 }
721  
722 sub fetchhash(@)
723 {
724 my $self = shift( @_ );
725 my $dbo = $self->database_object;
726 my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" );
727 if( !$self->executed() )
728 {
729 $self->execute() || return( $self->pass_error );
730 }
731 # Ensure we set the cache of field names and types. We will need them to post process the query results with _convert_datetime2object()
732 # This is necessary for MySQL whose object lose that information, while the PostgreSQL or SQLite driver keep the information.
733 if( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object )
734 {
735 $self->_cache_field_names;
736 $self->_cache_field_types;
737 }
738 # $self->_cleanup();
739 # %hash = $sth->fetchhash;
740 # return( $h->fetchhash );
741 my $ref = $sth->fetchrow_hashref();
742 if( !defined( $ref ) && $sth->err )
743 {
744 $self->error({ code => $sth->err, message => $sth->errstr });
745 }
746 if( $ref )
747 {
748 if( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object )
749 {
750 $ref = $self->_convert_json2hash({ statement => $sth, data => $ref }) if( $dbo->auto_decode_json );
751 $ref = $self->_convert_datetime2object({ statement => $sth, data => $ref }) if( $dbo->auto_convert_datetime_to_object );
752 }
753 return( %$ref );
754 }
755 else
756 {
757 return( () );
758 }
759 }
760  
761 sub fetchrow(@)
762 {
763 my $self = shift( @_ );
764 my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" );
765 if( !$self->executed() )
766 {
767 $self->execute() || return( $self->pass_error );
768 }
769 # $self->_cleanup();
770 # @arr = $sth->fetchrow; # Array context
771 # $firstcol = $sth->fetchrow; # Scalar context
772 # return( $h->fetchrow );
773 # my $ref = $self->fetchrow_arrayref();
774 my $ref = $sth->fetchrow_arrayref();
775 if( !defined( $ref ) && $sth->err )
776 {
777 $self->error({ code => $sth->err, message => $sth->errstr });
778 }
779 # my $ref = $self->{sth}->fetch();
780 if( $ref )
781 {
782 return( wantarray ? @$ref : $ref->[0] );
783 }
784 else
785 {
786 return( () );
787 }
788 }
789  
790 # sub fetchrow_hashref(@) is inherited from DBI
791 sub fetchrow_hashref
792 {
793 my $self = shift( @_ );
794 my $dbo = $self->database_object;
795 my $deb = {};
796 %$deb = %$self;
797 my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" );
798 if( !$self->executed() )
799 {
800 $self->execute() || return( $self->pass_error );
801 }
802 # Ensure we set the cache of field names and types. We will need them to post process the query results with _convert_datetime2object()
803 # This is necessary for MySQL whose object lose that information, while the PostgreSQL or SQLite driver keep the information.
804 if( $dbo->auto_decode_json || $dbo->auto_convert_datetime_to_object )
805 {
806 $self->_cache_field_names;
807 $self->_cache_field_types;
808 }
809 my $ref = $sth->fetchrow_hashref;
810 # DBI documentation says:
811 # "If there are no more rows or if an error occurs, then fetchrow_hashref returns an undef. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the undef returned was due to an error."
812 # Also: <https://metacpan.org/pod/DBI#errstr>
813 if( !defined( $ref ) && $sth->err )
814 {
815 $self->error({ code => $sth->err, message => $sth->errstr });
816 }
817 $ref = $self->_convert_json2hash({ statement => $sth, data => $ref }) if( $dbo->auto_decode_json );
818 $ref = $self->_convert_datetime2object({ statement => $sth, data => $ref }) if( $dbo->auto_convert_datetime_to_object );
819 return( $ref );
820 }
821  
822 sub fetchrow_object
823 {
824 my $self = shift( @_ );
825 # This should give us something like Postgres or Mysql or SQLite
826 my $basePack = ( ref( $self ) =~ /^DB::Object::([^\:]+)/ )[0];
827 my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" );
828 if( !$self->executed() )
829 {
830 $self->execute() || return( $self->pass_error );
831 }
832 # $self->_cleanup();
833 my $rows = $self->{sth}->rows;
834 my $ref = $self->{sth}->fetchrow_hashref();
835 # DBI documentation says:
836 # "If there are no more rows or if an error occurs, then fetchrow_hashref returns an undef. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the undef returned was due to an error."
837 if( !defined( $ref ) && $sth->err )
838 {
839 $self->error({ code => $sth->err, message => $sth->errstr });
840 }
841 if( $ref && scalar( keys( %$ref ) ) )
842 {
843 my $struct = { map{ $_ => '$' } keys( %$ref ) };
844 my $table = $self->table;
845 my $class = "DB::Object::${basePack}::Result::${table}";
846 if( !defined( &{ $class . '::new' } ) )
847 {
848 struct $class => $struct;
849 }
850 my $obj = $class->new( %$ref );
851 return( $obj );
852 }
853 else
854 {
855 return( () );
856 }
857 }
858  
859 # NOTE: field_names -> NAME
860 # <https://metacpan.org/pod/DBI#NAME>
861 sub field_names { return( shift->_get_statement_attribute( 'NAME' ) ); }
862  
863 # NOTE: field_names_lc -> NAME_lc
864 # <https://metacpan.org/pod/DBI#NAME_lc>
865 sub field_names_lc { return( shift->_get_statement_attribute( 'NAME_lc' ) ); }
866  
867 # NOTE: field_names_uc -> NAME_uc
868 # <https://metacpan.org/pod/DBI#NAME_uc>
869 sub field_names_uc { return( shift->_get_statement_attribute( 'NAME_uc' ) ); }
870  
871 # NOTE: field_nullables -> NULLABLE
872 # <https://metacpan.org/pod/DBI#NULLABLE>
873 sub field_nullables { return( shift->_get_statement_attribute( 'NULLABLE' ) ); }
874  
875 # NOTE: field_precisions -> PRECISION
876 # <https://metacpan.org/pod/DBI#PRECISION>
877 sub field_precisions { return( shift->_get_statement_attribute( 'PRECISION' ) ); }
878  
879 # NOTE: field_scales -> SCALE
880 # <https://metacpan.org/pod/DBI#SCALE>
881 sub field_scales { return( shift->_get_statement_attribute( 'SCALE' ) ); }
882  
883 # NOTE: field_types -> TYPE
884 # <https://metacpan.org/pod/DBI#TYPE>
885 sub field_types { return( shift->_get_statement_attribute( 'TYPE' ) ); }
886  
887 sub finish
888 {
889 my $self = shift( @_ );
890 my $rc = $self->{sth}->finish();
891 if( !$rc )
892 {
893 return( $self->error( $self->{sth}->errstr() ) );
894 }
895 else
896 {
897 return( $rc );
898 }
899 }
900  
901 sub ignore
902 {
903 my $self = shift( @_ );
904 my $query = $self->{query} ||
905 return( $self->error( "No query to set as to be ignored." ) );
906  
907 my $type = uc( ( $query =~ /^\s*(\S+)\s+/ )[0] );
908 # ALTER for table alteration statements (DB::Object::Tables
909 my @allowed = qw( INSERT UPDATE ALTER );
910 my $allowed = CORE::join( '|', @allowed );
911 if( !scalar( grep{ /^$type$/i } @allowed ) )
912 {
913 return( $self->error( "You may not flag statement of type \U$type\E to be ignored:\n$query" ) );
914 }
915 # Incompatible. Do not bother going further
916 return( $self ) if( $query =~ /^\s*(?:$allowed)\s+(?:DELAYED|LOW_PRIORITY|HIGH_PRIORITY)\s+/i );
917 return( $self ) if( $type eq 'ALTER' && $query !~ /^\s*$type\s+TABLE\s+/i );
918  
919 $query =~ s/^(\s*)($allowed)(\s+)/$1$2 IGNORE /;
920 # my $sth = $self->prepare( $query ) ||
921 # $self->{ 'query' } = $query;
922 # saving parameters to bind later on must have been done previously
923 my $sth = $self->_cache_this( $query ) ||
924 return( $self->error( "Error while preparing new ignored query:\n$query" ) );
925 if( !defined( wantarray() ) )
926 {
927 $sth->execute() ||
928 return( $self->error( "Error while executing new ignored query:\n$query" ) );
929 }
930 return( $sth );
931 }
932  
933 sub join
934 {
935 my $self = shift( @_ );
936 my $data = shift( @_ );
937 my $on;
938 if( @_ )
939 {
940 $on = ( scalar( @_ ) == 1 && ref( $_[0] ) ) ? shift( @_ ) : [ @_ ];
941 }
942 my $q = $self->query_object || return( $self->error( "No query formatter object was set" ) );
943 my $tbl_o = $q->table_object || return( $self->error( "No table object is set in query object." ) );
944 my $query = $q->query ||
945 return( $self->error( "No query prepared for join with another table." ) );
946 if( $query !~ /^[[:blank:]]*SELECT[[:blank:]]+/i )
947 {
948 return( $self->error( "You may not perform a join on a query other than select." ) );
949 }
950 my $constant = $q->constant;
951 # Constant is set and query object marked as final, which means this statement has already been processed as a join and so we skip all further processing.
952 if( scalar( keys( %$constant ) ) && $q->final )
953 {
954 return( $self );
955 }
956 my $table = $tbl_o->table;
957 my $db = $tbl_o->database;
958 my $multi_db = $tbl_o->prefix_database;
959 my $alias = $tbl_o->as;
960 my $new_fields = '';
961 my $new_table = '';
962 my $new_db = '';
963 my $class = ref( $self );
964 my $q_source = $q->clone;
965 # clone() does a shallow copy - $q_source->{elements} would share the same object
966 # as $q->{elements}. Any subsequent _save_bind() on $q would then corrupt the
967 # element list of the cached statement. We reset elements here so $q_source gets
968 # its own fresh object, populated by _query_components below.
969 $q_source->{elements} = $q_source->new_elements;
970 # clone() copies the hash shallowly, which means {table_object} is a strong reference
971 # in the clone even though _query_object_create() weakens it for freshly created query
972 # objects. If left strong, $q_source permanently retains the table object, which in turn
973 # retains every new query object created by _reset_query() on each execute() cycle,
974 # causing an ~8 MB per-iteration memory leak. Weaken it here to restore correct ownership.
975 Scalar::Util::weaken( $q_source->{table_object} ) if( $q_source->{table_object} && !Scalar::Util::isweak( $q_source->{table_object} ) );
976 Scalar::Util::weaken( $q_source->{database_object} ) if( $q_source->{database_object} && !Scalar::Util::isweak( $q_source->{database_object} ) );
977  
978 my $q_target;
979 # On the duplicated table object, add the current table in the join
980 $q_source->join_tables( $tbl_o ) if( !$q_source->join_tables->length );
981 # $data is a DB::Object::Postgres::Statement object - we get all its parameter and merge them with ours
982 # if( ref( $data ) && ref( $data ) eq $class )
983 if( ref( $data ) && $self->_is_a( $data, $class ) )
984 {
985 $q_target = $data->query_object;
986 }
987 # $data is the table name
988 else
989 {
990 my $join_tbl;
991 if( $self->_is_object( $data ) && $data->isa( 'DB::Object::Tables' ) )
992 {
993 $join_tbl = $data;
994 }
995 elsif( $self->_is_object( $data ) )
996 {
997 return( $self->error( "I was expecting either a table name as a scalar or a table object, but instead got \"$data\" (", ref( $data ), ")." ) );
998 }
999 else
1000 {
1001 return( $self->error( "No such table \"$data\" exists in database \"$db\"." ) ) if( !$self->database_object->table_exists( $data ) );
1002 $join_tbl = $self->database_object->table( $data );
1003 return( $self->error( "Could not get a table object from \"$data\"." ) ) if( !$join_tbl );
1004 }
1005 $join_tbl->prefixed( $db ne $join_tbl->database_object->database ? 3 : 1 );
1006 my $sth_tmp = $join_tbl->select || return( $self->pass_error( $join_tbl->error ) );
1007 $q_target = $sth_tmp->query_object ||
1008 return( $self->error( "Could not get a query object out of the dummy select query I made from table \"$data\"." ) );
1009 $new_fields = $q_target->selected_fields;
1010 # NOTE: 2021-08-22: If we reset it here, we lose the table aliasing
1011 # $join_tbl->reset;
1012  
1013 # $join_tbl->prefixed( $db ne $join_tbl->database_object->database ? 3 : 1 ) unless( $join_tbl->prefixed );
1014 $new_table = $join_tbl->prefix;
1015 $join_tbl->reset;
1016 # We assume this table is part of our same database
1017 $new_db = $db;
1018 # my $db_data = $self->getdefault( $new_table );
1019 # $new_fields = $db_data->format_statement();
1020 $new_fields = '';
1021 }
1022 # TODO: check this or remove it
1023 # $q_target->table_object->prefixed( $db ne $q_target->database_object->database ? 3 : 1 );
1024 $new_fields = $q_target->selected_fields;
1025 $new_table = $q_target->table_object->name;
1026 # $new_table = $q_target->table_object->prefix;
1027 $new_db = $q_target->database_object->database;
1028 $q_source->join_tables->push( $q_target->table_object );
1029 if( $q->where && $q_target->where )
1030 {
1031 # We must NOT call $q_source->where( AND(...) ) here because _where_having would
1032 # reconstruct the WHERE via process_where_condition, losing the bind elements that
1033 # were built up in $q->where. Instead we build a merged Clause directly, copying
1034 # the existing elements from $q->where so they are available to _save_bind below.
1035 my $merged = $q_source->new_clause;
1036 $merged->merge( $self->AND( $q->where, $q_target->new_clause({ value => '( ' . ( $q_target->where ) . ' )' }) ) );
1037 $q_source->{where} = $merged;
1038 }
1039 elsif( $q_target->where )
1040 {
1041 $q_source->where( $q_target->where );
1042 }
1043 if( my $group_target = $q_target->group )
1044 {
1045 $q_source->group( $group_target ) if( $group_target->value->length );
1046 }
1047 if( my $order_target = $q_target->order )
1048 {
1049 $q_source->order( $order_target ) if( $order_target->value->length );
1050 }
1051  
1052 if( ( !$q_source->limit || ( $q_source->limit && !$q_source->limit->length ) ) &&
1053 $q_source->limit && $q_source->limit->length )
1054 {
1055 $q_source->limit( $q_target->limit );
1056 }
1057  
1058 my $prev_fields = length( $q->join_fields ) ? $q->join_fields : $q->selected_fields;
1059 # Regular express to prepend previous fields by their table name if that's not the case already
1060 $tbl_o->prefixed( $db ne $new_db ? 3 : 1 );
1061 # Prefix for previous fields list
1062 my $prev_prefix = $tbl_o->prefix;
1063 my $prev_fields_hash = $q->table_object->fields;
1064 my $prev_fields_list = CORE::join( '|', sort( keys( %$prev_fields_hash ) ) );
1065 my $re = qr/(?<![\.\"])\b($prev_fields_list)\b/;
1066 $prev_fields =~ s/(?<![\.\"])\b($prev_fields_list)\b/${prev_prefix}.$1/gs;
1067 my $fields = $new_fields ? CORE::join( ', ', $prev_fields, $new_fields ) : $prev_fields;
1068 $q_source->join_fields( $fields );
1069 $q_source->from_table->push(
1070 $q_source->table_alias
1071 ? sprintf( '%s AS %s', $q_source->table_object->name, $q_source->table_alias )
1072 : ( $q_source->table_object->prefixed ? $q_source->table_object->prefix : $q_source->table_object->name )
1073 ) if( !$q_source->from_table->length );
1074 my $left_join = '';
1075 my $condition = '';
1076 my $format_condition;
1077 $format_condition = sub
1078 {
1079 my @vals = ();
1080 my $vals = shift( @_ );
1081 my $op = shift( @_ );
1082 my @res = ();
1083 my $fields_tables = {};
1084 while( scalar( @$vals ) )
1085 {
1086 if( $self->_is_object( $vals->[0] ) && $vals->[0]->isa( 'DB::Object::Operator' ) )
1087 {
1088 my $sub_obj = shift( @$vals );
1089 my $sub_op = $sub_obj->operator;
1090 my( @sub_vals ) = $sub_obj->value;
1091 my $this_ref = $format_condition->( \@sub_vals, $sub_op );
1092 CORE::push( @res, $this_ref->{clause} ) if( length( $this_ref->{clause} ) );
1093 my $tmp = $this_ref->{fields_tables};
1094 my @those_table_names = keys( %$tmp );
1095 @$fields_tables{ @those_table_names } = @$tmp{ @those_table_names };
1096 }
1097 else
1098 {
1099 if( $self->_is_object( $vals->[0] ) && $vals->[0]->isa( 'DB::Object::Fields::Overloaded' ) )
1100 {
1101 my $f1 = shift( @$vals );
1102 $f1->field->prefixed( $multi_db ? 3 : 1 );
1103 CORE::push( @res, "$f1" );
1104 $fields_tables->{ $f1->field->table }++ if( !$fields_tables->{ $f1->field->table } );
1105 next;
1106 }
1107  
1108 my( $f1, $f2 ) = ( shift( @$vals ), shift( @$vals ) );
1109 my $i_am_negative = 0;
1110 if( $self->_is_object( $f2 ) && $f2->isa( 'DB::Object::NOT' ) )
1111 {
1112 ( $f2 ) = $f2->value;
1113 $i_am_negative++;
1114 }
1115  
1116 my( $field1, $field2 );
1117 if( $self->_is_object( $f1 ) && $f1->isa( 'DB::Object::Fields::Field' ) )
1118 {
1119 $f1->prefixed( $multi_db ? 3 : 1 );
1120 $field1 = $f1->name;
1121 $fields_tables->{ $f1->table }++ if( !$fields_tables->{ $f1->table } );
1122 }
1123 else
1124 {
1125 $field1 = $multi_db ? "$new_db.$new_table.$f1" : "$new_table.$f1";
1126 }
1127 if( $self->_is_object( $f2 ) && $f2->isa( 'DB::Object::Fields::Field' ) )
1128 {
1129 $f2->prefixed( $multi_db ? 3 : 1 );
1130 $field2 = $f2->name;
1131 $fields_tables->{ $f2->table }++ if( !$fields_tables->{ $f2->table } );
1132 }
1133 else
1134 {
1135 $field2 = $multi_db ? "$new_db.$new_table.$f2" : "$new_table.$f2";
1136 }
1137 CORE::push( @res, $i_am_negative ? "$field1 != $field2" : "$field1 = $field2" );
1138 }
1139 }
1140 return({
1141 clause => CORE::join( $op, @res ),
1142 fields_tables => $fields_tables,
1143 });
1144 };
1145  
1146 # $on is either a $dbh->AND, or $dbh->OR
1147 if( defined( $on ) )
1148 {
1149 if( $self->_is_object( $on ) && $on->isa( 'DB::Object::Operator' ) )
1150 {
1151 my $op = $on->operator;
1152 my( @vals ) = $on->value;
1153 my $ret = $format_condition->( \@vals, $op );
1154 my $as = $q_target->table_alias ? sprintf( ' AS %s', $q_target->table_alias ) : '';
1155 $left_join = "LEFT JOIN ${new_table}${as} ON $ret->{clause}";
1156 }
1157 elsif( $self->_is_object( $on ) && $on->isa( 'DB::Object::Fields::Overloaded' ) )
1158 {
1159 my $as = $q_target->table_alias ? sprintf( ' AS %s', $q_target->table_alias ) : '';
1160 $left_join = "LEFT JOIN ${new_table}${as} ON ${on}";
1161 }
1162 elsif( $self->_is_array( $on ) )
1163 {
1164 my $ret = $format_condition->( $on, 'AND' );
1165 my $as = $q_target->table_alias ? sprintf( ' AS %s', $q_target->table_alias ) : '';
1166 $left_join = "LEFT JOIN ${new_table}${as} ON $ret->{clause}";
1167 }
1168 # There is a second parameter - if so this is the condition of the 'LEFT JOIN'
1169 elsif( $self->_is_hash( $on => 'strict' ) )
1170 {
1171 # Previous join
1172 my $join_ref = $q_source->left_join;
1173 my $def = { on => $on, table_object => $q_target->table_object, query_object => $q_target };
1174 ## Add the current one
1175 if( $multi_db )
1176 {
1177 $join_ref->{ "$new_db.$new_table" } = $def;
1178 }
1179 else
1180 {
1181 $join_ref->{ $new_table } = $def;
1182 }
1183 # (Re)build the LEFT JOIN ... ON ... definition
1184 my @join_data = ();
1185 foreach my $joined ( keys( %$join_ref ) )
1186 {
1187 my $condition = $join_ref->{ $joined }->{on};
1188 my $to = $join_ref->{ $joined }->{table_object};
1189 my $qo = $join_ref->{ $joined }->{query_object};
1190 my $join_table_name = $to->prefix;
1191 my $join_table_alias = '';
1192 if( length( $join_table_alias = $qo->table_alias ) )
1193 {
1194 $join_table_alias = " AS $join_table_alias";
1195 }
1196 push( @join_data, "LEFT JOIN ${join_table_name}${join_table_alias} ON " . CORE::join( ' AND ', map{ "$_=$condition->{ $_ }" } keys( %$condition ) ) );
1197 }
1198 $left_join = CORE::join( ' ', @join_data );
1199 }
1200 else
1201 {
1202 warn( "Warning: I have no clue what to do with '$on' (", overload::StrVal( $on ), ") in this join for table \"", $q->table_object->name, "\"" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
1203 }
1204 }
1205 # Otherwise, this is a straight JOIN
1206 else
1207 {
1208 # $q_source->from_table->push( $multi_db ? "$new_db.$new_table" : $new_table );
1209 $q_source->from_table->push(
1210 $q_target->table_alias
1211 ? sprintf( '%s AS %s', $q_target->table_object->name, $q_target->table_alias )
1212 : ( $q_target->table_object->prefixed ? $q_target->table_object->prefix : $q_target->table_object->name )
1213 );
1214 }
1215 my $from = $q_source->from_table->join( ', ' );
1216 my $clause = $q_source->_query_components( 'select', { no_bind_copy => 1 } );
1217 # Copy WHERE (and other clause) elements directly into $q_source->elements so that
1218 # Statement::execute() can find the bind types regardless of the use_bind setting.
1219 # We do this explicitly rather than via _save_bind() because _save_bind() is gated
1220 # on use_bind, which may be 0 even when placeholders are present.
1221 # NOTE: $where->elements returns a Module::Generic::Array of Element objects directly
1222 # (NOT an Elements wrapper). Pass ->list to Elements::push(), not the array object itself.
1223 {
1224 my $elems = $q_source->new_elements;
1225 my $where = $q_source->where;
1226 my $limit = $q_source->limit;
1227 if( $where )
1228 {
1229 my $where_arr = $where->elements;
1230 $elems->push( $where_arr->list ) if( $where_arr && $where_arr->length );
1231 }
1232 if( $limit )
1233 {
1234 my $limit_arr = $limit->elements;
1235 $elems->push( $limit_arr->list ) if( $limit_arr && $limit_arr->length );
1236 }
1237 $q_source->elements( $elems );
1238  
1239 }
1240 my @query = ( "SELECT ${fields} FROM ${from} ${left_join}" );
1241 push( @query, @$clause ) if( @$clause );
1242 my $statement = CORE::join( ' ', @query );
1243 $q_source->query( $statement );
1244 my $sth = $tbl_o->_cache_this( $q_source ) ||
1245 return( $self->error( "Error while preparing query to select:\n", $q_source->as_string(), $tbl_o->error ) );
1246 # Routines such as as_string() expect an array on pupose so we do not have to commit the action
1247 # but rather get the statement string. At the end, we write:
1248 # $obj->select() to really select
1249 # $obj->select->as_string() to ONLY get the formatted statement
1250 # wantarray() returns the undefined value in void context, which is typical use of a real select command
1251 # i.e. $obj->select();
1252 if( !defined( wantarray() ) )
1253 {
1254 $sth->execute() ||
1255 return( $self->error( "Error while executing query to select:\n", $q_source->as_string(), "\nError: ", $sth->error() ) );
1256 }
1257 return( $sth );
1258 }
1259  
1260 # NOTE: number_of_fields -> NUM_OF_FIELDS
1261 # <https://metacpan.org/pod/DBI#NUM_OF_FIELDS>
1262 sub number_of_fields { return( shift->_get_statement_attribute( 'NUM_OF_FIELDS' ) ); }
1263  
1264 # NOTE: number_of_params -> NUM_OF_PARAMS
1265 # <https://metacpan.org/pod/DBI#NUM_OF_PARAMS>
1266 sub number_of_params { return( shift->_get_statement_attribute( 'NUM_OF_PARAMS' ) ); }
1267  
1268 sub object
1269 {
1270 my $self = shift( @_ );
1271 # This is intended for statement to fetched their object:
1272 # my $obj = $table->select( '*' )->object();
1273 # my $obj = $table->select( '*' )
1274 # would merly execute the statement before returning its object, but there are conditions
1275 # such like using a SELECT to create a table where we do not want the statement to be executed already
1276 return( $self->{sth} ) if( $self->{sth} );
1277 # More sensible approach will return a special Module::Generic::Null object to avoid perl complaining of 'called on undef value' if this is used in chaining
1278 return( Module::Generic::Null->new ) if( want( 'OBJECT' ) );
1279 return;
1280 }
1281  
1282 sub priority
1283 {
1284 my $self = shift( @_ );
1285 my $prio = shift( @_ );
1286 my $map =
1287 {
1288 0 => 'LOW_PRIORITY',
1289 1 => 'HIGH_PRIORITY',
1290 };
1291 ## Bad argument. Do not bother
1292 return( $self ) if( !exists( $map->{ $prio } ) );
1293  
1294 my $query = $self->{query} ||
1295 return( $self->error( "No query to set priority for was provided." ) );
1296 my $type = uc( ( $query =~ /^\s*(\S+)\s+/ )[ 0 ] );
1297 my @allowed = qw( DELETE INSERT REPLACE SELECT UPDATE );
1298 my $allowed = CORE::join( '|', @allowed );
1299 # Ignore if not allowed
1300 if( !scalar( grep{ /^$type$/i } @allowed ) )
1301 {
1302 $self->error( "You may not set priority on statement of type \U$type\E:\n$query" );
1303 return( $self );
1304 }
1305 # Incompatible. Do not bother going further
1306 return( $self ) if( $query =~ /^\s*(?:$allowed)\s+(?:DELAYED|LOW_PRIORITY|HIGH_PRIORITY)\s+/i );
1307 # SELECT with something else than HIGH_PRIORITY is incompatible, so do not bother to go further
1308 return( $self ) if( $prio != 1 && $type =~ /^(?:SELECT)$/i );
1309 return( $self ) if( $prio != 0 && $type =~ /^(?:DELETE|INSERT|REPLACE|UPDATE)$/i );
1310  
1311 $query =~ s/^(\s*)($allowed)(\s+)/$1$2 $map->{ $prio } /i;
1312 # $self->{ 'query' } = $query;
1313 # my $sth = $self->prepare( $query ) ||
1314 my $sth = $self->_cache_this( $query ) ||
1315 return( $self->error( "Error while preparing new low priority query:\n$query" ) );
1316 if( !defined( wantarray() ) )
1317 {
1318 $sth->execute() ||
1319 return( $self->error( "Error while executing new low priority query:\n$query" ) );
1320 }
1321 return( $sth );
1322 }
1323  
1324 sub promise
1325 {
1326 my $self = shift( @_ );
1327 $self->_load_class( 'Promise::Me' ) || return( $self->pass_error );
1328 return( Promise::Me->new(sub
1329 {
1330 return( $self->execute( @_ ) );
1331 }) );
1332 }
1333  
1334 sub query { return( shift->_set_get_scalar( 'query', @_ ) ); }
1335  
1336 sub query_object { return( shift->_set_get_object_without_init( 'query_object', 'DB::Object::Query', @_ ) ); }
1337  
1338 sub query_time { return( shift->_set_get_datetime( 'query_time', @_ ) ); }
1339  
1340 sub rollback
1341 {
1342 my $self = shift( @_ );
1343 if( $self->{sth} && $self->param( 'autocommit' ) )
1344 {
1345 my $sth = $self->prepare( "ROLLBACK" ) || return( $self->error( "An error occurred while preparing query to rollback: ", $self->error ) );
1346 $sth->execute() || return( $self->error( "Error occurred while executing query to rollback: ", $sth->error ) );
1347 $sth->finish();
1348 }
1349 return( $self );
1350 }
1351  
1352 sub rows(@)
1353 {
1354 my $self = shift( @_ );
1355 if( !$self->executed() )
1356 {
1357 $self->execute() || return( $self->pass_error );
1358 }
1359 # $self->_cleanup();
1360 # $rv = $sth->rows;
1361 if( !ref( $self ) )
1362 {
1363 return( $DBI::rows );
1364 }
1365 else
1366 {
1367 return( $self->{sth}->rows() );
1368 }
1369 }
1370  
1371 # NOTE: statement -> Statement
1372 # <https://metacpan.org/pod/DBI#Statement>
1373 sub statement { return( shift->_get_statement_attribute( 'Statement' ) ); }
1374  
1375 # A DBI::sth object. This should rather be a _set_get_object helper method, but I am not 100% sure if this is really a DBI::sth
1376 sub sth { return( shift->_set_get_scalar( 'sth', @_ ) ); }
1377  
1378 sub table { return( shift->{table} ); }
1379  
1380 sub table_object { return( shift->_set_get_object_without_init( 'table_object', 'DB::Object::Tables', @_ ) ); }
1381  
1382 sub undo
1383 {
1384 goto( &rollback );
1385 }
1386  
1387 sub wait { return( shift->error( "Method wait() is not implemented by this driver." ) ); }
1388  
1389 # Used to get the cached field names by _convert_datetime2object
1390 sub _cache_field_names
1391 {
1392 my $self = shift( @_ );
1393 my $names;
1394 if( !( $names = $self->{_cache_field_names} ) )
1395 {
1396 $names = $self->{_cache_field_names} = $self->field_names;
1397 }
1398 return( $names );
1399 }
1400  
1401 # Used to get the cached field names by _convert_datetime2object
1402 sub _cache_field_types
1403 {
1404 my $self = shift( @_ );
1405 my $types;
1406 if( !( $types = $self->{_cache_field_types} ) )
1407 {
1408 $types = $self->{_cache_field_types} = $self->field_types;
1409 }
1410 return( $types );
1411 }
1412  
1413 # sub _convert_datetime2object { return( shift->database_object->_convert_datetime2object( @_ ) ); }
1414 # sub _convert_datetime2object
1415 # {
1416 # my $self = shift( @_ );
1417 # my $opts = $self->_get_args_as_hash( @_ );
1418 # return( $opts->{data} );
1419 # }
1420 sub _convert_datetime2object
1421 {
1422 my $self = shift( @_ );
1423 my $opts = $self->_get_args_as_hash( @_ );
1424 my $sth = $opts->{statement} || return( $self->error( "No statement handler was provided to convert data from json to perl." ) );
1425 # my $data = $opts->{data} || return( $self->error( "No data was provided to convert from json to perl." ) );
1426 return( $opts->{data} ) if( !defined( $opts->{data} ) || !CORE::length( $opts->{data} ) );
1427 my $data = $opts->{data};
1428 # my $names = $sth->FETCH('NAME');
1429 # my $types = $sth->FETCH('pg_type');
1430 # Get the cached field names and types that we stored after executing the query, but before we finished reading the statement
1431 my $names = $self->_cache_field_names;
1432 my $types = $self->_cache_field_types;
1433 my $mode = ref( $data );
1434  
1435 for( my $i = 0; $i < scalar( @$names ); $i++ )
1436 {
1437 if( $types->[$i] eq DBI::SQL_DATE ||
1438 $types->[$i] eq DBI::SQL_TIMESTAMP ||
1439 $types->[$i] eq 'date' ||
1440 $types->[$i] eq 'timestamp' )
1441 {
1442 if( $mode eq 'ARRAY' )
1443 {
1444 for( my $j = 0; $j < scalar( @$data ); $j++ )
1445 {
1446 next if( !$data->[ $j ]->{ $names->[ $i ] } );
1447 my $dt = $self->_convert_string2datetime( $data->[ $j ]->{ $names->[ $i ] } );
1448 if( !defined( $dt ) )
1449 {
1450 warn( $self->error ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
1451 }
1452 $data->[ $j ]->{ $names->[ $i ] } = $dt;
1453 }
1454 }
1455 elsif( $mode eq 'HASH' )
1456 {
1457 next if( !$data->{ $names->[ $i ] } );
1458 my $dt = $self->_convert_string2datetime( $data->{ $names->[ $i ] } );
1459 if( !defined( $dt ) )
1460 {
1461 warn( $self->error ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
1462 }
1463 $data->{ $names->[ $i ] } = $dt;
1464 }
1465 }
1466 }
1467 return( $data );
1468 }
1469  
1470 # sub _convert_json2hash { return( shift->database_object->_convert_json2hash( @_ ) ); }
1471 # Does nothing by default
1472 # Must be superseded by the subclasses because we use the data types like PG_JSON, PG_JSONB
1473 # and we don't have them at this top level
1474 sub _convert_json2hash
1475 {
1476 my $self = shift( @_ );
1477 my $opts = $self->_get_args_as_hash( @_ );
1478 return( $opts->{data} );
1479 }
1480  
1481 sub _convert_string2datetime
1482 {
1483 my $self = shift( @_ );
1484 my $str = shift( @_ ) || return;
1485 my $dt = $self->_parse_timestamp( $str );
1486 if( !defined( $dt ) )
1487 {
1488 return( $self->pass_error );
1489 }
1490 # An empty string means it did not fail, but probably did not recognise the format
1491 elsif( !$dt )
1492 {
1493 return( $str );
1494 }
1495 return( $dt );
1496 }
1497  
1498 sub _get_statement_attribute
1499 {
1500 my $self = shift( @_ );
1501 my $attr = shift( @_ );
1502 if( !length( $attr // '' ) )
1503 {
1504 return( $self->error( "No statement attribute was provided to retrieve its value." ) );
1505 }
1506 my $sth = $self->{sth} || die( "Unable to get the underlying statement handler!" );
1507 my $val;
1508 # try-catch
1509 local $@;
1510 eval
1511 {
1512 # Ensure we stringify
1513 $val = $sth->{ "$attr" };
1514 };
1515 if( $@ )
1516 {
1517 return( $self->error( "Error retrieving value for '${attr}': $@" ) );
1518 }
1519 return( $val );
1520 }
1521  
1522 # NOTE: DESTROY
1523 DESTROY
1524 {
1525 # Do nothing but existing so it is handled by this package
1526 # print( STDERR "DESTROY'ing statement $self ($self->{ 'query' })\n" );
1527 };
1528  
1529 # NOTE: Storable hooks
1530 # We intentionally do NOT freeze DBI handles (dbh/sth) or back-references (dbo/table_object)
1531 # because they are process-local and cannot be safely restored.
1532 # NOTE: For CBOR and Sereal
1533 sub FREEZE
1534 {
1535 my $self = CORE::shift( @_ );
1536 my $serialiser = CORE::shift( @_ ) // '';
1537 my $class = CORE::ref( $self );
1538  
1539 # We keep a strict allow-list to avoid accidentally freezing DBI handles or other
1540 # process-local state.
1541 # 2026-01-29: I removed 'query_object' in an effort to reduce memory consumption. Let's see...
1542 my @props = qw(
1543 as_string bind cache params query query_object selected_fields
1544 table tie tie_order _fields _cache_field_names _cache_field_types
1545 );
1546  
1547 my $hash = {};
1548 foreach my $prop ( @props )
1549 {
1550 if( CORE::exists( $self->{ $prop } ) &&
1551 defined( $self->{ $prop } ) &&
1552 CORE::ref( $self->{ $prop } ) ne 'CODE' )
1553 {
1554 $hash->{ $prop } = $self->{ $prop };
1555 }
1556 }
1557 $hash->{_serial_version} = $DB::Object::SERIALISATION_VERSION;
1558  
1559 # Return an array reference rather than a list so this works with Sereal and CBOR.
1560 # Before Sereal version 4.023, Sereal did not support multiple values returned.
1561 if( $serialiser eq 'Sereal' )
1562 {
1563 require Sereal::Encoder;
1564 require version;
1565  
1566 if( version->parse( Sereal::Encoder->VERSION ) < version->parse( '4.023' ) )
1567 {
1568 CORE::return( [$class, $hash] );
1569 }
1570 }
1571  
1572 # But Storable wants a list with the first element being the serialised element
1573 CORE::return( $class, $hash );
1574 }
1575  
1576 sub STORABLE_freeze { return( shift->FREEZE( @_ ) ); }
1577  
1578 sub STORABLE_thaw { return( shift->THAW( @_ ) ); }
1579  
1580 sub STORABLE_thaw_post_processing
1581 {
1582 my $obj = shift( @_ );
1583 my @keys = %$obj;
1584 my $class = ref( $obj );
1585 my $hash = {};
1586 @$hash{ @keys } = @$obj{ @keys };
1587 my $self = bless( $hash => $class );
1588 return( $self );
1589 }
1590  
1591 sub THAW
1592 {
1593 # STORABLE_thaw would issue $cloning as the 2nd argument, while CBOR would issue
1594 # 'CBOR' as the second value.
1595 my( $self, undef, @args ) = @_;
1596 my $ref = ( CORE::scalar( @args ) == 1 && CORE::ref( $args[0] ) eq 'ARRAY' ) ? CORE::shift( @args ) : \@args;
1597 my $class = ( CORE::defined( $ref ) && CORE::ref( $ref ) eq 'ARRAY' && CORE::scalar( @$ref ) > 1 ) ? CORE::shift( @$ref ) : ( CORE::ref( $self ) || $self );
1598 my $hash = CORE::ref( $ref ) eq 'ARRAY' ? CORE::shift( @$ref ) : {};
1599  
1600 my $sv = CORE::delete( $hash->{_serial_version} ) // 0;
1601 if( $sv != $DB::Object::SERIALISATION_VERSION )
1602 {
1603 require( $EXCEPTION_CLASS );
1604 die( $EXCEPTION_CLASS->new({
1605 code => 409, # Conflict
1606 message => sprintf(
1607 "Serialisation version mismatch in %s: expected %d, got %d. Please purge the cache.",
1608 $class,
1609 $DB::Object::SERIALISATION_VERSION,
1610 $sv,
1611 )
1612 }) );
1613 }
1614  
1615 # Since this class is inherited, we also need to load from which we depend, if necessary.
1616 if( $class ne 'DB::Object::Statement' )
1617 {
1618 require DB::Object;
1619 require DB::Object::Statement;
1620 my @supported_classes = CORE::values( %$DB::Object::DRIVER2PACK );
1621 push( @supported_classes, 'DB::Object' );
1622 my $ok_classes = CORE::join( '|', CORE::map{ CORE::quotemeta( $_ ) } @supported_classes );
1623 my $base_class = ( $class =~ /^($ok_classes)/ )[0];
1624 eval( "require $base_class;" );
1625 if( $@ )
1626 {
1627 require( $EXCEPTION_CLASS );
1628 die( $EXCEPTION_CLASS->new( "Failure to load $base_class: $@" ) );
1629 }
1630  
1631 # If inheritance is still missing (or incomplete) for any reason, repair it explicitly.
1632 no strict 'refs';
1633  
1634 my $stash = \%{"${class}\::"};
1635 my $isa_ref;
1636 # We check if the 'ISA' symbol exists in the stash and its ARRAY slot is defined
1637 if( exists( $stash->{ISA} ) &&
1638 defined( *{"${class}\::ISA"}{ARRAY} ) )
1639 {
1640 $isa_ref = *{"${class}\::ISA"}{ARRAY};
1641 }
1642 else
1643 {
1644 # # Force creation of @ISA array slot
1645 # @{"${class}::ISA"} = ();
1646 # $isa_ref = *{"${class}::ISA"}{ARRAY};
1647 # But I want it to die, so this can be dealt with, and not swept under the rug.
1648 die( "Unable to find the \@ISA value in $class. The package contains the following stashes:\n", $self->Module::Generic::dump( $stash ) );
1649 }
1650  
1651 my $has_stmt = 0;
1652 foreach my $p ( @$isa_ref )
1653 {
1654 # Same as what we can find in modules DB::Object::(Postgres|SQLite|Mysql)::Statement
1655 $has_stmt = 1 if( CORE::defined( $p ) && $p eq 'DB::Object::Statement' );
1656 }
1657  
1658 if( !$has_stmt )
1659 {
1660 @$isa_ref = ( 'DB::Object::Statement' );
1661 }
1662 }
1663 my $new;
1664 # Storable pattern requires to modify the object it created rather than returning a new one
1665 if( CORE::ref( $self ) )
1666 {
1667 foreach( CORE::keys( %$hash ) )
1668 {
1669 $self->{ $_ } = CORE::delete( $hash->{ $_ } );
1670 }
1671 $new = $self;
1672 }
1673 else
1674 {
1675 $new = CORE::bless( $hash => $class );
1676 }
1677 CORE::return( $new );
1678 }
1679  
1680 1;
1681 # NOTE: POD
1682 __END__