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

filter: Statementstmt 0.0% 0 / 1194 Branchbran 0.0% 0 / 720 Conditioncond 0.0% 0 / 522 MC/DCmcdc 0.0% 0 / 299 Subroutinesub 0.0% 0 / 96 Podpod 0.0% 0 / 81 totaltotal 0.0% 0 / 2912 CC 361 SCAR 68.4
CC
361
Cov
0%
_where_having
4032.0
getdefault
1332.0
select
930.0
CRAP 933.6
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Query.pm
4 ## Version v0.10.2
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/09/15
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::Query;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'DB::Object' );
20 use parent qw( DB::Object );
21 use vars qw( $VERSION $DEBUG $EXCEPTION_CLASS );
22 use DB::Object::Query::Clause;
23 use DB::Object::Query::Elements;
24 use DB::Object::Query::Element;
25 use Scalar::Util qw( weaken );
26 use Wanted;
27 our $DEBUG = 0;
28 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
29 our $VERSION = 'v0.10.2';
30 };
31  
32 use strict;
33 use warnings;
34  
35 sub init
36 {
37 my $self = shift( @_ );
38 $self->{alias} = {} unless( CORE::exists( $self->{alias} ) );
39 $self->{avoid} = [] unless( CORE::exists( $self->{avoid} ) );
40 $self->{binded} = [] unless( CORE::exists( $self->{binded} ) );
41 # $self->{binded_group} = [] unless( CORE::exists( $self->{binded_group} ) );
42 # $self->{binded_limit} = [] unless( CORE::exists( $self->{binded_limit} ) );
43 # $self->{binded_order} = [] unless( CORE::exists( $self->{binded_order} ) );
44 $self->{binded_types} = [] unless( CORE::exists( $self->{binded_types} ) );
45 $self->{binded_values} = [] unless( CORE::exists( $self->{binded_values} ) );
46 $self->{binded_where} = [] unless( CORE::exists( $self->{binded_where} ) );
47 $self->{dirty} = 0;
48 $self->{elements} = undef unless( CORE::exists( $self->{elements} ) );
49 $self->{enhance} = 0 unless( CORE::exists( $self->{enhance} ) );
50 $self->{from_table} = [] unless( CORE::exists( $self->{from_table} ) );
51 $self->{from_unixtime} = [] unless( CORE::exists( $self->{from_unixtime} ) );
52 $self->{group_by} = '' unless( CORE::exists( $self->{group_by} ) );
53 $self->{having} = '' unless( CORE::exists( $self->{having} ) );
54 $self->{join_fields} = '' unless( CORE::exists( $self->{join_fields} ) );
55 $self->{left_join} = {} unless( CORE::exists( $self->{left_join} ) );
56 $self->{limit} = '' unless( CORE::exists( $self->{limit} ) );
57 $self->{local} = {} unless( CORE::exists( $self->{local} ) );
58 $self->{order_by} = '' unless( CORE::exists( $self->{order_by} ) );
59 $self->{prepare_options}= {} unless( CORE::exists( $self->{prepare_options} ) );
60 $self->{query_values} = undef unless( CORE::exists( $self->{query_values} ) );
61 $self->{reverse} = '' unless( CORE::exists( $self->{reverse} ) );
62 $self->{sorted} = [] unless( CORE::exists( $self->{sorted} ) );
63 $self->{table_alias} = '' unless( CORE::exists( $self->{table_alias} ) );
64 $self->{table_object} = '' unless( CORE::exists( $self->{table_object} ) );
65 $self->{unix_timestamp} = [] unless( CORE::exists( $self->{unix_timestamp} ) );
66 $self->{where} = '' unless( CORE::exists( $self->{where} ) );
67 $self->{_init_strict_use_sub} = 1;
68 $self->{_exception_class} = $EXCEPTION_CLASS;
69 $self->SUPER::init( @_ ) || return( $self->pass_error );
70 $self->{constant} = {};
71 $self->{query} = '';
72 $self->{query_reset} = 0;
73 $self->{query_reset_core_keys} = [qw(
74 alias binded binded_group binded_limit binded_order binded_types binded_values
75 binded_where dirty from_unixtime group_by having is_upsert limit local order_by reverse
76 sorted table_alias unix_timestamp where
77 from_table join_fields join_tables left_join prepare_options query_values constant
78 query selected_fields tie_order
79 )];
80 $self->{selected_fields} = '';
81 $self->{table_object} = '';
82 $self->{tie_order} = [];
83 unless( $self->{elements} )
84 {
85 $self->{elements} = $self->new_elements;
86 }
87 return( $self );
88 }
89  
90 sub alias { return( shift->_set_get_hash( 'alias', @_ ) ); }
91  
92 sub as_string { return( shift->{query} ); }
93  
94 sub attach
95 {
96 my $self = shift( @_ );
97 my $this = shift( @_ );
98 if( $self->_is_a( $this => 'DB::Object' ) )
99 {
100 my $base_class = $self->base_class;
101 unless( $self->_is_a( $this => $base_class ) )
102 {
103 return( $self->error( "Value provided is not a ${base_class} object." ) );
104 }
105 $self->database_object( $this ) || return( $self->pass_error );
106 }
107 elsif( $self->_is_a( $this => 'DB::Object::Tables' ) )
108 {
109 my $base_class = $self->base_class;
110 unless( $self->_is_a( $this => "${base_class}::Tables" ) )
111 {
112 return( $self->error( "Value provided is not a ${base_class}::Tables object." ) );
113 }
114 $self->table_object( $this ) || return( $self->pass_error );
115 }
116 else
117 {
118 return( $self->error( "No DB::Object or DB::Object::Tables object was provided." ) );
119 }
120 $self->debug( $this->debug );
121 if( my $elems = $self->elements )
122 {
123 $elems->attach( $self );
124 }
125 return( $self );
126 }
127  
128 sub avoid { return( shift->_set_get_array_as_object( 'avoid', @_ ) ); }
129  
130 sub binded { return( shift->_set_get_array_as_object( 'binded', @_ ) ); }
131  
132 sub binded_group { return( shift->group->values ); }
133  
134 sub binded_limit { return( shift->limit->values ); }
135  
136 sub binded_order { return( shift->order->values ); }
137  
138 # NOTE: sub binded_types is not used anymore as of 2023-07-19 (v0.11.7)
139 sub binded_types { return( shift->_set_get_array_as_object( 'binded_types', @_ ) ); }
140 # sub binded_types
141 # {
142 # my $self = shift( @_ );
143 # my $arr = $self->new_array;
144 # my $e = $self->elements;
145 # $e->keys->sort->foreach(sub
146 # {
147 # my $k = shift( @_ );
148 # $arr->push( $e->{ $k }->type );
149 # });
150 # return( $arr );
151 # }
152  
153 # sub binded_types_as_param
154 # {
155 # my $self = shift( @_ );
156 # return( $self->error( "The driver has not implemented the method binded_types_as_param." ) );
157 # }
158 sub binded_types_as_param
159 {
160 my $self = shift( @_ );
161 my $params = $self->new_array;
162 $self->elements->foreach(sub
163 {
164 my $elem = shift( @_ );
165 my $type;
166 if( $elem && $elem->as_is )
167 {
168 return;
169 }
170 elsif( $elem && defined( $type = $elem->type ) )
171 {
172 $params->push( $type );
173 }
174 else
175 {
176 $params->push( '' );
177 }
178 });
179 return( $params );
180 }
181  
182 sub binded_values { return( shift->_set_get_array_as_object( 'binded_values', @_ ) ); }
183  
184 sub binded_where { return( shift->_set_get_array_as_object( 'binded_where', @_ ) ); }
185  
186 sub constant
187 {
188 my $self = shift( @_ );
189 if( @_ )
190 {
191 my $def = shift( @_ );
192 return( $self->error( "I was expecting a hash reference, but got '$def' instead." ) ) if( !$self->_is_hash( $def => 'strict' ) );
193 foreach my $k (qw( pack file line ))
194 {
195 return( $self->error( "Parameter \"$k\" is missing in hash refernece provided." ) ) if( !$def->{ $k } );
196 }
197 ## sth may or may not be there
198 return( $self->error( "Statement handler provided is not a DB::Object::Statement object." ) ) if( $def->{sth} && ( !$self->_is_object( $def->{sth} ) && !$def->{sth}->isa( 'DB::Object::Statement' ) ) );
199 $self->{constant} = $def;
200 }
201 return( $self->{constant} );
202 }
203  
204 # sub database_object { return( shift->table_object->database_object ) }
205 # NOTE: we cannot simply use the database object of the table, even if it would make sense, because a query object can be instantiated by a database object (see DB::Object->_query_object_create), and when that happens, this method would set the database object of our query object.
206 sub database_object { return( shift->_set_get_object_without_init( 'database_object', 'DB::Object', @_ ) ); }
207  
208 sub delete
209 {
210 my $self = shift( @_ );
211 my $constant = $self->constant;
212 if( scalar( keys( %$constant ) ) )
213 {
214 return( $constant->{sth} ) if( $constant->{sth} && $self->_is_object( $constant->{sth} ) && $constant->{sth}->isa( 'DB::Object::Statement' ) );
215 }
216 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
217 my $table = $tbl_o->name ||
218 return( $self->error( "No table to delete entries from was set." ) );
219 my $where = '';
220 $self->where( @_ ) if( @_ );
221 # if( !$where && $self->{ 'query_reset' } )
222 if( !$where )
223 {
224 $where = $self->where();
225 }
226 if( !$where )
227 {
228 return( $self->error( "You have provided no where clause. If you intend to delete all records from table '$table', you must do explicitly by preparing the statement yourself." ) );
229 }
230 my $clauses = $self->_query_components( 'delete' );
231 my @query = ( "DELETE FROM $table" );
232 # 'query_reset' condition to avoid catching parameters from pervious queries.
233 push( @query, @$clauses ) if( scalar( @$clauses ) );
234 my $query = $self->{query} = CORE::join( ' ', @query );
235 return( $self->error( "Refusing to do a bulk delete. Enable the allow_bulk_delete database object property if you want to do so. Original query was: $query" ) ) if( !$self->where && !$self->database_object->allow_bulk_delete );
236 $self->_save_bind();
237 my $sth = $tbl_o->_cache_this( $self ) ||
238 return( $self->error( "Error while preparing query to delete from table '$table':\n$query" ) );
239 # Routines such as as_string() expect an array on pupose so we do not have to commit the action
240 # but rather get the statement string. At the end, we write:
241 # $obj->delete() to really delete
242 # $obj->delete->as_string() to ONLY get the formatted statement
243 # wantarray returns undef in void context, i.e. $obj->delete()
244 if( !defined( wantarray() ) )
245 {
246 $sth->execute() ||
247 return( $self->error( "Error while executing query to delete from table '$table':\n$query" ) );
248 # Will be destroyed anyway and permits the end user to manipulate the object if needed
249 # $sth->finish();
250 }
251 # wantarray returns false but not undef() otherwise, i.e.
252 # $obj->delete->as_string();
253 return( $sth );
254 }
255  
256 sub dirty { return( shift->_set_get_boolean( 'dirty', @_ ) ); }
257  
258 # sub elements { return( shift->_set_get_hash_as_mix_object( 'elements', @_ ) ); }
259 sub elements { return( shift->_set_get_object_without_init( 'elements', 'DB::Object::Query::Elements', @_ ) ); }
260  
261 sub enhance { return( shift->_set_get_boolean( 'enhance', @_ ) ); }
262  
263 sub error
264 {
265 my $self = shift( @_ );
266 # Query object is now in an error state and must not be re-used.
267 $self->{dirty} = 1 if( ref( $self ) );
268 return( $self->SUPER::error( @_ ) );
269 }
270  
271 # Used in conjonction with constant(), allows internally to know if the query has reached the end of the chain
272 # Such as $tbl->select->join( $tbl_object, $conditions )->join( $other_tbl_object, $other_conditions );
273 # final() enables to know the query reached the end, so that when constant is used, all the processing can be skipped
274 sub final { return( shift->_set_get_scalar( 'final', @_ ) ); }
275  
276 sub format_from_epoch
277 {
278 my $self = shift( @_ );
279 warn( "This method \"format_from_epoch\" was not superseded." ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
280 }
281  
282 sub format_to_epoch
283 {
284 my $self = shift( @_ );
285 warn( "This method \"format_to_epoch\" was not superseded." ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
286 }
287  
288 # NOTE: For select or insert queries
289 sub format_statement
290 {
291 my $self = shift( @_ );
292 my $opts = $self->_get_args_as_hash( @_ );
293 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
294 my $dbo = $tbl_o->database_object ||
295 return( $self->error( "No database object is currently set on this table object for table '", $tbl_o->name, "'" ) );
296 # Should we use bind statement?
297 my $bind = $dbo->use_bind;
298 $opts->{data} = $self->{_default} if( !$opts->{data} );
299 $opts->{order} = $self->{_fields} if( !$opts->{order} );
300 $opts->{table} = $tbl_o->qualified_name if( !$opts->{table} );
301 local $_;
302 my $data = $opts->{data};
303 my $order = $opts->{order};
304 my $table = $opts->{table};
305 my $prefix = $tbl_o->prefix;
306 my $from_unix = {};
307 my $unixtime = {};
308 my $args = $self->{_args};
309 my $fields = '';
310 my $values = '';
311 my $base_class = $self->base_class;
312 $from_unix = $self->{_from_unix};
313 my $tmp_ref = $self->from_unixtime();
314 map{ $from_unix->{ $_ }++ } @$tmp_ref;
315 $tmp_ref = $self->unix_timestamp();
316 map{ $unixtime->{ $_ }++ } @$tmp_ref;
317 my @format_fields = ();
318 my @format_values = ();
319 # my $binded = $self->{binded_values} = [];
320 my $multi_db = $tbl_o->prefix_database;
321 my $db = $tbl_o->database;
322 my $fields_ref = $tbl_o->fields_as_array;
323 my $ok_list = $fields_ref->join( '|' )->scalar;
324 my $tables = CORE::join( '|', @{$dbo->tables} );
325 my $struct = $tbl_o->structure || return( $self->pass_error( $tbl_o->error ) );
326 my $query_type = $self->{query_type};
327 my @sorted = ();
328 if( $self->query_type eq 'insert' &&
329 @$args &&
330 !( @$args % 2 ) )
331 {
332 for( my $i = 0; $i < @$args; $i += 2 )
333 {
334 push( @sorted, $args->[ $i ] ) if( exists( $order->{ $args->[ $i ] } ) );
335 $data->{ $args->[ $i ] } = $args->[ $i + 1 ] if( !exists( $data->{ $args->[ $i ] } ) );
336 }
337 }
338 @sorted = sort{ $order->{ $a }->pos <=> $order->{ $b }->pos } keys( %$order ) if( !@sorted );
339 # Used for insert or update so that execute can take a hash of key => value pair and we would bind the values in the right order
340 # But or that we need to know the order of the fields.
341 $self->{sorted} = \@sorted;
342 my $placeholder_re = $dbo->_placeholder_regexp;
343 my $elems = $self->new_elements;
344  
345 foreach( @sorted )
346 {
347 my $elem = $self->new_element;
348 if( exists( $data->{ $_ } ) )
349 {
350 my $value = $data->{ $_ };
351 if( $self->_is_a( $value => "${base_class}::Statement" ) )
352 {
353 $elem->value( '(' . $value->as_string . ')' );
354 $elem->elements( $value->query_object->elements );
355 }
356 # This is for insert or update statement types
357 elsif( exists( $from_unix->{ $_ } ) )
358 {
359 if( $bind )
360 {
361 $elem->value( $value );
362 $elem->format( $self->format_from_epoch({ value => $value, bind => 1 }) );
363 }
364 else
365 {
366 $elem->format( $self->format_from_epoch({ value => $value, bind => 0 }) );
367 }
368 }
369 elsif( exists( $unixtime->{ $_ } ) )
370 {
371 if( $bind )
372 {
373 $elem->value( $value );
374 $elem->format( $self->format_to_epoch({ value => $value, bind => 1 }) );
375 }
376 else
377 {
378 $elem->format( $self->format_to_epoch({ value => $value, bind => 0 }) );
379 }
380 }
381 # A scalar reference implies this is used as-is
382 elsif( ref( $value ) eq 'SCALAR' )
383 {
384 $elem->format( $$value );
385 $elem->as_is(1);
386 }
387 # The placeholder may be embedded inside a function like `UPPER(?)'
388 elsif( $value =~ /($placeholder_re)/ )
389 {
390 $elem->placeholder( $1 );
391 $elem->format( $value );
392 }
393 elsif( $struct->{ $_ } =~ /^\s*\bBLOB\b/i )
394 {
395 $elem->placeholder( '?' );
396 $elem->format( '?' );
397 $elem->value( $value );
398 }
399 # If the value itself looks like a field name or like a SQL function
400 # or simply if bind option is inactive
401 # This stinks too much. It is way too complex to parse or guess a sql query
402 # use \( instead to pass a scalar reference
403 # elsif( $value =~ /(?:\.|\A)(?:$ok_list)\b/ ||
404 # $value =~ /[a-zA-Z_]{3,}\([^\)]*\)/ ||
405 # $value eq '?' )
406 # {
407 # push( @format_values, $value );
408 # }
409 elsif( !$bind )
410 {
411 $elem->format( sprintf( "%s", $dbo->quote( $value ) ) );
412 }
413 # We do this before testing for param binding because DBI puts quotes around SET number :-(
414 elsif( $value =~ /^\d+$/ && $struct->{ $_ } =~ /\bSET\(/i )
415 {
416 $elem->format( $value );
417 }
418 elsif( $value =~ /^\d+$/ &&
419 $struct->{ $_ } =~ /\bENUM\(/i &&
420 ( $query_type eq 'insert' || $query_type eq 'update' ) )
421 {
422 $elem->format( "'$value'" );
423 }
424 # Otherwise, bind option is enabled, we bind parameter
425 elsif( $bind )
426 {
427 $elem->placeholder( '?' );
428 $elem->format( '?' );
429 $elem->value( $value );
430 }
431 # In last resort, we handle the formatting ourself
432 else
433 {
434 $elem->format( $dbo->quote( $value ) );
435 }
436 }
437  
438 if( $prefix )
439 {
440 s{
441 (?<![\.\"])\b($ok_list)\b(\s*)?(?!\.)
442 }
443 {
444 my( $field, $spc ) = ( $1, $2 );
445 if( $` =~ /\s+(?:AS|FROM)\s+$/i )
446 {
447 "$field$spc";
448 }
449 elsif( $query_type eq 'select' && $prefix )
450 {
451 "$prefix.$field$spc";
452 }
453 else
454 {
455 "$field$spc";
456 }
457 }gex;
458 s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
459 }
460 $elem->field( $_ );
461 $elems->push( $elem );
462 }
463 if( !wantarray() && scalar( @{$self->{_extra}} ) )
464 {
465 foreach my $this ( @{$self->{_extra}} )
466 {
467 $elems->push({
468 field => $this,
469 debug => $self->debug,
470 });
471 }
472 }
473  
474 return( $elems );
475 }
476  
477 sub format_update
478 {
479 my $self = shift( @_ );
480 my $data = shift( @_ ) if( $self->_is_array( $_[0] ) || $self->_is_hash( $_[0] => 'strict' ) || @_ % 2 );
481 my @arg = @_;
482 if( !@arg && $data )
483 {
484 if( $self->_is_hash( $data => 'strict' ) )
485 {
486 @arg = %$data;
487 }
488 elsif( $self->_is_array( $data ) )
489 {
490 @arg = @$data;
491 }
492 }
493  
494 return( $self->error( "Must provide key => value pairs. I received an odd number of arguments" ) ) if( @arg && ( scalar( @arg ) % 2 ) );
495 my %arg = ( @arg );
496 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
497 my $dbo = $tbl_o->database_object ||
498 return( $self->error( "No database object is currently set on this table object for table '", $tbl_o->name, "'" ) );
499 $arg{default} ||= $self->{_default};
500 if( $arg{data} && !$data )
501 {
502 my $hash = $arg{data};
503 my @vals = %$hash;
504 $data = \@vals;
505 }
506 elsif( $self->_is_hash( $data => 'strict' ) )
507 {
508 my @vals = %$data;
509 $data = \@vals;
510 }
511 my $info = $data || \@arg;
512 if( !$info || !scalar( @$info ) )
513 {
514 return( $self->error( "No data to update was provided to format update." ) );
515 }
516 my $bind = $dbo->use_bind;
517 my $def = $arg{default} || $self->{_default};
518 my $fields_ref = $tbl_o->fields;
519 my $fields_list = CORE::join( '|', keys( %$fields_ref ) );
520 my $struct = $tbl_o->structure || return( $self->pass_error( $tbl_o->error ) );
521 my $types = $tbl_o->types;
522 my $from_unix = $self->from_unixtime();
523 my $from_unixtime = { map{ $_ => 1 } @$from_unix };
524 my @fields = ();
525 my @binded = ();
526 my @types = ();
527 # Get the constant has definition for each table fields
528 my $types_const = $tbl_o->types_const;
529 my $placeholder_re = $dbo->_placeholder_regexp;
530 # Before we used to call getdefault supplying it our new values and the
531 # format_statement() that would take the default supplied values.
532 # Now, this works differently since we use update() method and supply directly our
533 # value to update to it.
534 # In this context, getting the default values is dangerous, since resetting the values
535 # to their default ones is not was we want, is it?
536 my $elems = $self->new_elements;
537 while( @$info )
538 {
539 my( $field, $value ) = splice( @$info, 0, 2 );
540 # Do not update a field that does not belong in this table
541 next if( !exists( $fields_ref->{ $field } ) );
542 # DB::Object::Fields::Field object
543 my $fo = $fields_ref->{ $field };
544 my $elem = $self->new_element( field => $field );
545 # Make it a FROM_UNIXTIME field if this is what we need.
546 # $value = "FROM_UNIXTIME($value)" if( exists( $from_unixtime->{ $field } ) );
547 # $value = \"TO_TIMESTAMP($value)" if( exists( $from_unixtime->{ $field } ) );
548 # This is for insert or update statement types
549 if( exists( $from_unixtime->{ $field } ) )
550 {
551 if( $bind )
552 {
553 $elem->value( $value );
554 $elem->format( "$field=" . $self->format_from_epoch({ value => $value, bind => 1 }) );
555 }
556 else
557 {
558 $elem->format( "$field=" . $self->format_from_epoch({ value => $value, bind => 0 }) );
559 }
560 }
561 elsif( ref( $value ) eq 'SCALAR' )
562 {
563 $elem->format( "$field=$$value" );
564 $elem->as_is(1);
565 }
566 # Maybe $bind is not enabled, but the user may have manually provided a placeholder, i.e. '?'
567 elsif( !$bind )
568 {
569 my $const;
570 # The placeholder could be embedded inside a function like 'UPPER(?)'
571 if( $value =~ /($placeholder_re)/ )
572 {
573 $elem->placeholder( $1 );
574 $elem->format( "$field = $value" );
575 if( $const = $fo->datatype->constant )
576 {
577 $elem->type( $const );
578 }
579 }
580 elsif( $self->_is_hash( $value => 'strict' ) &&
581 ( $fo->type eq 'jsonb' || $fo->type eq 'json' ) )
582 {
583 my $this_json = $self->_encode_json( $value );
584 $const = $fo->datatype->constant;
585 $elem->format( sprintf( "$field=%s", $dbo->quote( $this_json, $const ) ) );
586 }
587 elsif( $dbo->placeholder->has( $self->_is_scalar( $value ) ? $value : \$value ) )
588 {
589 $dbo->placeholder->replace( $self->_is_scalar( $value ) ? $value : \$value );
590 $elem->placeholder( '?' );
591 $elem->format( "$field = ${value}" );
592 if( $const = $fo->datatype->constant )
593 {
594 $elem->type( $const );
595 }
596 }
597 elsif( $const = $fo->datatype->constant )
598 {
599 $elem->format( sprintf( "$field=%s", $dbo->quote( $value, $const ) ) );
600 }
601 else
602 {
603 $elem->format( sprintf( "$field=%s", $dbo->quote( $value ) ) );
604 }
605 }
606 # if this is a SET field type and value is a number, treat it as a number and not as a string
607 # We do this before testing for param binding because DBI puts quotes around SET number :-(
608 elsif( $value =~ /^\d+$/ && $struct->{ $field } =~ /\bSET\(/i )
609 {
610 $elem->format( "$field=$value" );
611 }
612 elsif( $bind )
613 {
614 $elem->placeholder( '?' );
615 $elem->format( "$field=?" );
616 $elem->value( $value );
617 my $const;
618 if( $const = $fo->datatype->constant )
619 {
620 $elem->type( $const );
621 }
622 }
623 else
624 {
625 my $const;
626 if( $const = $fo->datatype->constant )
627 {
628 $elem->format( "$field=" . $dbo->quote( $value, $const ) );
629 }
630 else
631 {
632 $elem->format( "$field=" . $dbo->quote( $value ) );
633 }
634 }
635 $elems->push( $elem );
636 }
637 return( $elems );
638 }
639  
640 sub from_table { return( shift->_set_get_array_as_object( 'from_table', @_ ) ); }
641  
642 sub from_unixtime { return( shift->_set_get_array_as_object( 'from_unixtime', @_ ) ); }
643  
644 sub getdefault
645 {
646 my $self = shift( @_ );
647 my $opts = $self->_get_args_as_hash( @_ );
648 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
649 my $table = $opts->{table} || $tbl_o->name;
650 my $prefix = $tbl_o->query_object->table_alias ? $tbl_o->query_object->table_alias : $tbl_o->prefix;
651 my $arg = [];
652 if( $opts->{arg} )
653 {
654 return( $self->error( "arg parameter provided, but is not an array reference." ) ) if( !$self->_is_array( $opts->{arg} ) );
655 $arg = $opts->{arg};
656 return( $self->error( "arg parameter provided is not a key => value pair. Its number of elements should be an even number." ) ) if( scalar( @$arg ) && ( @$arg % 2 ) );
657 }
658 my %arg = ();
659 my $default = {};
660 my $fields = [];
661 my $structure = {};
662 my $base_class = $self->base_class;
663 # Contains some extra parameters for SELECT queries only
664 # Right now a concatenation of 'last_name' and 'first_name' fields into field named 'name'
665 my @extra = ();
666 %arg = @$arg if( scalar( @$arg ) );
667 $opts->{table} = lc( $opts->{table} );
668 $opts->{time} = time() if( !defined( $opts->{time} ) );
669 my $time = '';
670 $time = $opts->{time} if( $opts->{time} =~ /^\d+$/ );
671 $time ||= $opts->{unixtime} || time();
672 my $query_type = $opts->{query_type};
673 if( !$query_type )
674 {
675 my( $pkg, $file, $line, $sub ) = caller(1);
676 $sub =~ s/(.*):://;
677 $query_type = $sub;
678 }
679 my $alias = '';
680 if( $query_type ne 'insert' && $query_type ne 'delete' && $query_type ne 'replace' )
681 {
682 $alias = $opts->{as};
683 $alias = $self->alias if( !$alias || !%$alias );
684 }
685 my $avoid = $opts->{avoid} || $self->avoid();
686 my $unix_time = $opts->{unix_timestamp} || $self->unix_timestamp;
687 my $from_unix = $opts->{from_unixtime} || $self->from_unixtime;
688  
689 my $enhance = $self->enhance;
690 # Need to do hard copy of hashes
691 $default = $tbl_o->default || return( $self->pass_error( $tbl_o->error ) );
692 $fields = $tbl_o->fields || return( $self->pass_error( $tbl_o->error ) );
693 $structure = $tbl_o->structure || return( $self->pass_error( $tbl_o->error ) );
694  
695 if( !scalar( keys( %$fields ) ) )
696 {
697 return( $self->error( "Missing fields (", scalar( keys( %$fields ) ), " found) for table \"$table\"." ) );
698 }
699  
700 if( $query_type eq 'select' && $enhance )
701 {
702 my @sorted = sort{ $fields->{ $a }->pos <=> $fields->{ $b }->pos } keys( %$fields );
703 foreach my $field ( @sorted )
704 {
705 if( $structure->{ $field } =~ /^\s*(?:DATE(?:TIME)?|TIMESTAMP)\s*/i )
706 {
707 my $f = $self->format_to_epoch({
708 value => ( $prefix ? "${prefix}.${field}" : $field ),
709 bind => 0,
710 quote => 0,
711 });
712 my $fo = $tbl_o->fo->new_field(
713 debug => $self->debug,
714 name => "$f AS ${field}_unixtime",
715 pos => ( scalar( keys( %$fields ) ) + 1 ),
716 query_object => $self,
717 table_object => $self->table_object,
718 type => 'integer',
719 ) || return( $self->pass_error( $tbl_o->fo->error ) );
720 # $fields->{ "$f AS ${field}_unixtime" } = scalar( keys( %$fields ) ) + 1;
721 $fields->{ "$f AS ${field}_unixtime" } = $fo;
722 }
723 }
724 }
725  
726 my %to_unixtime = ();
727 if( $self->_is_array( $unix_time ) )
728 {
729 %to_unixtime = map{ $_ => 1 } @$unix_time;
730 }
731 elsif( $self->_is_hash( $unix_time => 'strict' ) )
732 {
733 %to_unixtime = %$unix_time;
734 }
735  
736 if( %to_unixtime && scalar( keys( %to_unixtime ) ) )
737 {
738 foreach my $field ( keys( %to_unixtime ) )
739 {
740 if( exists( $fields->{ $field } ) )
741 {
742 my $func = $self->format_to_epoch({
743 value => ( $prefix ? "${prefix}.${field}" : $field ),
744 bind => 0,
745 quote => 0,
746 });
747 my $fo = $tbl_o->fo->new_field(
748 debug => $self->debug,
749 name => $func . ' AS ' . $field,
750 pos => $fields->{ $field }->pos,
751 query_object => $self,
752 table_object => $self->table_object,
753 type => 'integer',
754 ) || return( $self->pass_error( $tbl_o->fo->error ) );
755 $fields->{ $func . ' AS ' . $field } = $fo;
756 delete( $fields->{ $field } );
757 }
758 }
759 }
760  
761 my %avoid = ();
762 if( $self->_is_array( $avoid ) )
763 {
764 %avoid = map{ $_ => 1 } @$avoid;
765 }
766 elsif( $self->_is_hash( $avoid => 'strict' ) )
767 {
768 %avoid = %$avoid;
769 }
770  
771 if( %avoid && scalar( keys( %avoid ) ) )
772 {
773 foreach my $field ( keys( %avoid ) )
774 {
775 if( exists( $fields->{ $field } ) )
776 {
777 delete( $fields->{ $field } );
778 delete( $default->{ $field } );
779 }
780 }
781 }
782  
783 my %as = ();
784 if( $self->_is_hash( $alias => 'strict' ) )
785 {
786 %as = %$alias;
787 foreach my $field ( keys( %as ) )
788 {
789 my $f;
790 if( exists( $fields->{ $field } ) )
791 {
792 $f = $prefix
793 ? "${prefix}.${field}"
794 : $field;
795 # delete( $fields{ $field } );
796 }
797 else
798 {
799 $f = $field;
800 }
801 my $fo = $tbl_o->fo->new_field(
802 debug => $self->debug,
803 name => $f . ' AS "' . $as{ $field } . '"',
804 pos => ( scalar( keys( %$fields ) ) + 1 ),
805 query_object => $self,
806 table_object => $self->table_object,
807 type => 'integer',
808 ) || return( $self->pass_error( $tbl_o->fo->error ) );
809 $fields->{ $f . ' AS "' . $as{ $field } . '"' } = $fo;
810 }
811 }
812 if( $query_type eq 'select' &&
813 $enhance &&
814 exists( $fields->{last_name} ) &&
815 exists( $fields->{first_name} ) &&
816 !exists( $fields->{name} ) )
817 {
818  
819 my $f = $prefix
820 ? "CONCAT(${prefix}.first_name, ' ', ${prefix}.last_name)"
821 : "CONCAT(first_name, ' ', last_name)";
822 push( @extra, "$f AS name" );
823 }
824  
825 if( ( exists( $default->{auth} ) && !defined( $arg{auth} ) ) ||
826 defined( $arg{auth} ) )
827 {
828 $default->{auth} = defined( $arg{auth} )
829 ? $arg{auth}
830 : 0;
831 }
832 if( ( exists( $default->{status} ) && !defined( $default->{status} ) ) ||
833 defined( $arg{status} ) )
834 {
835 $default->{status} = defined( $arg{status} )
836 ? $arg{status}
837 : 1;
838 }
839  
840 foreach my $data ( keys( %arg ) )
841 {
842 if( exists( $default->{ $data } ) )
843 {
844 $default->{ $data } = $arg{ $data };
845 }
846 }
847 my %from_unixtime = ();
848 if( $self->_is_array( $from_unix ) )
849 {
850 %from_unixtime = map{ $_ => 1 } @$from_unix;
851 }
852 elsif( $self->_is_hash( $from_unix => 'strict' ) )
853 {
854 %from_unixtime = %$from_unix;
855 }
856  
857 $self->{_args} = $arg;
858 $self->{_default} = $default;
859 $self->{_fields} = $fields;
860 $self->{_extra} = \@extra;
861 $self->{_structure} = $structure;
862 $self->{_from_unix} = \%from_unixtime;
863 $self->{_to_unix} = \%to_unixtime;
864 $self->{query_type} = $query_type;
865 $self->{bind} = $tbl_o->database_object->use_bind;
866 return( $self );
867 }
868  
869 sub group { return( shift->_group_order( 'group', 'group_by', @_ ) ); }
870  
871 sub having { return( shift->error( "Having clause is not supported by this driver." ) ); }
872  
873 # $tbl->insert( field1 => $val1, field2 => $val2 );
874 # or
875 # $tbl->insert([ field1 => $val1, field2 => $val2 ]);
876 # or
877 # $tbl->insert({ field1 => $val1, field2 => $val2 });
878 # or
879 # my $select_statement_object = $tbl2->select || die( $tbl2->error );
880 # $tbl->insert( $select_statement_object );
881 # or
882 # my $select_statement_object = $tbl2->select || die( $tbl2->error );
883 # $tbl->insert( field1 => $val1, field2 => $val2, $select_statement_object );
884 # or
885 # my $select_statement_object = $tbl2->select || die( $tbl2->error );
886 # $tbl->insert([ field1 => $val1, field2 => $val2, $select_statement_object ]);
887 sub insert
888 {
889 my $self = shift( @_ );
890 # Could be an array of fields, or a SQL statement object.
891 my $data = shift( @_ ) if( @_ == 1 && ref( $_[0] ) );
892 my @arg = @_;
893 my $constant = $self->constant;
894 if( scalar( keys( %$constant ) ) )
895 {
896 return( $constant->{sth} ) if( $constant->{sth} && $self->_is_object( $constant->{sth} ) && $constant->{sth}->isa( 'DB::Object::Statement' ) );
897 }
898 my %arg = ();
899 my $select = '';
900 my $base_class = $self->base_class;
901 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
902 my $table = $tbl_o->name ||
903 return( $self->error( "No table was provided to insert data." ) );
904 # We do not decide of the value of AUTO_INCREMENT fields, so we do not use them in
905 # our INSERT statement.
906 my $fields_ref = $tbl_o->fields || return( $self->pass_error( $tbl_o->error ) );
907 my @avoid = ();
908 my( $fields, $values, $elems );
909 my $el = $self->elements;
910  
911 if( !@arg && $data && $self->_is_hash( $data => 'strict' ) )
912 {
913 @arg = %$data;
914 }
915 # User passed an array reference
916 elsif( !@arg && ref( $data ) && $self->_is_array( $data ) )
917 {
918 @arg = @$data;
919 if( scalar( @arg ) && $self->_is_a( $arg[-1] => "${base_class}::Statement" ) )
920 {
921 my $sth = pop( @arg );
922 $select = $sth->as_string;
923 $el->merge( $sth->query_object->elements );
924 }
925 }
926 # insert into (field1, field2, field3) select field1, field2, field3 from some_table where some_id=12
927 elsif( $data && ref( $data ) eq "${base_class}::Statement" )
928 {
929 $select = $data->as_string;
930 $el->merge( $data->query_object->elements );
931 }
932 elsif( scalar( @arg ) && $self->_is_a( $arg[-1] => "${base_class}::Statement" ) )
933 {
934 my $sth = pop( @arg );
935 $select = $sth->as_string;
936 $el->merge( $sth->query_object->elements );
937 }
938 my @query = ();
939 if( $select )
940 {
941 my $sql;
942 if( scalar( @arg ) )
943 {
944 for( my $i = 0; $i < scalar( @arg ); $i++ )
945 {
946 if( $self->_is_a( $arg[$i] => 'DB::Object::Fields::Unknown' ) )
947 {
948 warn( "Unknown field object '", $arg[$i]->field, "' provided for INSERT into table '", $arg[$i], "'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
949 splice( @arg, $i, 1 );
950 }
951 }
952 $sql = "INSERT INTO $table (" . join( ', ', @arg ) . ") $select";
953 }
954 else
955 {
956 $sql = "INSERT INTO $table $select";
957 }
958 @query = ( $sql );
959 }
960 else
961 {
962 %arg = @arg if( @arg );
963 foreach my $field ( keys( %$fields_ref ) )
964 {
965 my $fo = $fields_ref->{ $field };
966 # push( @avoid, $field ) if( $fields_ref->{ $field } =~ /\b(AUTO_INCREMENT|SERIAL|nextval)\b/i && !$arg{ $field } );
967 if( defined( $fo->default ) &&
968 $fo->default =~ /\b(AUTO_INCREMENT|SERIAL|nextval)\b/i &&
969 !$arg{ $field } )
970 {
971 push( @avoid, $field );
972 }
973 # It is useless to insert a blank data in a field whose default value is NULL.
974 # Especially since a test on a NULL field may be made specifically.
975 if( scalar( @arg ) &&
976 !exists( $arg{ $field } ) &&
977 $fo->is_nullable )
978 {
979 push( @avoid, $field );
980 }
981 }
982 $self->getdefault(
983 table => $table,
984 arg => \@arg,
985 avoid => \@avoid,
986 ) || return( $self->pass_error );
987 $elems = $self->format_statement || return( $self->pass_error );
988 $fields = $elems->fields->join( ', ' );
989 $values = $elems->formats->join( ', ' );
990 $el->merge( $elems );
991 @query = ( "INSERT INTO $table ($fields) VALUES($values)" );
992 }
993  
994 if( $data && $self->_is_hash( $data => 'strict' ) && $el->types->length )
995 {
996 warn( "You have passed arguments to this insert as hash reference, and you are using placeholders. Using placeholders requires fixed order of arguments which an hash reference cannot guarantee. This will potentially lead to error when executing the query. I recommend you switch to an array of arguments instead, i.e. from { field1 => value1, field2 => value2 } to ( field1 => value1, field2 => value2 ), or to use numbered placeholders like \$1, \$2, etc..." ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
997 }
998 my $clauses = $self->_query_components( 'insert' ) || return( $self->pass_error );
999 push( @query, @$clauses ) if( scalar( @$clauses ) );
1000 my $query = $self->{query} = CORE::join( ' ', @query );
1001 # Everything meaningfull lies within the object
1002 # If no bind should be done _save_bind does nothing
1003 $self->_save_bind();
1004 # Query string should lie within the object
1005 # _cache_this sends back an object no matter what or unde() if an error occurs
1006 my $sth = $tbl_o->_cache_this( $self );
1007 # STOP! No need to go further
1008 if( !defined( $sth ) )
1009 {
1010 return( $self->error( "Error '", $tbl_o->error, "' while preparing query to insert data into table '$table':\n$query" ) );
1011 }
1012 # Called in void context
1013 if( !defined( wantarray() ) )
1014 {
1015 $sth->execute() ||
1016 return( $self->error( "Error while executing query to insert data to table '$table':\n$query" ) );
1017 }
1018 return( $sth );
1019 }
1020  
1021 sub is_upsert { return( shift->_set_get_boolean( 'is_upsert', @_ ) ); }
1022  
1023 sub join_fields { return( shift->_set_get_scalar( 'join_fields', @_ ) ); }
1024  
1025 sub join_tables { return( shift->_set_get_object_array_object( 'join_tables', 'DB::Object::Tables', @_ ) ); }
1026  
1027 sub left_join { return( shift->_set_get_hash( 'left_join', @_ ) ); }
1028  
1029 sub limit
1030 {
1031 my $self = shift( @_ );
1032 my $limit = $self->{limit};
1033 if( @_ )
1034 {
1035 # Returns a DB::Object::Query::Clause
1036 $limit = $self->_process_limit( @_ ) ||
1037 return( $self->pass_error );
1038 if( CORE::length( $limit->metadata->limit // '' ) )
1039 {
1040 $limit->generic( CORE::length( $limit->metadata->offset // '' ) ? 'LIMIT ?, ?' : 'LIMIT ?' );
1041 # %s works for integer, and also for numbered placeholders like $1 or ?1, or regular placeholder like ?
1042 $limit->value(
1043 CORE::length( $limit->metadata->offset // '' )
1044 ? sprintf( "LIMIT %s, %s", $limit->metadata->offset, $limit->metadata->limit )
1045 : sprintf( "LIMIT %s", $limit->metadata->limit )
1046 );
1047 }
1048 }
1049  
1050 if( !$limit && want( 'OBJECT' ) )
1051 {
1052 return( $self->new_null( type => 'object' ) );
1053 }
1054 return( $limit );
1055 }
1056  
1057 sub local
1058 {
1059 my $self = shift( @_ );
1060 $self->{local} ||= {};
1061 my $local = $self->{local};
1062 if( @_ )
1063 {
1064 my $data = $self->_get_args_as_hash( @_ );
1065 my $str = '';
1066 if( scalar( keys( %$data ) ) )
1067 {
1068 my @keys = keys( %$data );
1069 @$local{ @keys } = @$data{ @keys };
1070 }
1071 }
1072 return( wantarray() ? () : undef() ) if( !$local || !%$local );
1073 return( %$local ) if( wantarray() );
1074 my $str = join( ', ', map{ "\@${_} = '" . $local->{ $_ } . "'" } keys( %$local ) );
1075 # return( "SET $str" );
1076 return( $str );
1077 }
1078  
1079 sub lock { return( shift->error( "Locking mechanism is not supported by this driver." ) ); }
1080  
1081 sub new_clause
1082 {
1083 my $self = shift( @_ );
1084 my $opts = $self->_get_args_as_hash( @_ );
1085 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1086 $opts->{query_object} = $self;
1087 my $o = DB::Object::Query::Clause->new( %$opts ) ||
1088 return( $self->error( "Unable to create a DB::Object::Query::Clause object: ", DB::Object::Query::Clause->error ) );
1089 # Weaken the back-reference to the query object to prevent circular reference memory leaks.
1090 weaken( $o->{query_object} ) if( $o->{query_object} );
1091 return( $o );
1092 }
1093  
1094 sub new_element
1095 {
1096 my $self = shift( @_ );
1097 my $opts = $self->_get_args_as_hash( @_ );
1098 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1099 $opts->{query_object} = $self;
1100 my $elem = DB::Object::Query::Element->new( %$opts ) ||
1101 return( $self->pass_error( DB::Object::Query::Element->error ) );
1102 # Weaken the back-reference to the query object to prevent circular reference memory leaks.
1103 weaken( $elem->{query_object} ) if( $elem->{query_object} );
1104 return( $elem );
1105 }
1106  
1107 sub new_elements
1108 {
1109 my $self = shift( @_ );
1110 my $opts = $self->_get_args_as_hash( @_ );
1111 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1112 $opts->{query_object} = $self;
1113 my $e = DB::Object::Query::Elements->new( %$opts ) ||
1114 return( $self->pass_error( DB::Object::Query::Elements->error ) );
1115 # Weaken the back-reference to the query object to prevent circular reference memory leaks.
1116 weaken( $e->{query_object} ) if( $e->{query_object} );
1117 return( $e );
1118 }
1119  
1120 sub order { return( shift->_group_order( 'order', 'order_by', @_ ) ); }
1121  
1122 sub pass_error
1123 {
1124 my $self = shift( @_ );
1125  
1126 # Propagating an error also taints this query object.
1127 $self->{dirty} = 1 if( ref( $self ) );
1128  
1129 return( $self->SUPER::pass_error( @_ ) );
1130 }
1131  
1132 sub prepare_options { return( shift->_set_get_hash_as_mix_object( 'prepare_options', @_ ) ); }
1133  
1134 sub query { return( shift->_set_get_scalar( 'query', @_ ) ); }
1135  
1136 sub query_reset { return( shift->_set_get_boolean( 'query_reset', @_ ) ); }
1137  
1138 sub query_reset_core_keys { return( shift->_set_get_array_as_object( 'query_reset_core_keys', @_ ) ); }
1139  
1140 sub query_reset_keys { return( shift->_set_get_array_as_object( 'query_reset_keys', @_ ) ); }
1141  
1142 sub query_type { return( shift->_set_get_scalar( 'query_type', @_ ) ); }
1143  
1144 sub query_values { return( shift->_set_get_scalar_as_object( 'query_values', @_ ) ); }
1145  
1146 sub replace { return( shift->error( "The replace sql query is not supported by this driver." ) ); }
1147  
1148 sub reset
1149 {
1150 my $self = shift( @_ );
1151 if( !$self->{query_reset} )
1152 {
1153 my $core_keys = $self->query_reset_core_keys;
1154 my $keys = $self->query_reset_keys;
1155 # Make sure the driver's list of keys for query reset is complete by merging this base class keys with the diver's one
1156 unless( $core_keys == $keys )
1157 {
1158 my $new_keys = $keys->merge( $core_keys )->unique->sort;
1159 $keys = $self->query_reset_keys( $new_keys );
1160 }
1161 CORE::delete( @$self{ @$keys } );
1162 # elements is not in query_reset_core_keys because CORE::delete would leave it undef
1163 # and there is no re-init pass after reset(). We clear it explicitly here instead,
1164 # so that _save_bind() on each fresh select() starts from an empty element stack.
1165 $self->{elements} = $self->new_elements;
1166 $self->{query_reset}++;
1167 # $self->{enhance} = 1;
1168 }
1169 return( $self );
1170 }
1171  
1172 sub reset_bind
1173 {
1174 my $self = shift( @_ );
1175 my @f = qw( binded binded_group binded_limit binded_order binded_types binded_where );
1176 foreach my $field ( @f )
1177 {
1178 $self->{ $field } = [];
1179 }
1180 return( $self );
1181 }
1182  
1183 sub returning { return( shift->error( "Returning clause is not supported by this driver" ) ); }
1184  
1185 sub reverse
1186 {
1187 my $self = shift( @_ );
1188 if( @_ )
1189 {
1190 $self->{reverse}++;
1191 }
1192 return( $self->{reverse} );
1193 }
1194  
1195 sub select
1196 {
1197 my $self = shift( @_ );
1198 my $constant = $self->constant;
1199 if( scalar( keys( %$constant ) ) )
1200 {
1201 return( $constant->{sth} ) if( $constant->{sth} && $self->_is_object( $constant->{sth} ) && $constant->{sth}->isa( 'DB::Object::Statement' ) );
1202 }
1203 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
1204 my $prefix = $tbl_o->query_object->table_alias ? $tbl_o->query_object->table_alias : $tbl_o->prefix;
1205 my $table = $tbl_o->qualified_name ||
1206 return( $self->error( "No table name provided to perform select statement." ) );
1207 my $bind = $tbl_o->use_bind;
1208 my $cache = $tbl_o->use_cache;
1209 my $multi_db = $tbl_o->prefix_database;
1210 my $db = $tbl_o->database();
1211 my $fields = '';
1212 my $ok_ref = $tbl_o->fields;
1213 my $ok_list = CORE::join( '|', keys( %$ok_ref ) );
1214 my $tables = CORE::join( '|', @{$tbl_o->database_object->tables} );
1215 if( @_ )
1216 {
1217 # Get aliases
1218 my $alias = $self->alias();
1219 my $data = ( @_ == 1 && ref( $_[0] ) ) ? shift( @_ ) : [ @_ ];
1220 if( ref( $data ) eq 'SCALAR' )
1221 {
1222 $fields = $$data;
1223 }
1224 elsif( $self->_is_array( $data ) )
1225 {
1226 # Remove from the provided list any name that are aliases
1227 FIELD: for( my $i = 0; $i < scalar( @$data ); $i++ )
1228 {
1229 if( $self->_is_a( $data->[$i] => 'DB::Object::Fields::Unknown' ) )
1230 {
1231 warn( "Unknown field object '", $data->[$i]->field, "' of table '", $data->[$i]->table, "' used in SELECT statement" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
1232 splice( @$data, $i, 1 );
1233 $i--;
1234 next;
1235 }
1236  
1237 foreach my $n ( keys( %$alias ) )
1238 {
1239 if( lc( $alias->{ $n } ) eq lc( $data->[$i] ) )
1240 {
1241 splice( @$data, $i, 1 );
1242 $i--;
1243 next FIELD;
1244 }
1245 }
1246 }
1247 # No fields provided after all? We fallback to use the magic '*' optimizer
1248 $fields = @$data
1249 ? CORE::join( ', ', @$data )
1250 : scalar( keys( %$alias ) )
1251 ? ''
1252 : ( $prefix ? "${prefix}.*" : '*' );
1253 }
1254 else
1255 {
1256 $fields = $data;
1257 }
1258  
1259 if( length( $fields ) )
1260 {
1261 # Now, we eventually add the table and database specification to the fields
1262 $fields =~ s{
1263 (?<![\.\"])\b($ok_list)\b(\s*)?(?!\.)
1264 }
1265 {
1266 my( $field, $spc ) = ( $1, $2 );
1267 if( $` =~ /\s+(?:AS|FROM)\s+$/i || !$field )
1268 {
1269 "${field}${spc}";
1270 }
1271 elsif( $prefix )
1272 {
1273 "${prefix}.${field}${spc}";
1274 }
1275 else
1276 {
1277 "${field}${spc}";
1278 }
1279 }gex;
1280 $fields =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
1281 }
1282  
1283 if( $alias && %$alias )
1284 {
1285 my @aliases = ();
1286 foreach my $f ( keys( %$alias ) )
1287 {
1288 if( ref( $alias->{ $f } ) eq 'SCALAR' )
1289 {
1290 CORE::push( @aliases, "$f AS " . ${$alias->{ $f }} );
1291 }
1292 elsif( CORE::exists( $ok_ref->{ $f } ) && $prefix )
1293 {
1294 CORE::push( @aliases, "${prefix}.${f} AS \"" . $alias->{ $f } . "\"" );
1295 }
1296 elsif( $f =~ /\b(?:$ok_list)\b/ ||
1297 $f =~ /\w\([^\)]*\)/ )
1298 {
1299 $f =~ s{
1300 (?<![\.\"])\b($ok_list)\b(\s*)?(?!\.)
1301 }
1302 {
1303 my( $ok, $spc ) = ( $1, $2 );
1304 "${prefix}.${ok}${spc}";
1305 }gex if( $prefix );
1306 $f =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
1307 CORE::push( @aliases, "$f AS " . "\"" . $alias->{ $f } . "\"" );
1308 }
1309 else
1310 {
1311 CORE::push( @aliases, "$f AS " . "\"" . $alias->{ $f } . "\"" );
1312 }
1313 }
1314 $fields = length( $fields )
1315 ? join( ', ', $fields, @aliases )
1316 : join( ', ', @aliases );
1317 }
1318 }
1319 else
1320 {
1321 $self->getdefault( table => $table ) || return( $self->pass_error );
1322 my $elems = $self->format_statement || return( $self->pass_error );
1323 $fields = $elems->fields->join( ', ' );
1324 }
1325  
1326 my $tie = $self->tie();
1327 my $clauses = $self->_query_components( 'select' ) || return( $self->pass_error );
1328 my $vars = $self->local();
1329 # You may not sort if there is no order clause
1330 my $sort = $self->reverse() ? 'DESC' : $self->sort() ? 'ASC' : '';
1331 # my @query = $multi_db ? ( "SELECT $fields FROM $db.$table" ) : ( "SELECT $fields FROM $table" );
1332 # $table comes from $tbl->qualified_name which automatically sets itself with the right prefixes based on the prefixed() settings
1333 my $table_alias = '';
1334 if( length( $table_alias = $self->table_alias ) )
1335 {
1336 $table_alias = " AS $table_alias";
1337 }
1338 my @query = ( "SELECT $fields FROM ${table}${table_alias}" );
1339 my $prev_fields = $self->selected_fields;
1340 my $last_sth = '';
1341 # my $queries = $self->_cache_queries;
1342 # # A simple check to avoid to do this test on each query, but rather only on those who deserve it.
1343 # if( $fields eq $prev_fields && @$queries )
1344 # {
1345 # my @last_query = grep
1346 # {
1347 # $_->selected_fields ||= '';
1348 # $_->selected_fields eq $fields
1349 # } @$queries;
1350 # $last_sth = $last_query[ 0 ] || {};
1351 # }
1352 # If the selected fields in the last query performed were the same than those ones and
1353 # that the last query object has the flag 'as_string' set to true, this would mean that
1354 # user has made a statement as string and is now really executing it
1355 # Now, if the special flag 'query_reset' is true, this means that the user has accessed the methods
1356 # where(), group(), order() or limit() and hence this is a brain new query for which we need
1357 # to get the clause conditions
1358 #if( $fields eq $$prev_fields && $last_sth->{ 'as_string' } )
1359 #{
1360 # unshift( @query, "${vars};" ) if( $vars );
1361 push( @query, @$clauses ) if( @$clauses );
1362 #}
1363 # used by join()
1364 $self->selected_fields( $fields );
1365 my $query = $self->{query} = CORE::join( ' ', @query );
1366 my @tie_order = ();
1367 if( $tie && %$tie )
1368 {
1369 my $copy = $fields;
1370 # According to bind_col() specifications, we need to bind perl variable
1371 # in the right column order.
1372 # We make it easy for our user, to only provide the column name and its corresponding variable
1373 # We will do the job of matching
1374 while( $copy =~ s/^.*?\b([a-zA-Z0-9\_]+)\s*(?:\,|\Z)// )
1375 {
1376 push( @tie_order, $1 );
1377 }
1378 $self->{tie_order} = \@tie_order;
1379 }
1380 # Everything meaningfull lies within the object
1381 # If no bind should be done _save_bind does nothing
1382 $self->_save_bind();
1383  
1384 # Predeclare variables if any.
1385 $tbl_o->set();
1386  
1387 # Query string should lie within the object
1388 # _cache_this sends back an object no matter what or undef() if an error occurs
1389 my $sth = $tbl_o->_cache_this( $self );
1390 # STOP! No need to go further
1391 if( !defined( $sth ) )
1392 {
1393 return( $self->error( "Error while preparing query to select on table '", $tbl_o->name, "':\n$query\n", $tbl_o->error() ) );
1394 }
1395 # Routines such as as_string() expect an array on pupose so we do not have to commit the action
1396 # but rather get the statement string. At the end, we write:
1397 # $obj->select() to really select
1398 # $obj->select->as_string() to ONLY get the formatted statement
1399 # wantarray() returns the undefined value in void context, which is typical use of a real select command
1400 # i.e. $obj->select();
1401 # Straight forward declaration: $obj->select(); or $obj->select->execute() || die( $obj->error() );
1402 if( !defined( wantarray() ) )
1403 {
1404 $sth->execute ||
1405 return( $self->error( "Error while executing query to select:\n", $self->as_string(), "\n", $sth->errstr() ) );
1406 }
1407 return( $sth );
1408 }
1409  
1410 sub selected_fields { return( shift->_set_get( 'selected_fields', @_ ) ); }
1411  
1412 sub sort
1413 {
1414 my $self = shift( @_ );
1415 if( @_ )
1416 {
1417 $self->{reverse} = 0;
1418 }
1419 return( $self->{reverse} );
1420 }
1421  
1422 # The fields in their order of appearance in insert and update
1423 # so that following ->exec( $hash ) would be able to allocate the bind values in the right order
1424 sub sorted { return( shift->_set_get_array_as_object( 'sorted', @_ ) ); }
1425  
1426 sub table_alias { return( shift->_set_get_scalar( 'table_alias', @_ ) ); }
1427  
1428 sub table_object { return( shift->_set_get_object_without_init( 'table_object', 'DB::Object::Tables', @_ ) ); }
1429  
1430 sub tie
1431 {
1432 my $self = shift( @_ );
1433 if( @_ )
1434 {
1435 my $ref = '';
1436 $ref = shift( @_ ) if( @_ && @_ % 2 );
1437 my %hash = ( @_ );
1438 $ref ||= \%hash;
1439 $self->{tie} = $ref;
1440 }
1441 return( wantarray() ? %{$self->{tie}} : $self->{tie} );
1442 }
1443  
1444 sub unix_timestamp { return( shift->_set_get_array_as_object( 'unix_timestamp', @_ ) ); }
1445  
1446 sub update
1447 {
1448 my $self = shift( @_ );
1449 my $data = shift( @_ ) if( @_ == 1 && ref( $_[ 0 ] ) );
1450 my @arg = @_;
1451 if( !@arg && $data )
1452 {
1453 if( $self->_is_hash( $data => 'strict' ) )
1454 {
1455 @arg = %$data;
1456 }
1457 elsif( $self->_is_array( $data ) )
1458 {
1459 @arg = @$data;
1460 }
1461 }
1462 my $constant = $self->constant;
1463 if( scalar( keys( %$constant ) ) )
1464 {
1465 return( $constant->{sth} ) if( $constant->{sth} && $self->_is_object( $constant->{sth} ) && $constant->{sth}->isa( 'DB::Object::Statement' ) );
1466 }
1467 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
1468 my $table = $tbl_o->name ||
1469 return( $self->error( "No table to update was provided." ) );
1470 if( !scalar( @arg ) )
1471 {
1472 return( $self->error( "No data to update was provided." ) );
1473 }
1474 my $el = $self->elements;
1475 my $elems = $self->format_update( \@arg ) || return( $self->pass_error );
1476 $el->merge( $elems ) || return( $self->pass_error );
1477 my $values = $elems->formats->join( ', ' );
1478 my $clauses = $self->_query_components( 'update' );
1479 my @query = ( "UPDATE $table SET $values" );
1480 push( @query, @$clauses ) if( scalar( @$clauses ) );
1481 my $query = $self->{query} = CORE::join( ' ', @query );
1482 if( !$self->where && !$self->database_object->allow_bulk_update )
1483 {
1484 my( $p, $f, $l ) = caller();
1485 my $call_sub = ( caller(1) )[3];
1486 return( $self->error( "Refusing to do a bulk update. Called from package $p in file $f at line $l from sub $call_sub. Enable the allow_bulk_update database object property if you want to do so. Original query was: $query" ) );
1487 }
1488 $self->query_values( $values );
1489 $self->_save_bind();
1490 my $sth = $tbl_o->_cache_this( $self ) || return( $self->pass_error( $tbl_o->error ) );
1491 # return( $self->error( "Error while preparing query to update table '$table':\n$query" ) );
1492 # $obj->update() to really delete
1493 # $obj->update->as_string() to ONLY get the formatted statement
1494 # wantarray() returns the undefined value in void context, which is typical use of a real update command
1495 # i.e. $obj->update();
1496 if( !defined( wantarray() ) )
1497 {
1498 $sth->execute() ||
1499 return( $self->error( "Error while executing query to update table '$table':\n$query\n", $sth->error ) );
1500 # $sth->finish();
1501 }
1502 # wantarray returns false but not undefined when $obj->update->as_string();
1503 return( $sth );
1504 }
1505  
1506 sub where { return( shift->_where_having( 'where', 'where', @_ ) ); }
1507  
1508 sub _group_order
1509 {
1510 my $self = shift( @_ );
1511 # This is the type, ie 'group', 'order' and used to initiate the DB::Object::Query::Clause
1512 my $type = shift( @_ ) || return( $self->error( "No clause type was provided." ) );
1513 # This is used to store the data in $self such as $self->{ $prop } = $clause;
1514 my $prop = shift( @_ ) || return( $self->error( "No object data property name was provided for clause type '$type'." ) );
1515 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
1516 my $dbo = $tbl_o->database_object ||
1517 return( $self->error( "No database object is currently set on this table object for table '", $tbl_o->name, "'" ) );
1518 my $bind = $tbl_o->use_bind;
1519 my $table = $tbl_o->name;
1520 # $self->{ $prop } = $self->new_clause if( !CORE::length( $self->{ $prop } ) && !ref( $self->{ $prop } ) );
1521 my $placeholder_re = $dbo->_placeholder_regexp;
1522 my $clause;
1523 if( @_ )
1524 {
1525 my $fields_ref = $tbl_o->fields;
1526 my $fields = join( '|', keys( %$fields_ref ) );
1527 my $prefix = $tbl_o->prefix;
1528 my $db = $tbl_o->database;
1529 my $tables = CORE::join( '|', @{$dbo->tables} );
1530 my $multi_db = $tbl_o->prefix_database;
1531 my $data = ( @_ == 1 && ( !$self->_is_object( $_[0] ) || $self->_is_array( $_[0] ) ) && !exists( $fields_ref->{ "$_[0]" } ) )
1532 ? shift( @_ )
1533 : [ @_ ];
1534 if( $self->_is_array( $data ) )
1535 {
1536 $clause = $self->new_clause(
1537 type => $type,
1538 debug => $self->debug,
1539 );
1540  
1541 foreach my $field ( @$data )
1542 {
1543 # Some garbage reached us
1544 next if( !CORE::length( $field // '' ) );
1545  
1546 # Special treatment if we are being provided multiple clause to merge with ours
1547 if( $self->_is_a( $field => 'DB::Object::Query::Clause' ) )
1548 {
1549 if( !$self->{ $prop } )
1550 {
1551 $self->{ $prop } = $clause;
1552 }
1553 else
1554 {
1555 $clause = $self->{ $prop };
1556 }
1557 $clause->merge( $field );
1558 next;
1559 }
1560  
1561 # Transform a simple 'field' into a field object
1562 $field = $tbl_o->fo->$field if( CORE::exists( $fields_ref->{ $field } ) );
1563 # my $elem = $self->new_element( field => $field );
1564 my $elem;
1565 if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) )
1566 {
1567 $elem = $self->new_element(
1568 field => $field,
1569 # Not necessary; this is already the default value
1570 # generic => '?',
1571 type => '',
1572 value => $field,
1573 );
1574 }
1575 elsif( $self->_is_a( $field => 'DB::Object::Fields::Unknown' ) )
1576 {
1577 # warn( "Unnown field provided with field object for field ", $field->field ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
1578 # next;
1579 return( $self->error( "Unnown field provided with field object for field '", $field->field, "'" ) );
1580 }
1581 # i.e. GROUP BY width => GROUP BY table.width
1582 elsif( ref( $field ) eq 'SCALAR' )
1583 {
1584 $elem = $self->new_element(
1585 field => $field,
1586 type => '',
1587 value => $$field,
1588 );
1589 }
1590 elsif( $field =~ /($placeholder_re)/ )
1591 {
1592 $elem = $self->new_element(
1593 field => $field,
1594 placeholder => $1,
1595 type => '',
1596 value => $field,
1597 );
1598 }
1599 elsif( $field =~ /\b(?:$fields)\b/ ||
1600 $field =~ /\w\([^\)]*\)/ ||
1601 !$bind )
1602 {
1603 $field =~ s{
1604 (?<![\.\"])\b($fields)\b(\s*)?(?!\.)
1605 }
1606 {
1607 my( $ok, $spc ) = ( $1, $2 );
1608 "${prefix}.${ok}${spc}";
1609 }gex if( $prefix );
1610 $field =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
1611 $elem = $self->new_element(
1612 field => $field,
1613 type => '',
1614 value => $field,
1615 );
1616 }
1617 else
1618 {
1619 $elem = $self->new_element(
1620 field => $field,
1621 # Not necessary; this is already the default value
1622 # generic => '?',
1623 type => '',
1624 value => $field,
1625 );
1626 }
1627 $clause->push( $elem );
1628 }
1629 $clause->value( $clause->values->join( ', ' ) );
1630 $clause->generic( $clause->generics->join( ', ' ) );
1631 }
1632 # Merging our clause with a new one
1633 elsif( $self->_is_a( $data => 'DB::Object::Query::Clause' ) )
1634 {
1635 $clause = $self->{ $prop }
1636 ? $self->{ $prop }
1637 : $self->new_clause( type => $type );
1638 $clause->merge( $data );
1639 }
1640 else
1641 {
1642 $clause = $self->new_clause({
1643 value => $data,
1644 type => $type,
1645 });
1646 my $elem;
1647 if( ref( $data ) eq 'SCALAR' )
1648 {
1649 $elem = $self->new_element(
1650 field => $data,
1651 type => '',
1652 value => $$data,
1653 );
1654 $clause->push( $elem );
1655 }
1656 elsif( $data =~ /($placeholder_re)/ )
1657 {
1658 $elem = $self->new_element(
1659 field => $data,
1660 placeholder => $1,
1661 type => '',
1662 value => $data,
1663 );
1664 $clause->push( $elem );
1665 }
1666 elsif( $data =~ /\b(?:$fields)\b/ ||
1667 $data =~ /\w\([^\)]*\)/ ||
1668 !$bind )
1669 {
1670 $data =~ s{
1671 (?<![\.\"])\b($fields)\b(\s*)?(?!\.)
1672 }
1673 {
1674 my( $ok, $spc ) = ( $1, $2 );
1675 "${prefix}.${ok}${spc}";
1676 }gex if( $prefix );
1677 $data =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
1678 $elem = $self->new_element(
1679 field => $data,
1680 type => '',
1681 value => $data,
1682 );
1683 $clause->push( $elem );
1684 }
1685 elsif( $bind )
1686 {
1687 # $self->_value2bind( \$data, $ref );
1688 my $elems = $self->_value2bind( \$data );
1689 # $clause->bind->values( $ref );
1690 # $clause->bind->types( ( '' ) x scalar( @$ref ) );
1691 $clause->push( $elems->elements->list ) if( $elems->elements->length );
1692 }
1693 else
1694 {
1695 $elem = $self->new_element(
1696 field => $data,
1697 # Not necessary; this is already the default value
1698 # generic => '?',
1699 type => '',
1700 value => $data,
1701 );
1702 $clause->push( $elem );
1703 }
1704 }
1705 $self->{ $prop } = $clause if( $clause->elements->length );
1706 }
1707 else
1708 {
1709 $clause = $self->{ $prop };
1710 }
1711  
1712 if( !$clause && want( 'OBJECT' ) )
1713 {
1714 return( $self->new_null( type => 'object' ) );
1715 }
1716 return( $clause );
1717 }
1718  
1719 # Each driver can call on this private method like sub having { return( shift->_having( @_ ) ); }
1720 # to avoid recreating it themselve
1721 sub _having
1722 {
1723 my $self = shift( @_ );
1724 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
1725 my $bind = $tbl_o->use_bind;
1726 my $table = $tbl_o->name;
1727 my $prefix = $tbl_o->prefix;
1728 my $placeholder_re = $tbl_o->database_object->_placeholder_regexp;
1729 my $clause;
1730 if( @_ )
1731 {
1732 my $data = ( @_ == 1 ) ? shift( @_ ) : [ @_ ];
1733 if( $self->_is_array( $data ) )
1734 {
1735 my $fields_ref = $tbl_o->fields;
1736 my $fields = join( '|', keys( %$fields_ref ) );
1737 my $db = $tbl_o->database;
1738 my $tables = CORE::join( '|', @{$self->{tables}->{ $db }} );
1739 my $multi_db = $tbl_o->prefix_database;
1740 my @values = ();
1741 my @clause = ();
1742 my @types = ();
1743 foreach my $field ( @$data )
1744 {
1745 # In case we received some garbage
1746 next if( !CORE::length( $field ) );
1747  
1748 # Special treatment if we are being provided multiple clause to merge with ours
1749 if( $self->_is_a( $field => 'DB::Object::Query::Clause' ) )
1750 {
1751 if( !$self->{having} )
1752 {
1753 $self->{having} = $self->new_clause( type => 'having' );
1754 }
1755 else
1756 {
1757 $clause = $self->{having};
1758 }
1759 $clause->merge( $field );
1760 next;
1761 }
1762  
1763 # i.e. HAVING width => HAVING table.width
1764 if( ref( $field ) eq 'SCALAR' )
1765 {
1766 push( @clause, $self->new_clause({
1767 value => $$field,
1768 type => 'having',
1769 }) );
1770 }
1771 elsif( $field =~ /($placeholder_re)/ )
1772 {
1773 my $plh = $1;
1774 my $cl = $self->new_clause(
1775 value => $field,
1776 type => 'having',
1777 );
1778  
1779 my $elem = $self->new_element(
1780 format => $field,
1781 placeholder => $plh,
1782 );
1783 $cl->push( $elem );
1784 CORE::push( @clause, $cl );
1785 }
1786 elsif( $field =~ /\b(?:$fields)\b/ ||
1787 $field =~ /\w\([^\)]*\)/ ||
1788 !$bind )
1789 {
1790 $field =~ s{
1791 (?<![\.\"])\b($fields)\b(\s*)?(?!\.)
1792 }
1793 {
1794 my( $ok, $spc ) = ( $1, $2 );
1795 "${prefix}.${ok}${spc}";
1796 }gex if( $prefix );
1797 $field =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
1798 push( @clause, $self->new_clause({
1799 value => $field,
1800 type => 'having',
1801 }) );
1802 }
1803 elsif( $bind )
1804 {
1805 my $elem = $self->new_element(
1806 placeholder => '?',
1807 value => $field,
1808 );
1809 my $cl = $self->new_clause(
1810 value => '?',
1811 type => 'having',
1812 );
1813 $cl->push( $elem );
1814 CORE::push( @clause, $cl );
1815 }
1816 else
1817 {
1818 push( @clause, $self->new_clause({
1819 value => $field,
1820 type => 'having',
1821 }) );
1822 }
1823 }
1824 $clause = $self->new_clause( type => 'having' )->merge( $self->database_object->AND( @clause ) );
1825 # $clause->bind->values( @values ) if( $bind );
1826 # $clause->bind->types( @types ) if( $bind );
1827 }
1828 else
1829 {
1830 # my $ref = [];
1831 # if( $bind )
1832 # {
1833 # $self->_value2bind( \$clause, $ref );
1834 # $clause->bind->values( @$ref ) if( $bind && scalar( @$ref ) );
1835 # $clause->bind->types( ( '' ) x scalar( @$ref ) ) if( $bind );
1836 # }
1837 my $elems = $self->_value2bind( \$data );
1838 $clause = $self->new_clause(
1839 value => $data,
1840 type => 'having',
1841 );
1842 $clause->push( $elems->elements->list ) if( $elems->elements->length );
1843 }
1844 $self->{having} = $clause;
1845 }
1846 else
1847 {
1848 $clause = $self->{having};
1849 }
1850  
1851 if( !$clause && want( 'OBJECT' ) )
1852 {
1853 return( $self->new_null( type => 'object' ) );
1854 }
1855 return( $clause );
1856 }
1857  
1858 sub _initiate_clause_object
1859 {
1860 my $self = shift( @_ );
1861 return( DB::Object::Query::Clause->new( @_ ) );
1862 }
1863  
1864 sub _limit { return( shift->_set_get_object( 'limit', 'DB::Object::Query::Clause', @_ ) ); }
1865  
1866 sub _process_limit
1867 {
1868 my $self = shift( @_ );
1869 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
1870 my $bind = $tbl_o->use_bind;
1871 my $placeholder_re = $tbl_o->database_object->_placeholder_regexp;
1872 my $limit;
1873  
1874 # $self->limit can be used to set the offset and limit, but can also be used to
1875 # pass limit clause object to be merged, so here we check it, and if found, we do not go further.
1876 if( @_ )
1877 {
1878 # First check if what we are being provided is not clause objects
1879 my @clauses = ();
1880 for( my $i = 0; $i < scalar( @_ ); $i++ )
1881 {
1882 # Special treatment if we are being provided multiple clause to merge with ours
1883 if( $self->_is_a( $_[$i] => 'DB::Object::Query::Clause' ) )
1884 {
1885 push( @clauses, $_[$i] );
1886 splice( @_, $i, 1 );
1887 $i--;
1888 }
1889 }
1890  
1891 if( scalar( @clauses ) )
1892 {
1893 if( !$self->{limit} )
1894 {
1895 $self->{limit} = $limit = $self->new_clause( type => 'limit' );
1896 }
1897 else
1898 {
1899 $limit = $self->{limit};
1900 }
1901 $limit->merge( @clauses );
1902 return( $limit );
1903 }
1904  
1905 my( $start, $end );
1906 if( @_ == 1 )
1907 {
1908 $end = shift( @_ );
1909 }
1910 else
1911 {
1912 ( $start, $end ) = splice( @_, 0, 2 );
1913 }
1914 my @binded = ();
1915 my @list = ();
1916 my @types = ();
1917 my @generic = ();
1918 $limit = $self->new_clause( type => 'limit' );
1919 foreach my $value ( $start, $end )
1920 {
1921 next if( !CORE::length( $value // '' ) );
1922 my $elem = $self->new_element;
1923 # This is a raw parameter - being a ref to a SCALAR means we must not modify it
1924 if( ref( $value ) eq 'SCALAR' )
1925 {
1926 push( @list, $$value );
1927 }
1928 # A value to be a place holder - forward it
1929 # elsif( $value eq '?' )
1930 elsif( $value =~ /($placeholder_re)/ )
1931 {
1932 # Maybe ? or $1, or ?1
1933 push( @list, $1 );
1934 push( @generic, $1 );
1935 $elem->placeholder( $1 );
1936 # push( @binded, $value );
1937 # push( @types, '' );
1938 $elem->value( $value );
1939 }
1940 # Normal processing
1941 else
1942 {
1943 push( @list, $value );
1944 push( @generic, '?' );
1945 # push( @binded, $value );
1946 # push( @types, '' );
1947 $elem->placeholder( '?' );
1948 $elem->value( $value );
1949 }
1950 $limit->push( $elem );
1951 }
1952 # $limit = $self->{limit} = [ @list ];
1953 $limit->value( CORE::join( ', ', @list ) ) if( scalar( @list ) );
1954 $limit->generic( CORE::join( ', ', @generic ) ) if( scalar( @generic ) );
1955 # $limit->bind->values( \@binded );
1956 # $limit->bind->types( \@types );
1957 if( scalar( @list ) )
1958 {
1959 if( scalar( @list ) > 1 )
1960 {
1961 $limit->metadata->offset( $list[0] ) if( CORE::length( $list[0] // '' ) );
1962 $limit->metadata->limit( $list[1] ) if( CORE::length( $list[1] // '' ) );
1963 }
1964 else
1965 {
1966 $limit->metadata->offset( '' );
1967 $limit->metadata->limit( $list[0] ) if( CORE::length( $list[0] // '' ) );
1968 }
1969 }
1970 $self->{limit} = $limit;
1971 }
1972 else
1973 {
1974 $limit = $self->{limit};
1975 }
1976  
1977 if( !$limit && want( 'OBJECT' ) )
1978 {
1979 return( $self->new_null( type => 'object' ) );
1980 }
1981 return( $limit );
1982 }
1983  
1984 sub _query_components
1985 {
1986 my $self = shift( @_ );
1987 my $type = lc( shift( @_ ) ) || $self->_query_type() || return( $self->error( "You must specify a query type: select, insert, update or delete" ) );
1988 my( $where, $group, $sort, $order, $limit );
1989 $where = $self->where;
1990 if( $type eq 'select' )
1991 {
1992 $group = $self->group;
1993 $sort = $self->reverse ? 'DESC' : $self->sort ? 'ASC' : '';
1994 $order = $self->order;
1995 }
1996 $limit = $self->limit;
1997 my @query = ();
1998 push( @query, "WHERE $where" ) if( $where && $type ne 'insert' );
1999 push( @query, "GROUP BY $group" ) if( $group && $type eq 'select' );
2000 push( @query, "ORDER BY $order" ) if( $order && $type eq 'select' );
2001 push( @query, $sort ) if( $sort && $order && $type eq 'select' );
2002 push( @query, "LIMIT $limit" ) if( $limit && $type ne 'insert' );
2003 return( \@query );
2004 }
2005  
2006 sub _query_type
2007 {
2008 my $self = shift( @_ );
2009 if( $self->{query} && length( $self->{query} ) )
2010 {
2011 return( lc( ( $self->{query} =~ /^[[:blank:]]*(ALTER|CREATE|DROP|GRANT|LISTEN|NOTIFY|INSERT|UPDATE|DELETE|SELECT|TRUNCATE)\b/i )[0] ) )
2012 }
2013 return;
2014 }
2015  
2016 sub _save_bind
2017 {
2018 my $self = shift( @_ );
2019 my $type = shift( @_ );
2020 if( !$type )
2021 {
2022 my( $pkg, $file, $line, $sub ) = caller( 1 );
2023 $sub =~ s/(.*):://;
2024 $type = $sub;
2025 }
2026 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
2027 my $bind = $tbl_o->use_bind;
2028 my $where = $self->where;
2029 my $group = $self->group;
2030 my $order = $self->order;
2031 my $limit = $self->limit;
2032 # This is used so upon execute, the saved binded parameters get sent to the DBI::execute method
2033 if( $bind )
2034 {
2035 # Build a fresh Elements object and assign it directly, rather than calling
2036 # $self->elements (which may return a copy) and pushing onto it. This ensures
2037 # the stored reference is always up-to-date and never accumulates across calls.
2038 my $elems = $self->new_elements;
2039 $elems->push( $where->elements ) if( $where->length && !$where->elements->is_empty );
2040 $elems->push( $group->elements ) if( $group->length && !$group->elements->is_empty );
2041 $elems->push( $order->elements ) if( $order->length && !$order->elements->is_empty );
2042 $elems->push( $limit->elements ) if( $limit->length && !$limit->elements->is_empty );
2043 $self->{elements} = $elems;
2044  
2045 }
2046 return( $self );
2047 }
2048  
2049 sub _value2bind
2050 {
2051 my $self = shift( @_ );
2052 # If we are not suppose to bind any values, there is no point to go on.
2053 # return(1) if( !$self->{ 'bind' } );
2054 my $str = shift( @_ );
2055 my $ref = shift( @_ );
2056 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
2057 my $dbo = $tbl_o->database_object ||
2058 return( $self->error( "No database object is currently set on this table object for table '", $tbl_o->name, "'" ) );
2059 my $table = $tbl_o->name;
2060 my $bind = $tbl_o->use_bind;
2061 my $db = $tbl_o->database;
2062 my $prefix = $tbl_o->prefix;
2063 my $fields_ref = $tbl_o->fields;
2064 my $fields = CORE::join( '|', keys( %$fields_ref ) );
2065 my $tables = CORE::join( '|', @{$dbo->tables} );
2066 my $multi_db = $tbl_o->param( 'multi_db' );
2067 my @binded = ();
2068 my $placeholder_re = $dbo->_placeholder_regexp;
2069 my $elems = $self->new_elements;
2070 $$str =~ s
2071 {
2072 (([\w\_]+)(?:\.))?\b([a-zA-Z\_]+)\b\s*(=|\!=|LIKE)\s*['"]([^'"]+)['"]
2073 }
2074 {
2075 do
2076 {
2077 my( $this_table, $field, $equity, $value ) = ( $2, $3, $4, $5 );
2078 # Add to the list of value to bind on execute() only if this is not already a place holder
2079 # push( @binded, $value ) if( $bind && $value ne '?' );
2080 $this_table ||= $table;
2081 $this_table .= '.';
2082 # $bind ? "${this_table}${field}=?" : "${this_table}${field}='$value'";
2083 my $elem = $self->new_element( field => "${this_table}${field}" );
2084 my $result;
2085 if( $value !~ /[\r\n]+/ &&
2086 ( $value =~ /\b(?:$fields)\b/ ||
2087 $value =~ /\w\([^\)]*\)/ ||
2088 $value =~ /$placeholder_re/ ) )
2089 {
2090 if( $value =~ /($placeholder_re)/ )
2091 {
2092 $elem->placeholder( $1 );
2093 $elem->format( $value );
2094 }
2095 $result = "${this_table}${field} $equity $value";
2096 $elems->push( $elem );
2097 }
2098 elsif( $bind )
2099 {
2100 # push( @binded, $value );
2101 $result = "${this_table}${field} $equity ?";
2102 $elem->placeholder( '?' );
2103 $elem->value( $value );
2104 $elems->push( $elem );
2105 }
2106 else
2107 {
2108 $result = "${this_table}${field} $equity '$value'";
2109 }
2110 $result;
2111 };
2112 }geix;
2113 $$str =~ s
2114 {
2115 (?<![\.\"])\b($fields)\b(\s*)?(?!\.)
2116 }
2117 {
2118 my( $ok, $spc ) = ( $1, $2 );
2119 "$prefix.$ok$spc";
2120 }gex if( $prefix );
2121 $$str =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
2122 # push( @$ref, @binded ) if( @binded );
2123 # return(1);
2124 return( $elems );
2125 }
2126  
2127 sub _where_having
2128 {
2129 my $self = shift( @_ );
2130 # This is the type, ie 'group', 'order' and used to initiate the DB::Object::Query::Clause
2131 my $type = shift( @_ ) || return( $self->error( "No clause type was provided." ) );
2132 # This is used to store the data in $self such as $self->{ $prop } = $clause;
2133 my $prop = shift( @_ ) || return( $self->error( "No object data property name was provided for clause type '$type'." ) );
2134 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
2135 my $dbo = $tbl_o->database_object ||
2136 return( $self->error( "No database object is currently set on this table object for table '", $tbl_o->name, "'" ) );
2137 my $base_class = $tbl_o->base_class;
2138 my $bind = $tbl_o->use_bind;
2139 # $self->{ $prop } = $self->new_clause if( !CORE::length( $self->{ $prop } ) || !$self->_is_object( $self->{ $prop } ) );
2140 # my $where = $self->{ $prop };
2141 my $where;
2142 my $placeholder_re = $dbo->_placeholder_regexp;
2143 if( @_ )
2144 {
2145 my @params = @_;
2146 # This will change the belonging of the object $self to the class DB::Object::Prepare so method
2147 # such as select, insert, update, delete know there are some conditionning clause to be added
2148 my $table = $tbl_o->name;
2149 my $db = $tbl_o->database;
2150 my $multi_db = $tbl_o->prefix_database;
2151 my $prefix = $tbl_o->prefix;
2152 my $fields_ref = $tbl_o->fields;
2153 my $fields = CORE::join( '|', keys( %$fields_ref ) );
2154 my $fields_type = $tbl_o->types;
2155  
2156 my $process_where_condition;
2157 $process_where_condition = sub
2158 {
2159 # my @parameters = @_;
2160 # my $data = shift( @_ ) if( @_ % 2 && !( scalar( @_ ) == 1 && $self->_is_object( $_[0] ) ) );
2161 my $data;
2162 unless( scalar( @_ ) == 1 && $self->_is_object( $_[0] ) )
2163 {
2164 $data = shift( @_ ) if( ( @_ % 2 ) && !$self->_is_object( $_[0] ) );
2165 }
2166 # Implicit AND operator by default to join multiple fields
2167 my $agg_op = 'AND';
2168 my @arg = ();
2169 if( $self->_is_a( $_[0], 'DB::Object::Operator' ) )
2170 {
2171 return( $self->error( "I was expecting an operator object, but got \"", $_[0], "\" instead." ) ) if( !$_[0]->isa( 'DB::Object::Operator' ) );
2172 $agg_op = $_[0]->operator || return( $self->error( "Unknown operator for \"", $_[0], "\"." ) );
2173 # We filter out any unknown field
2174 ( @arg ) = grep( !$self->_is_a( $_ => 'DB::Object::Fields::Unknown' ), $_[0]->value );
2175 }
2176 else
2177 {
2178 @arg = @_;
2179 }
2180 $data = \@arg if( @arg );
2181 my $str = '';
2182 my @binded = ();
2183 my @types = ();
2184 my $clause;
2185 # A simple scalar
2186 if( ref( $data ) eq 'SCALAR' )
2187 {
2188 $str = $$data;
2189 }
2190 elsif( ref( $data ) )
2191 {
2192 my @list = ();
2193 my( $field, $value );
2194 while( @arg )
2195 {
2196 if( $self->_is_object( $arg[0] ) && $arg[0]->isa( 'DB::Object::Operator' ) )
2197 {
2198 my $op_object = shift( @arg );
2199 $clause = $process_where_condition->( $op_object );
2200 push( @list, $clause );
2201 next;
2202 }
2203 # This is an already formulated clause
2204 elsif( $self->_is_object( $arg[0] ) && $arg[0]->isa( 'DB::Object::Query::Clause' ) )
2205 {
2206 push( @list, shift( @arg ) );
2207 next;
2208 }
2209 # An expression
2210 elsif( $self->_is_a( $arg[0] => 'DB::Object::Expression' ) )
2211 {
2212 push( @list, shift( @arg ) );
2213 next;
2214 }
2215 elsif( $self->_is_object( $arg[0] ) && $arg[0]->isa( 'DB::Object::Fields::Overloaded' ) )
2216 {
2217 my $f = shift( @arg );
2218 my $cl = $self->new_clause(
2219 value => $f,
2220 type => 'where',
2221 );
2222 # $cl->bind->types->push( '' ) if( $f->binded );
2223 if( $f->placeholder )
2224 {
2225 my $const = $f->field->datatype->constant;
2226 my $offset = $f->index;
2227 # $cl->push({
2228 # field => $f->field,
2229 # # Use the offset expressly provided (e.g. $1 (PostgreSQL) or ?1 (SQLite), or the last position in the array
2230 # ( defined( $offset ) ? ( index => $offset ) : () ),
2231 # ( $const ? ( type => $const ) : () ),
2232 # }) || return( $self->pass_error( $cl->error ) );
2233 # Even better than instantiating a new DB::Object::Element object, we just use as-is the DB::Object::Fields::Overloaded object, which inherits from DB::Object::Element :)
2234 $cl->push( $f );
2235  
2236 # if( $const )
2237 # {
2238 # $cl->bind->types->push( $const );
2239 # }
2240 # else
2241 # {
2242 # $cl->bind->types->push( '' );
2243 # }
2244 }
2245 push( @list, $cl );
2246  
2247 # If this field value assignment is followed (as a pair) by just a regular field, this is likely a typo.
2248 # Catching some typical typo errors for the benefit of the coder (from experience)
2249 if( scalar( @arg ) &&
2250 $self->_is_a( $arg[0], 'DB::Object::Fields::Field' ) )
2251 {
2252 warn( "Warning only: found a (proper) field value assignment ($f) followed by a field object '$arg[0]' (never mind the surrounding quotes) (", overload::StrVal( $arg[0] ), "). Did you forget to assign a value such as \$tbl->fo->$arg[0] == 'something' ?" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2253 }
2254 next;
2255 }
2256 # Ignore it
2257 elsif( $self->_is_a( $arg[0] => 'DB::Object::Fields::Unknown' ) )
2258 {
2259 # warn( "Found an unknown field object DB::Object::Fields::Unknown '", $arg[0]->field, "' of table '", $arg[0]->table, "' in WHERE or HAVING clause: ", $arg[0]->error ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2260 # shift( @arg );
2261 # next;
2262 return( $self->error( "Found an unknown field object DB::Object::Fields::Unknown '", $arg[0]->field, "' of table '", $arg[0]->table, "' in WHERE or HAVING clause: ", $arg[0]->error ) );
2263 }
2264 # Case where there is a litteral query component, e.g. "LENGTH(lang) = 2" and the number of arguments is odd which means there is no second argument such as: ->where( "LENGTH(lang) = 2", $tbl->fo->user_id => "something );
2265 elsif( ( scalar( @arg ) % 2 ) && !ref( $arg[0] ) )
2266 {
2267 push( @list, $self->new_clause( value => shift( @arg ), type => 'where' ) );
2268 next;
2269 }
2270 elsif( ( scalar( @arg ) % 2 ) && ref( $arg[0] ) eq 'SCALAR' )
2271 {
2272 my $scalar = shift( @arg );
2273 push( @list, $self->new_clause( value => $$scalar, type => 'where' ) );
2274 next;
2275 }
2276 # Catching some typical typo errors for the benefit of the coder (from experience)
2277 # The coder provided a field object without associated value and there are no other argument passed to the where clause. He/she probably forget the assignment like $tbl->fo->field == 'something'
2278 elsif( $self->_is_a( $arg[0], 'DB::Object::Fields::Field' ) && scalar( @arg ) == 1 )
2279 {
2280 warn( "Warning only: found a field object '$arg[0]' (never mind the surrounding quotes) (", overload::StrVal( $arg[0] ), ") followed by no other argument. Did you forget to assign a value such as \$tbl->fo->$arg[0] == 'something' ?" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2281 }
2282  
2283 my( $field, $value ) = splice( @arg, 0, 2 );
2284 # Catching some typical typo errors for the benefit of the coder (from experience)
2285 if( $self->_is_a( $field, 'DB::Object::Fields::Field' ) &&
2286 $self->_is_a( $value, 'DB::Object::Fields::Overloaded' ) )
2287 {
2288 warn( "Warning only: found a field object '$field' (never mind the surrounding quotes) (", overload::StrVal( $field ), ") followed by an another (proper) field value assignment ($value). Did you forget to assign a value such as \$tbl->fo->$field == 'something' ?" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
2289 }
2290  
2291 unless( $self->_is_a( $field => 'DB::Object::Fields::Field' ) )
2292 {
2293 $field =~ s/\b(?<![\.\"])($fields)\b/$prefix.$1/gs if( $prefix );
2294 }
2295 my $i_am_negative = 0;
2296 if( $self->_is_a( $value, 'DB::Object::NOT' ) )
2297 {
2298 ( $value ) = $value->value;
2299 $value = $self->database_object->NULL if( !defined( $value ) );
2300 # https://www.postgresql.org/docs/8.3/functions-comparison.html
2301 if( lc( $value ) eq 'null' )
2302 {
2303 # If e do not first copy the value to a separate variable, we would end up with a circular reference (type REF)
2304 push( @list, $self->new_clause({
2305 value => "$field IS NOT NULL",
2306 type => 'where',
2307 })
2308 );
2309 next;
2310 }
2311 $i_am_negative++;
2312 }
2313 # When value is undef() or explicitly set to NULL, we need to write this as IS NULL to be sql compliant
2314 elsif( !defined( $value ) || lc( $value ) eq 'null' )
2315 {
2316 push( @list, $self->new_clause({
2317 value => "$field IS NULL",
2318 type => 'where',
2319 })
2320 );
2321 next;
2322 }
2323  
2324 my $f;
2325 if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) )
2326 {
2327 $f = '%s';
2328 }
2329 else
2330 {
2331 $f = $prefix ? "$prefix.$field" : $field;
2332 }
2333  
2334 if( ref( $value ) eq 'SCALAR' )
2335 {
2336 push( @list, $self->new_clause({
2337 value => $i_am_negative ? "$field != $$value" : "$field = $$value",
2338 type => 'where'
2339 })
2340 );
2341 }
2342 elsif( ref( $value ) eq 'HASH' )
2343 {
2344 foreach my $json_key ( keys( %$value ) )
2345 {
2346 my $json_value = $value->{ $json_key };
2347 # Assuming default "=" operator for now
2348 my $clause = $self->new_clause(
2349 value => "${field}->>'${json_key}' = '${json_value}'",
2350 generic => "${field}->>'${json_key}' = ?",
2351 type => 'where',
2352 );
2353 # Bind the value if it is not a DB::Object reference
2354 # if( !$self->_is_object( $json_value ) )
2355 # {
2356 # $clause->push({ value => $json_value });
2357 # }
2358 $clause->push({ value => $json_value });
2359 push( @list, $clause );
2360 }
2361 }
2362 # If this is a sub-select - i.e.
2363 # SELECT article, dealer, price
2364 # FROM shop
2365 # WHERE price=(SELECT MAX(price) FROM shop)
2366 # By default we get the value and use it in our clause, but sub classes like DB::Object::Postgres::Query would use the statement as is to form a native sub-query
2367 elsif( ref( $value ) eq "${base_class}::Statement" )
2368 {
2369 my $res = $value->fetchrow();
2370 my $cl = $self->new_clause({
2371 value => $i_am_negative ? "$f != '$res'" : "$f = '$res'",
2372 generic => $i_am_negative ? "$f != ?" : "$f = ?",
2373 type => 'where',
2374 });
2375 # $cl->bind->values( $res );
2376 # $cl->bind->types( '' );
2377 # $cl->fields( $field ) if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) );
2378 $cl->push( $value->query_object->elements );
2379 push( @list, $cl );
2380 }
2381 elsif( ref( $value ) eq 'Regexp' )
2382 {
2383 # (?^:^want-(.*?)) => ^want-(.*?)
2384 if( $value =~ s/^\(\?\^\:// )
2385 {
2386 $value =~ s/\)$//;
2387 }
2388 my $cl;
2389 if( $self->database_object->driver eq 'Pg' )
2390 {
2391 $cl = $self->new_clause({
2392 value => $i_am_negative ? "$f !~ '$value'" : "$f ~ '$value'",
2393 generic => $i_am_negative ? "$f !~ ?" : "$f ~ ?",
2394 type => 'where',
2395 });
2396 }
2397 elsif( $self->database_object->driver eq 'SQLite' ||
2398 $self->database_object->driver eq 'mysql' )
2399 {
2400 $cl = $self->new_clause({
2401 value => $i_am_negative ? "$f NOT REGEXP('$value')" : "$f REGEXP('$value')",
2402 generic => $i_am_negative ? "$f NOT REGEXP(?)" : "$f REGEXP(?)",
2403 type => 'where',
2404 });
2405 }
2406 # $cl->bind->values( $value );
2407 # $cl->bind->types( '' );
2408 $cl->push({
2409 ( $self->_is_a( $field => 'DB::Object::Fields::Field' ) ? ( field => $field ) : () ),
2410 value => $value,
2411 });
2412 # $cl->fields( $field ) if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) );
2413 push( @list, $cl );
2414 }
2415 elsif( $value =~ /($placeholder_re)/ )
2416 {
2417 my $plh = $1;
2418 my $cl = $self->new_clause(
2419 value => $i_am_negative ? "$f != $value" : "$f = $value",
2420 type => 'where',
2421 );
2422 my $el = $self->new_element(
2423 field => $field,
2424 placeholder => $plh,
2425 format => $value,
2426 );
2427 my $const;
2428 if( lc( $fields_type->{ $field } // '' ) eq 'bytea' &&
2429 ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
2430 {
2431 $el->type( $const );
2432 }
2433 $cl->push( $el );
2434 push( @list, $cl );
2435 }
2436 elsif( $value =~ /[\s\(\)\.\'\"]+(?:$fields)[\s\(\)\.\'\"]+/ ||
2437 $value =~ /\w\([^\)]*\)/ )
2438 {
2439 # Nothing fancy, as is. Even with binding option on, it will still return the clause without placeholder, because we don't know what $value is
2440 my $cl = $self->new_clause(
2441 value => $i_am_negative ? "$f != $value" : "$f = $value",
2442 type => 'where',
2443 );
2444 # $cl->bind->types( '' ) if( $value =~ /^$placeholder_re$/ );
2445 # $cl->fields( $field ) if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) );
2446 if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) )
2447 {
2448 my $el = $self->new_element(
2449 field => $field,
2450 );
2451 $cl->push( $el );
2452 }
2453 push( @list, $cl );
2454 }
2455 else
2456 {
2457 my( $cl, $const, $el );
2458 if( lc( $fields_type->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
2459 {
2460 $cl = $self->new_clause(
2461 value => "$f" . ( $i_am_negative ? '!=' : '=' ) . $dbo->quote( $value, $const ),
2462 type => 'where',
2463 );
2464 $el = $self->new_element;
2465 }
2466 else
2467 {
2468 $cl = $self->new_clause(
2469 value => "$f" . ( $i_am_negative ? '!=' : '=' ) . $dbo->quote( $value ),
2470 generic => $i_am_negative ? "$f != ?" : "$f = ?",
2471 type => 'where',
2472 );
2473 # $cl->bind->values( $value );
2474 $cl->push({
2475 value => $value,
2476 });
2477 $el = $self->new_element( value => $value );
2478 }
2479  
2480 $el->field( $field ) if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) );
2481 if( lc( $fields_type->{ $field } ) eq 'bytea' &&
2482 ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
2483 {
2484 $el->type( $const );
2485 }
2486 # else
2487 # {
2488 # $cl->bind->types( '' ) if( $value =~ /^$placeholder_re$/ );
2489 # }
2490 $cl->push( $el ) if( defined( $el ) );
2491 CORE::push( @list, $cl );
2492 }
2493 }
2494 # End while @arg loop
2495 if( scalar( @list ) )
2496 {
2497 $clause = $self->new_clause->merge( $dbo->$agg_op( @list ) );
2498 }
2499 }
2500 elsif( $data )
2501 {
2502 # $self->_value2bind( \$data, \@binded ) if( $bind );
2503 # $str = $data;
2504 # @types = ( '' ) x scalar( @binded );
2505 # $clause = $self->new_clause({
2506 # value => $str,
2507 # bind =>
2508 # {
2509 # values => \@binded,
2510 # types => \@types,
2511 # }
2512 # });
2513 my $elems = $self->_value2bind( \$data );
2514 $clause = $self->new_clause(
2515 value => $data,
2516 type => 'where',
2517 );
2518 $clause->push( $elems ) if( $elems->elements->length );
2519 }
2520 return( $clause );
2521 };
2522 $where = $self->{ $prop } = $process_where_condition->( @params ) ||
2523 return( $self->pass_error );
2524 return( $where );
2525 }
2526 else
2527 {
2528 $where = $self->{ $prop };
2529 }
2530  
2531 if( !$where && want( 'OBJECT' ) )
2532 {
2533 return( $self->new_null( type => 'object' ) );
2534 }
2535 return( $where );
2536 }
2537  
2538 # NOTE: For CBOR and Sereal
2539 sub FREEZE
2540 {
2541 my $self = CORE::shift( @_ );
2542 my $serialiser = CORE::shift( @_ ) // '';
2543 my $class = CORE::ref( $self );
2544 my $hash = {};
2545 my @keys = grep{ !/^binded_/ } @{$self->{query_reset_core_keys}};
2546 push( @keys, qw( elements table_object enhance ) );
2547 foreach my $prop ( @keys )
2548 {
2549 if( CORE::exists( $self->{ $prop } ) &&
2550 defined( $self->{ $prop } ) &&
2551 # Because we cannot reliably freeze code reference, and we do not usually need to.
2552 CORE::ref( $self->{ $prop } ) ne 'CODE' )
2553 {
2554 $hash->{ $prop } = $self->{ $prop };
2555 }
2556 }
2557  
2558 # Return an array reference rather than a list so this works with Sereal and CBOR
2559 # Before Sereal version 4.023, Sereal did not support multiple values returned
2560 if( $serialiser eq 'Sereal' )
2561 {
2562 require Sereal::Encoder;
2563 require version;
2564
2565 if( version->parse( Sereal::Encoder->VERSION ) < version->parse( '4.023' ) )
2566 {
2567 CORE::return( [$class, $hash] );
2568 }
2569 }
2570 # But Storable want a list with the first element being the serialised element
2571 CORE::return( $class, $hash );
2572 }
2573  
2574 sub STORABLE_freeze { return( shift->FREEZE( @_ ) ); }
2575  
2576 sub STORABLE_thaw { return( shift->THAW( @_ ) ); }
2577  
2578 sub STORABLE_thaw_post_processing
2579 {
2580 my $obj = shift( @_ );
2581 my @keys = %$obj;
2582 my $class = ref( $obj );
2583 my $hash = {};
2584 @$hash{ @keys } = @$obj{ @keys };
2585 my $self = bless( $hash => $class );
2586 return( $self );
2587 }
2588  
2589 # NOTE: CBOR will call the THAW method with the stored classname as first argument, the constant string CBOR as second argument, and all values returned by FREEZE as remaining arguments.
2590 # NOTE: Storable calls it with a blessed object it created followed with $cloning and any other arguments initially provided by STORABLE_freeze
2591 sub THAW
2592 {
2593 # STORABLE_thaw would issue $cloning as the 2nd argument, while CBOR would issue
2594 # 'CBOR' as the second value.
2595 my( $self, undef, @args ) = @_;
2596 my $ref = ( CORE::scalar( @args ) == 1 && CORE::ref( $args[0] ) eq 'ARRAY' ) ? CORE::shift( @args ) : \@args;
2597 my $class = ( CORE::defined( $ref ) && CORE::ref( $ref ) eq 'ARRAY' && CORE::scalar( @$ref ) > 1 ) ? CORE::shift( @$ref ) : ( CORE::ref( $self ) || $self );
2598 my $hash = CORE::ref( $ref ) eq 'ARRAY' ? CORE::shift( @$ref ) : {};
2599 # Since this class is inherited, we also need to load from which we depend, if necessary.
2600 if( $class ne 'DB::Object::Query' )
2601 {
2602 require DB::Object::Query;
2603  
2604 # If inheritance is still missing (or incomplete) for any reason, repair it explicitly.
2605 no strict 'refs';
2606  
2607 my $stash = \%{"${class}\::"};
2608 my $isa_ref;
2609 # We check if the 'ISA' symbol exists in the stash and its ARRAY slot is defined
2610 if( exists( $stash->{ISA} ) &&
2611 defined( *{"${class}\::ISA"}{ARRAY} ) )
2612 {
2613 $isa_ref = *{"${class}\::ISA"}{ARRAY};
2614 }
2615 else
2616 {
2617 # # Force creation of @ISA array slot
2618 # @{"${class}::ISA"} = ();
2619 # $isa_ref = *{"${class}::ISA"}{ARRAY};
2620 # But I want it to die, so this can be dealt with, and not swept under the rug.
2621 die( "Unable to find the \@ISA value in $class. The package contains the following stashes:\n", $self->Module::Generic::dump( $stash ) );
2622 }
2623 my $has_qo = 0;
2624  
2625 foreach my $p ( @$isa_ref )
2626 {
2627 $has_qo = 1 if( CORE::defined( $p ) && $p eq 'DB::Object::Query' );
2628 }
2629  
2630 if( !$has_qo )
2631 {
2632 # Same as what we can find in modules DB::Object::(Postgres|SQLite|Mysql)::Query
2633 @$isa_ref = ( 'DB::Object::Query' );
2634 }
2635 }
2636 my $new;
2637 # Storable pattern requires to modify the object it created rather than returning a new one
2638 if( CORE::ref( $self ) )
2639 {
2640 foreach( CORE::keys( %$hash ) )
2641 {
2642 # No, this was a bad idea, because the instance property, such as 'where' bears the same name as the method
2643 # So, we would be calling the method 'where', but there is no table object or database object...
2644 # if( my $ref = $self->can( $_ ) )
2645 # {
2646 # $ref->( $self, CORE::delete( $hash->{ $_ } ) );
2647 # }
2648 $self->{ $_ } = CORE::delete( $hash->{ $_ } );
2649 }
2650 $new = CORE::bless( $self => $class );
2651 }
2652 else
2653 {
2654 $new = CORE::bless( $hash => $class );
2655 }
2656 unless( $new->{elements} )
2657 {
2658 $new->{elements} = $new->new_elements;
2659 }
2660 CORE::return( $new );
2661 }
2662  
2663 1;
2664 # NOTE: POD
2665 __END__