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

filter: Statementstmt 0.0% 0 / 1188 Branchbran 0.0% 0 / 706 Conditioncond 0.0% 0 / 517 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 95 Podpod 0.0% 0 / 80 totaltotal 0.0% 0 / 2586 CC 354 SCAR 67.4
CC
354
Cov
0%
_where_having
3540.0
getdefault
1332.0
select
930.0
CRAP 846.6
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Query.pm
4 ## Version v0.10.0
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/03/27
9 ## All rights reserved
10 ##
11 ##
12 ## This program is free software; you can redistribute it and/or modify it
13 ## under the same terms as Perl itself.
14 ##----------------------------------------------------------------------------
15 package DB::Object::Query;
16 BEGIN
17 {
18 use strict;
19 use warnings;
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.0';
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 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  
267 # Query object is now in an error state and must not be re-used.
268 $self->{dirty} = 1 if( ref( $self ) );
269  
270 return( $self->SUPER::error( @_ ) );
271 }
272  
273 # Used in conjonction with constant(), allows internally to know if the query has reached the end of the chain
274 # Such as $tbl->select->join( $tbl_object, $conditions )->join( $other_tbl_object, $other_conditions );
275 # final() enables to know the query reached the end, so that when constant is used, all the processing can be skipped
276 sub final { return( shift->_set_get_scalar( 'final', @_ ) ); }
277  
278 sub format_from_epoch
279 {
280 warn( "This method \"format_from_epoch\" was not superseded.\n" );
281 }
282  
283 sub format_to_epoch
284 {
285 warn( "This method \"format_to_epoch\" was not superseded.\n" );
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 = $tbl_o->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  
858 $self->{_args} = $arg;
859 $self->{_default} = $default;
860 $self->{_fields} = $fields;
861 $self->{_extra} = \@extra;
862 $self->{_structure} = $structure;
863 $self->{_from_unix} = \%from_unixtime;
864 $self->{_to_unix} = \%to_unixtime;
865 $self->{query_type} = $query_type;
866 $self->{bind} = $tbl_o->database_object->use_bind;
867 return( $self );
868 }
869  
870 sub group { return( shift->_group_order( 'group', 'group_by', @_ ) ); }
871  
872 sub having { return( shift->error( "Having clause is not supported by this driver." ) ); }
873  
874 # $tbl->insert( field1 => $val1, field2 => $val2 );
875 # or
876 # $tbl->insert([ field1 => $val1, field2 => $val2 ]);
877 # or
878 # $tbl->insert({ field1 => $val1, field2 => $val2 });
879 # or
880 # my $select_statement_object = $tbl2->select || die( $tbl2->error );
881 # $tbl->insert( $select_statement_object );
882 # or
883 # my $select_statement_object = $tbl2->select || die( $tbl2->error );
884 # $tbl->insert( field1 => $val1, field2 => $val2, $select_statement_object );
885 # or
886 # my $select_statement_object = $tbl2->select || die( $tbl2->error );
887 # $tbl->insert([ field1 => $val1, field2 => $val2, $select_statement_object ]);
888 sub insert
889 {
890 my $self = shift( @_ );
891 # Could be an array of fields, or a SQL statement object.
892 my $data = shift( @_ ) if( @_ == 1 && ref( $_[ 0 ] ) );
893 my @arg = @_;
894 my $constant = $self->constant;
895 if( scalar( keys( %$constant ) ) )
896 {
897 return( $constant->{sth} ) if( $constant->{sth} && $self->_is_object( $constant->{sth} ) && $constant->{sth}->isa( 'DB::Object::Statement' ) );
898 }
899 my %arg = ();
900 my $select = '';
901 my $base_class = $self->base_class;
902 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
903 my $table = $tbl_o->name ||
904 return( $self->error( "No table was provided to insert data." ) );
905 # We do not decide of the value of AUTO_INCREMENT fields, so we do not use them in
906 # our INSERT statement.
907 my $fields_ref = $tbl_o->fields || return( $self->pass_error( $tbl_o->error ) );
908 my @avoid = ();
909 my( $fields, $values, $elems );
910 my $el = $self->elements;
911  
912 if( !@arg && $data && $self->_is_hash( $data => 'strict' ) )
913 {
914 @arg = %$data;
915 }
916 # User passed an array reference
917 elsif( !@arg && ref( $data ) && $self->_is_array( $data ) )
918 {
919 @arg = @$data;
920 if( scalar( @arg ) && $self->_is_a( $arg[-1] => "${base_class}::Statement" ) )
921 {
922 my $sth = pop( @arg );
923 $select = $sth->as_string;
924 $el->merge( $sth->query_object->elements );
925 }
926 }
927 # insert into (field1, field2, field3) select field1, field2, field3 from some_table where some_id=12
928 elsif( $data && ref( $data ) eq "${base_class}::Statement" )
929 {
930 $select = $data->as_string;
931 $el->merge( $data->query_object->elements );
932 }
933 elsif( scalar( @arg ) && $self->_is_a( $arg[-1] => "${base_class}::Statement" ) )
934 {
935 my $sth = pop( @arg );
936 $select = $sth->as_string;
937 $el->merge( $sth->query_object->elements );
938 }
939 my @query = ();
940 if( $select )
941 {
942 my $sql;
943 if( scalar( @arg ) )
944 {
945 for( my $i = 0; $i < scalar( @arg ); $i++ )
946 {
947 if( $self->_is_a( $arg[$i] => 'DB::Object::Fields::Unknown' ) )
948 {
949 warn( "Unknown field object '", $arg[$i]->field, "' provided for INSERT into table '", $arg[$i], "'" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
950 splice( @arg, $i, 1 );
951 }
952 }
953 $sql = "INSERT INTO $table (" . join( ', ', @arg ) . ") $select";
954 }
955 else
956 {
957 $sql = "INSERT INTO $table $select";
958 }
959 @query = ( $sql );
960 }
961 else
962 {
963 %arg = @arg if( @arg );
964 foreach my $field ( keys( %$fields_ref ) )
965 {
966 my $fo = $fields_ref->{ $field };
967 # push( @avoid, $field ) if( $fields_ref->{ $field } =~ /\b(AUTO_INCREMENT|SERIAL|nextval)\b/i && !$arg{ $field } );
968 if( defined( $fo->default ) &&
969 $fo->default =~ /\b(AUTO_INCREMENT|SERIAL|nextval)\b/i &&
970 !$arg{ $field } )
971 {
972 push( @avoid, $field );
973 }
974 # It is useless to insert a blank data in a field whose default value is NULL.
975 # Especially since a test on a NULL field may be made specifically.
976 if( scalar( @arg ) &&
977 !exists( $arg{ $field } ) &&
978 $fo->is_nullable )
979 {
980 push( @avoid, $field );
981 }
982 }
983 $self->getdefault(
984 table => $table,
985 arg => \@arg,
986 avoid => \@avoid,
987 ) || return( $self->pass_error );
988 $elems = $self->format_statement || return( $self->pass_error );
989 $fields = $elems->fields->join( ', ' );
990 $values = $elems->formats->join( ', ' );
991 $el->merge( $elems );
992 @query = ( "INSERT INTO $table ($fields) VALUES($values)" );
993 }
994  
995 if( $data && $self->_is_hash( $data => 'strict' ) && $el->types->length )
996 {
997 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...\n" );
998 }
999 my $clauses = $self->_query_components( 'insert' ) || return( $self->pass_error );
1000 push( @query, @$clauses ) if( scalar( @$clauses ) );
1001 my $query = $self->{query} = CORE::join( ' ', @query );
1002 # Everything meaningfull lies within the object
1003 # If no bind should be done _save_bind does nothing
1004 $self->_save_bind();
1005 # Query string should lie within the object
1006 # _cache_this sends back an object no matter what or unde() if an error occurs
1007 my $sth = $tbl_o->_cache_this( $self );
1008 # STOP! No need to go further
1009 if( !defined( $sth ) )
1010 {
1011 return( $self->error( "Error '", $tbl_o->error, "' while preparing query to insert data into table '$table':\n$query" ) );
1012 }
1013 # Called in void context
1014 if( !defined( wantarray() ) )
1015 {
1016 $sth->execute() ||
1017 return( $self->error( "Error while executing query to insert data to table '$table':\n$query" ) );
1018 }
1019 return( $sth );
1020 }
1021  
1022 sub is_upsert { return( shift->_set_get_boolean( 'is_upsert', @_ ) ); }
1023  
1024 sub join_fields { return( shift->_set_get_scalar( 'join_fields', @_ ) ); }
1025  
1026 sub join_tables { return( shift->_set_get_object_array_object( 'join_tables', 'DB::Object::Tables', @_ ) ); }
1027  
1028 sub left_join { return( shift->_set_get_hash( 'left_join', @_ ) ); }
1029  
1030 sub limit
1031 {
1032 my $self = shift( @_ );
1033 my $limit = $self->{limit};
1034 if( @_ )
1035 {
1036 # Returns a DB::Object::Query::Clause
1037 $limit = $self->_process_limit( @_ ) ||
1038 return( $self->pass_error );
1039 if( CORE::length( $limit->metadata->limit // '' ) )
1040 {
1041 $limit->generic( CORE::length( $limit->metadata->offset // '' ) ? 'LIMIT ?, ?' : 'LIMIT ?' );
1042 # %s works for integer, and also for numbered placeholders like $1 or ?1, or regular placeholder like ?
1043 $limit->value(
1044 CORE::length( $limit->metadata->offset // '' )
1045 ? sprintf( "LIMIT %s, %s", $limit->metadata->offset, $limit->metadata->limit )
1046 : sprintf( "LIMIT %s", $limit->metadata->limit )
1047 );
1048 }
1049 }
1050  
1051 if( !$limit && want( 'OBJECT' ) )
1052 {
1053 return( $self->new_null( type => 'object' ) );
1054 }
1055 return( $limit );
1056 }
1057  
1058 sub local
1059 {
1060 my $self = shift( @_ );
1061 $self->{local} ||= {};
1062 my $local = $self->{local};
1063 if( @_ )
1064 {
1065 my $data = $self->_get_args_as_hash( @_ );
1066 my $str = '';
1067 if( scalar( keys( %$data ) ) )
1068 {
1069 my @keys = keys( %$data );
1070 @$local{ @keys } = @$data{ @keys };
1071 }
1072 }
1073 return( wantarray() ? () : undef() ) if( !$local || !%$local );
1074 return( %$local ) if( wantarray() );
1075 my $str = join( ', ', map{ "\@${_} = '" . $local->{ $_ } . "'" } keys( %$local ) );
1076 # return( "SET $str" );
1077 return( $str );
1078 }
1079  
1080 sub new_clause
1081 {
1082 my $self = shift( @_ );
1083 my $opts = $self->_get_args_as_hash( @_ );
1084 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1085 $opts->{query_object} = $self;
1086 my $o = DB::Object::Query::Clause->new( %$opts ) ||
1087 return( $self->error( "Unable to create a DB::Object::Query::Clause object: ", DB::Object::Query::Clause->error ) );
1088 # Weaken the back-reference to the query object to prevent circular reference memory leaks.
1089 weaken( $o->{query_object} ) if( $o->{query_object} );
1090 return( $o );
1091 }
1092  
1093 sub new_element
1094 {
1095 my $self = shift( @_ );
1096 my $opts = $self->_get_args_as_hash( @_ );
1097 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1098 $opts->{query_object} = $self;
1099 my $elem = DB::Object::Query::Element->new( %$opts ) ||
1100 return( $self->pass_error( DB::Object::Query::Element->error ) );
1101 # Weaken the back-reference to the query object to prevent circular reference memory leaks.
1102 weaken( $elem->{query_object} ) if( $elem->{query_object} );
1103 return( $elem );
1104 }
1105  
1106 sub new_elements
1107 {
1108 my $self = shift( @_ );
1109 my $opts = $self->_get_args_as_hash( @_ );
1110 $opts->{debug} = $self->debug if( !exists( $opts->{debug} ) );
1111 $opts->{query_object} = $self;
1112 my $e = DB::Object::Query::Elements->new( %$opts ) ||
1113 return( $self->pass_error( DB::Object::Query::Elements->error ) );
1114 # Weaken the back-reference to the query object to prevent circular reference memory leaks.
1115 weaken( $e->{query_object} ) if( $e->{query_object} );
1116 return( $e );
1117 }
1118  
1119 sub order { return( shift->_group_order( 'order', 'order_by', @_ ) ); }
1120  
1121 sub pass_error
1122 {
1123 my $self = shift( @_ );
1124  
1125 # Propagating an error also taints this query object.
1126 $self->{dirty} = 1 if( ref( $self ) );
1127  
1128 return( $self->SUPER::pass_error( @_ ) );
1129 }
1130  
1131 sub prepare_options { return( shift->_set_get_hash_as_mix_object( 'prepare_options', @_ ) ); }
1132  
1133 sub query { return( shift->_set_get_scalar( 'query', @_ ) ); }
1134  
1135 sub query_reset { return( shift->_set_get_boolean( 'query_reset', @_ ) ); }
1136  
1137 sub query_reset_core_keys { return( shift->_set_get_array_as_object( 'query_reset_core_keys', @_ ) ); }
1138  
1139 sub query_reset_keys { return( shift->_set_get_array_as_object( 'query_reset_keys', @_ ) ); }
1140  
1141 sub query_type { return( shift->_set_get_scalar( 'query_type', @_ ) ); }
1142  
1143 sub query_values { return( shift->_set_get_scalar_as_object( 'query_values', @_ ) ); }
1144  
1145 sub replace { return( shift->error( "The replace sql query is not supported by this driver." ) ); }
1146  
1147 sub reset
1148 {
1149 my $self = shift( @_ );
1150 if( !$self->{query_reset} )
1151 {
1152 my $core_keys = $self->query_reset_core_keys;
1153 my $keys = $self->query_reset_keys;
1154 # Make sure the driver's list of keys for query reset is complete by merging this base class keys with the diver's one
1155 unless( $core_keys == $keys )
1156 {
1157 my $new_keys = $keys->merge( $core_keys )->unique->sort;
1158 $keys = $self->query_reset_keys( $new_keys );
1159 }
1160 CORE::delete( @$self{ @$keys } );
1161 # elements is not in query_reset_core_keys because CORE::delete would leave it undef
1162 # and there is no re-init pass after reset(). We clear it explicitly here instead,
1163 # so that _save_bind() on each fresh select() starts from an empty element stack.
1164 $self->{elements} = $self->new_elements;
1165 $self->{query_reset}++;
1166 $self->{enhance} = 1;
1167 }
1168 return( $self );
1169 }
1170  
1171 sub reset_bind
1172 {
1173 my $self = shift( @_ );
1174 my @f = qw( binded binded_group binded_limit binded_order binded_types binded_where );
1175 foreach my $field ( @f )
1176 {
1177 $self->{ $field } = [];
1178 }
1179 return( $self );
1180 }
1181  
1182 sub returning { return( shift->error( "Returning clause is not supported by this driver" ) ); }
1183  
1184 sub reverse
1185 {
1186 my $self = shift( @_ );
1187 if( @_ )
1188 {
1189 $self->{reverse}++;
1190 }
1191 return( $self->{reverse} );
1192 }
1193  
1194 sub select
1195 {
1196 my $self = shift( @_ );
1197 my $constant = $self->constant;
1198 if( scalar( keys( %$constant ) ) )
1199 {
1200 return( $constant->{sth} ) if( $constant->{sth} && $self->_is_object( $constant->{sth} ) && $constant->{sth}->isa( 'DB::Object::Statement' ) );
1201 }
1202 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
1203 my $prefix = $tbl_o->query_object->table_alias ? $tbl_o->query_object->table_alias : $tbl_o->prefix;
1204 my $table = $tbl_o->qualified_name ||
1205 return( $self->error( "No table name provided to perform select statement." ) );
1206 my $bind = $tbl_o->use_bind;
1207 my $cache = $tbl_o->use_cache;
1208 # my $multi_db = $tbl_o->param( 'multi_db' );
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' ?\n" );
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' ?\n" );
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' ?\n" );
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 $cl->push( $el );
2428 push( @list, $cl );
2429 }
2430 elsif( $value =~ /[\s\(\)\.\'\"]+(?:$fields)[\s\(\)\.\'\"]+/ ||
2431 $value =~ /\w\([^\)]*\)/ )
2432 {
2433 # 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
2434 my $cl = $self->new_clause(
2435 value => $i_am_negative ? "$f != $value" : "$f = $value",
2436 type => 'where',
2437 );
2438 # $cl->bind->types( '' ) if( $value =~ /^$placeholder_re$/ );
2439 # $cl->fields( $field ) if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) );
2440 if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) )
2441 {
2442 my $el = $self->new_element(
2443 field => $field,
2444 );
2445 $cl->push( $el );
2446 }
2447 push( @list, $cl );
2448 }
2449 else
2450 {
2451 my( $cl, $const, $el );
2452 if( lc( $fields_type->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
2453 {
2454 $cl = $self->new_clause(
2455 value => "$f" . ( $i_am_negative ? '!=' : '=' ) . $dbo->quote( $value, $const ),
2456 type => 'where',
2457 );
2458 $el = $self->new_element;
2459 }
2460 else
2461 {
2462 $cl = $self->new_clause(
2463 value => "$f" . ( $i_am_negative ? '!=' : '=' ) . $dbo->quote( $value ),
2464 generic => $i_am_negative ? "$f != ?" : "$f = ?",
2465 type => 'where',
2466 );
2467 # $cl->bind->values( $value );
2468 $cl->push({
2469 value => $value,
2470 });
2471 $el = $self->new_element( value => $value );
2472 }
2473  
2474 $el->field( $field ) if( $self->_is_a( $field => 'DB::Object::Fields::Field' ) );
2475 if( lc( $fields_type->{ $field } ) eq 'bytea' &&
2476 ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
2477 {
2478 $el->type( $const );
2479 }
2480 # else
2481 # {
2482 # $cl->bind->types( '' ) if( $value =~ /^$placeholder_re$/ );
2483 # }
2484 $cl->push( $el ) if( defined( $el ) );
2485 CORE::push( @list, $cl );
2486 }
2487 }
2488 # End while @arg loop
2489 if( scalar( @list ) )
2490 {
2491 $clause = $self->new_clause->merge( $dbo->$agg_op( @list ) );
2492 }
2493 }
2494 elsif( $data )
2495 {
2496 # $self->_value2bind( \$data, \@binded ) if( $bind );
2497 # $str = $data;
2498 # @types = ( '' ) x scalar( @binded );
2499 # $clause = $self->new_clause({
2500 # value => $str,
2501 # bind =>
2502 # {
2503 # values => \@binded,
2504 # types => \@types,
2505 # }
2506 # });
2507 my $elems = $self->_value2bind( \$data );
2508 $clause = $self->new_clause(
2509 value => $data,
2510 type => 'where',
2511 );
2512 $clause->push( $elems ) if( $elems->elements->length );
2513 }
2514 return( $clause );
2515 };
2516 $where = $self->{ $prop } = $process_where_condition->( @params ) ||
2517 return( $self->pass_error );
2518 return( $where );
2519 }
2520 else
2521 {
2522 $where = $self->{ $prop };
2523 }
2524  
2525 if( !$where && want( 'OBJECT' ) )
2526 {
2527 return( $self->new_null( type => 'object' ) );
2528 }
2529 return( $where );
2530 }
2531  
2532 # NOTE: For CBOR and Sereal
2533 sub FREEZE
2534 {
2535 my $self = CORE::shift( @_ );
2536 my $serialiser = CORE::shift( @_ ) // '';
2537 my $class = CORE::ref( $self );
2538 my $hash = {};
2539 my @keys = grep{ !/^binded_/ } @{$self->{query_reset_core_keys}};
2540 push( @keys, qw( elements table_object ) );
2541 foreach my $prop ( @keys )
2542 {
2543 if( CORE::exists( $self->{ $prop } ) &&
2544 defined( $self->{ $prop } ) &&
2545 # Because we cannot reliably freeze code reference, and we do not usually need to.
2546 CORE::ref( $self->{ $prop } ) ne 'CODE' )
2547 {
2548 $hash->{ $prop } = $self->{ $prop };
2549 }
2550 }
2551  
2552 # Return an array reference rather than a list so this works with Sereal and CBOR
2553 # Before Sereal version 4.023, Sereal did not support multiple values returned
2554 if( $serialiser eq 'Sereal' )
2555 {
2556 require Sereal::Encoder;
2557 require version;
2558
2559 if( version->parse( Sereal::Encoder->VERSION ) < version->parse( '4.023' ) )
2560 {
2561 CORE::return( [$class, $hash] );
2562 }
2563 }
2564 # But Storable want a list with the first element being the serialised element
2565 CORE::return( $class, $hash );
2566 }
2567  
2568 sub STORABLE_freeze { return( shift->FREEZE( @_ ) ); }
2569  
2570 sub STORABLE_thaw { return( shift->THAW( @_ ) ); }
2571  
2572 sub STORABLE_thaw_post_processing
2573 {
2574 my $obj = shift( @_ );
2575 my @keys = %$obj;
2576 my $class = ref( $obj );
2577 my $hash = {};
2578 @$hash{ @keys } = @$obj{ @keys };
2579 my $self = bless( $hash => $class );
2580 return( $self );
2581 }
2582  
2583 # 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.
2584 # NOTE: Storable calls it with a blessed object it created followed with $cloning and any other arguments initially provided by STORABLE_freeze
2585 sub THAW
2586 {
2587 # STORABLE_thaw would issue $cloning as the 2nd argument, while CBOR would issue
2588 # 'CBOR' as the second value.
2589 my( $self, undef, @args ) = @_;
2590 my $ref = ( CORE::scalar( @args ) == 1 && CORE::ref( $args[0] ) eq 'ARRAY' ) ? CORE::shift( @args ) : \@args;
2591 my $class = ( CORE::defined( $ref ) && CORE::ref( $ref ) eq 'ARRAY' && CORE::scalar( @$ref ) > 1 ) ? CORE::shift( @$ref ) : ( CORE::ref( $self ) || $self );
2592 my $hash = CORE::ref( $ref ) eq 'ARRAY' ? CORE::shift( @$ref ) : {};
2593 # Since this class is inherited, we also need to load from which we depend, if necessary.
2594 if( $class ne 'DB::Object::Query' )
2595 {
2596 require DB::Object::Query;
2597  
2598 # If inheritance is still missing (or incomplete) for any reason, repair it explicitly.
2599 no strict 'refs';
2600  
2601 my $stash = \%{"${class}\::"};
2602 my $isa_ref;
2603 # We check if the 'ISA' symbol exists in the stash and its ARRAY slot is defined
2604 if( exists( $stash->{ISA} ) &&
2605 defined( *{"${class}\::ISA"}{ARRAY} ) )
2606 {
2607 $isa_ref = *{"${class}\::ISA"}{ARRAY};
2608 }
2609 else
2610 {
2611 # # Force creation of @ISA array slot
2612 # @{"${class}::ISA"} = ();
2613 # $isa_ref = *{"${class}::ISA"}{ARRAY};
2614 # But I want it to die, so this can be dealt with, and not swept under the rug.
2615 die( "Unable to find the \@ISA value in $class. The package contains the following stashes:\n", $self->Module::Generic::dump( $stash ) );
2616 }
2617 my $has_qo = 0;
2618  
2619 foreach my $p ( @$isa_ref )
2620 {
2621 $has_qo = 1 if( CORE::defined( $p ) && $p eq 'DB::Object::Query' );
2622 }
2623  
2624 if( !$has_qo )
2625 {
2626 # Same as what we can find in modules DB::Object::(Postgres|SQLite|Mysql)::Query
2627 @$isa_ref = ( 'DB::Object::Query' );
2628 }
2629 }
2630 my $new;
2631 # Storable pattern requires to modify the object it created rather than returning a new one
2632 if( CORE::ref( $self ) )
2633 {
2634 foreach( CORE::keys( %$hash ) )
2635 {
2636 # No, this was a bad idea, because the instance property, such as 'where' bears the same name as the method
2637 # So, we would be calling the method 'where', but there is no table object or database object...
2638 # if( my $ref = $self->can( $_ ) )
2639 # {
2640 # $ref->( $self, CORE::delete( $hash->{ $_ } ) );
2641 # }
2642 $self->{ $_ } = CORE::delete( $hash->{ $_ } );
2643 }
2644 $new = CORE::bless( $self => $class );
2645 }
2646 else
2647 {
2648 $new = CORE::bless( $hash => $class );
2649 }
2650 unless( $new->{elements} )
2651 {
2652 $new->{elements} = $new->new_elements;
2653 }
2654 CORE::return( $new );
2655 }
2656  
2657 1;
2658 # NOTE: POD
2659 __END__
2660  
2661 =encoding utf-8
2662  
2663 =head1 NAME
2664  
2665 DB::Object::Query - Query Object
2666  
2667 =head1 SYNOPSIS
2668  
2669 my $q = DB::Object::Query->new;
2670  
2671 =head1 VERSION
2672  
2673 v0.10.0
2674  
2675 =head1 DESCRIPTION
2676  
2677 This is the base class for this L<DB::Object> query formatter.
2678  
2679 =head1 METHODS
2680  
2681 =head2 alias
2682  
2683 Sets or gets an hash of column name to alias.
2684  
2685 =head2 as_string
2686  
2687 Returns the formatted query as a string.
2688  
2689 =head2 attach
2690  
2691 $q->attach( $db_object );
2692  
2693 Provided with a L<DB::Object>, or one of its inheriting classes, and this will attach that database object to this query object.
2694  
2695 It returns the current query object upon success, or upon error, it set an error an returns an empty list in list context, or C<undef> in scalar context.
2696  
2697 =head2 avoid
2698  
2699 Takes a list or array reference of column to avoid in the next query. This returns a L<Module::Generic::Array> object.
2700  
2701 =head2 binded
2702  
2703 Takes a list or array reference of values to bind in the next query in L<DB::Object::Statement/execute>. This returns a L<Module::Generic::Array> object.
2704  
2705 =head2 binded_group
2706  
2707 This returns the values to bind for the C<group> clause of the query. This returns a L<Module::Generic::Array> object.
2708  
2709 =head2 binded_limit
2710  
2711 This returns the values to bind for the C<limit> clause of the query. This returns a L<Module::Generic::Array> object.
2712  
2713 =head2 binded_order
2714  
2715 This returns the values to bind for the C<order> clause of the query. This returns a L<Module::Generic::Array> object.
2716  
2717 =head2 binded_types
2718  
2719 Takes a list or array reference of value types to bind in the next query in L<DB::Object::Statement/execute>. This returns a L<Module::Generic::Array> object.
2720  
2721 =head2 binded_types_as_param
2722  
2723 This does nothing and must be implemented by the driver package. So, see L<DB::Object::Mysql::Query/binded_types_as_param>, L<DB::Object::Postgres::Query/binded_types_as_param>, and L<DB::Object::SQLite::Query/binded_types_as_param>
2724  
2725 =head2 binded_values
2726  
2727 Takes a list or array reference of values to bind in the next query in L<DB::Object::Statement/execute>. This returns a L<Module::Generic::Array> object.
2728  
2729 =head2 binded_where
2730  
2731 This returns the values to bind for the C<where> clause of the query. This returns a L<Module::Generic::Array> object.
2732  
2733 =head2 constant
2734  
2735 If any argument is provided, this expects an hash reference of constants to value pairs.
2736  
2737 It returns the currently set constants as a hash reference.
2738  
2739 =head2 database_object
2740  
2741 Returns the current database object, which should be driver specific like L<DB::Object::Postgres>
2742  
2743 =head2 delete
2744  
2745 Takes some optional arguments used to define the C<where> clause, and this will prepare a C<DELETE> query.
2746  
2747 It will refuse to prepare the query if no C<where> clause has been defined, as this would be a very unsafe query. You would need to execute such query yourself using L<DB::Object/do>.
2748  
2749 If this method is called in void, this will execute the query.
2750  
2751 It returns the newly created statement handler as a L<DB::Object::Statement>
2752  
2753 =head2 dirty
2754  
2755 Defines whether this query object is dirty or not, and this means whether it has suffered from an error, and is in a stalled state, thus unusable. This state is checked by L<DB::Object> when setting or reetting the query object for a table object.
2756  
2757 Return the current boolean value.
2758  
2759 =head2 elements
2760  
2761 Sets or gets an L<DB::Object::Query::Elements> object. This object serves to contain all the elements used in creating SQL queries, keeping track of their order, value, dta types, placeholders used, etc.
2762  
2763 =head2 enhance
2764  
2765 Enable or disable enhancement mode.
2766  
2767 =for Pod::Coverage error
2768  
2769 =head2 final
2770  
2771 Enables to know the query reached the end, so that when constant is used, all the processing can be skipped.
2772  
2773 =head2 from_table
2774  
2775 The table used, if any, in a C<FROM> clause.
2776  
2777 =head2 format_statement
2778  
2779 Provided with an hash or hash reference of parameters and this will format the sql statement for queries of types C<select>, C<delete> and C<insert>
2780  
2781 In list context, it returns 2 strings: one comma-separated list of fields and one comma-separated list of values. In scalar context, it only returns a comma-separated string of fields.
2782  
2783 Accepted parameters are:
2784  
2785 =over 4
2786  
2787 =item C<data>
2788  
2789 =item C<order>
2790  
2791 If not provided, this will use the default column order for this table.
2792  
2793 =item C<table>
2794  
2795 The table name to use, or, if not specified, this will be set to a value set with L<DB::Object::Tables/qualified_name>
2796  
2797 =back
2798  
2799 If any values were set by L</from_unixtime> or L</unix_timestamp>, the associated columns will be formatted accordingly in the sql statement.
2800  
2801 It will go through each of the parameter passed to the original C<insert>, C<delete>, or C<select> query and if a column is one set earlier by L</from_unixtime> or L</unix_timestamp>, it will format it.
2802  
2803 If a parameter provided is a L<DB::Object::Statement> it will stringify the query and add it surrounded by parenthesis.
2804  
2805 If a parameter is actually a scalar reference, this means to us to use the underlying string as is.
2806  
2807 If a parameter is C<?>, this will be treated as a placeholder.
2808  
2809 If a parameter is a blob, it will be transformed into a parameter as a placeholder with its value saved to be bound in L<DB::Object::Statement/execute>
2810  
2811 If L<DB::Object/bind> is not enabled, then the value provided with this parameter will be added after being possibly surrounded by quotes using L<DB::Object::Tables/quote>.
2812  
2813 If the column type for this parameter is C<ENUM> and the query is of type C<INSERT> or C<UPDATE>, then the parameter value is surrounded with single quote.
2814  
2815 If L<DB::Object/bind> is enabled, then a placeholder C<?> will be added and the parameter value will be saed to be passed during L<DB::Object::Statement/execute>
2816  
2817 If nothing else matches it will add the value, possible quoted, using L<DB::Object::Tables/quote>, whose implementation can be driver specific.
2818  
2819 If column prefix is required, then the necessary prefix will be prepended to columns.
2820  
2821 In list context, this returns the formatted columns and their values, and in scalar context it will returns only the formatted columns.
2822  
2823 =head2 format_update
2824  
2825 Provided with a list of parameters either as a key-value pairs, as an hash reference or even as an array reference and this will format update query based on the following arguments provided:
2826  
2827 =over 4
2828  
2829 =item C<data>
2830  
2831 An array of key-value pairs to be used in the update query. This array can be provided as the prime argument as a reference to an array, an array, or as the C<data> element of a hash or a reference to a hash provided.
2832  
2833 Why an array if eventually we build a list of key-value pair? Because the order of the fields may be important, and if the key-value pair list is provided, B<format_update> honors the order in which the fields are provided.
2834  
2835 =back
2836  
2837 If no data is provided, this will return an error.
2838  
2839 L</format_update> will then iterate through each field-value pair, and perform some work:
2840  
2841 If the field being reviewed was provided to L</from_unixtime>, then L</format_update> will enclose it in the function suitable for the driver to convert it into a database datetime. For example, for Mysql, this would be:
2842  
2843 FROM_UNIXTIME(field_name)
2844  
2845 If the the given value is a reference to a scalar, it will be used as-is, ie. it will not be enclosed in quotes or anything. This is useful if you want to control which function to use around that field.
2846  
2847 If the value is C<?> it will be used as a placeholder and the value will be saved to be bound later in L<DB::Object::Statement/execute>. Its associated type will be added as blank, so it can be guessed later. However, if the column data type is C<bytea>, the the PostgreSQL data type C<DBD::Pg::PG_BYTEA> will be used when binding the value.
2848  
2849 If the column type is C<jsonb>, and the value is an hash reference, it will be json encoded and used instead.
2850  
2851 If the given value is another field or looks like a function having parenthesis, or if the value is a question mark, the value will be used as-is.
2852  
2853 If L<DB::Object/bind> is off, the value will be escaped and the pair field='value' created.
2854  
2855 If the field is a SET data type and the value is a number, the value will be used as-is without surrounding single quote.
2856  
2857 If L<DB::Object/bind> is enabled, a question mark will be used as the value and the original value will be saved as value to bind upon executing the query.
2858  
2859 Finally, otherwise the value is escaped and surrounded by single quotes.
2860  
2861 L</format_update> returns a regular string representing the comma-separated list of columns with their value assigment that will be used.
2862  
2863 =head2 from_unixtime
2864  
2865 Takes a list or array reference of columns that needs to be treated as unix timestamp and will be converted into a database timestamp.
2866  
2867 It returns that list as a L<Module::Generic::Array>
2868  
2869 =head2 format_from_epoch
2870  
2871 This is the driver specific implementation to convert unix timestamp to the database timestamp.
2872  
2873 This is superseded in driver specific implementation, so see L<DB::Object::Mysql::Query/format_from_epoch>, L<DB::Object::Postgres::Query/format_from_epoch> and L<DB::Object::SQLite:::Query/format_from_epoch>
2874  
2875 =head2 format_to_epoch
2876  
2877 This is the driver specific implementation to convert the database timestamp to unix timestamp.
2878  
2879 This is superseded in driver specific implementation, so see L<DB::Object::Mysql::Query/format_from_epoch>, L<DB::Object::Postgres::Query/format_from_epoch> and L<DB::Object::SQLite:::Query/format_from_epoch>
2880  
2881 =head2 getdefault
2882  
2883 Provided with an hash or hash reference of parameters and this will do some preparation work.
2884  
2885 Possible parameters are:
2886  
2887 =over 4
2888  
2889 =item C<arg>
2890  
2891 An array reference of data which should be a key-value pairs.
2892  
2893 =item C<as>
2894  
2895 An hash reference of column to alias pairs. Alternatively, if this is not provided, the value set with L</alias> will be used.
2896  
2897 =item C<avoid>
2898  
2899 An array reference of column to avoid using. Alternatively, if this is not provided, the value set with L</avoid> will be used.
2900  
2901 =item C<from_unixtime>
2902  
2903 An array reference of columns to be converted from unix timestamp to the database timestamp.
2904  
2905 =item C<query_type>
2906  
2907 The type of query, such as C<delete>, C<insert>, C<replace>, C<select>, C<update>
2908  
2909 =item C<table>
2910  
2911 The table name.
2912  
2913 =item C<time>
2914  
2915 A unix timestamp. Alternatively, C<unixtime> can be used.
2916  
2917 =item C<unix_timestamp>
2918  
2919 An array reference of columns to be converted into unix timestamp.
2920  
2921 =back
2922  
2923 Does some preparation work such as :
2924  
2925 =over 4
2926  
2927 =item 1
2928  
2929 the date/time field to use the FROM_UNIXTIME and UNIX_TIMESTAMP functions
2930  
2931 =item 2
2932  
2933 removing from the query the fields to avoid, ie the ones set with the B<avoid> method.
2934  
2935 =item 3
2936  
2937 set the fields alias based on the information provided with the B<alias> method.
2938  
2939 =item 4
2940  
2941 if a field last_name and first_name exist, it will also create an alias C<name> based on the concatenation of the 2.
2942  
2943 =item 5
2944  
2945 it will set the default values provided. This is used for UPDATE queries.
2946  
2947 =back
2948  
2949 It sets the following properties of the current object:
2950  
2951 =over 4
2952  
2953 =item C<bind>
2954  
2955 A boolean value whether the use of placeholder is enabled.
2956  
2957 =item C<query_type>
2958  
2959 The type of query, such as C<select>, C<insert>, etc...
2960  
2961 =item C<_args>
2962  
2963 The arguments provided as an array reference.
2964  
2965 =item C<_default>
2966  
2967 The default value as an hash reference.
2968  
2969 =item C<_extra>
2970  
2971 Extra parameters as an array reference.
2972  
2973 =item C<_fields>
2974  
2975 The columns as an hash reference.
2976  
2977 =item C<_from_unix>
2978  
2979 An hash reference
2980  
2981 =item C<_structure>
2982  
2983 The table structure which is an hash reference of column name to definition pairs.
2984  
2985 =item C<_to_unix>
2986  
2987 An hash reference
2988  
2989 =back
2990  
2991 It returns a new L<DB::Object::Tables> object with all the data prepared within.
2992  
2993 =head2 group
2994  
2995 Format the C<group by> portion of the query by calling L</_group_order>
2996  
2997 It returns a new L<DB::Object::Query::Clause> object.
2998  
2999 =head2 having
3000  
3001 This must be superseded by driver specific implementation of this class. Check out L<DB::Object::Mysql::Query/having>, L<DB::Object::Postgres::Query/having>, L<DB::Object::SQLite::Query/having>
3002  
3003 =head2 insert
3004  
3005 $tbl->insert( col1 => $val1, col2 => $val 2 );
3006 # or
3007 $other_tbl->where( user => 'joe' );
3008 my $sth = $other_tbl->select;
3009 $tbl->insert( $sth );
3010 # will become INSERT INTO some_table SELECT col1, col2 FROM other_table WHERE user = 'joe'
3011  
3012 Provided with an array reference or an hash reference or a statement object (L<DB::Object::Statement>) or a list of parameters and this will prepares an C<insert> query using the field-value pairs provided.
3013  
3014 If a L<DB::Object::Statement> object is provided as first argument, it will be considered as a SELECT query to be used in the INSERT query, as in: INSERT INTO my table SELECT FROM another_table
3015  
3016 Otherwise, L</insert> will build the query based on the fields provided.
3017  
3018 In void context, it will execute the query by calling of L<DB::Object::Statement/execute>.
3019  
3020 It returns the statement object.
3021  
3022 =head2 is_upsert
3023  
3024 Sets or gets the boolean value if the query is an C<upsert>, which means a C<insert> or C<update> query that uses an C<ON CONFLICT> clause. See L<DB::Object::Postgres::Query/on_conflict>
3025  
3026 =head2 join_fields
3027  
3028 Sets or gets the join fields. This is a regular string.
3029  
3030 =head2 join_tables
3031  
3032 Sets or gets the table joined. This returns a L<Module::Generic::Array>
3033  
3034 =head2 left_join
3035  
3036 Sets or gets an hash reference of column joint column pairs
3037  
3038 =head2 limit
3039  
3040 Set or get the limit for the future statement, by calling L</_process_limit>
3041  
3042 It returns a L<DB::Object::Query::Clause> representing the C<limit> clause.
3043  
3044 =head2 local
3045  
3046 Provided with a variable name and value pairs and this will set them.
3047  
3048 It returns the formated declaration as a string.
3049  
3050 =head2 new_clause
3051  
3052 This returns a new L<DB::Object::Query::Clause> object.
3053  
3054 =head2 new_element
3055  
3056 Instantiate a new L<DB::Object::Query::Element> object, passing it whatever arguments were provided and sharing wit it the value of the L</debug> flag.
3057  
3058 =head2 new_elements
3059  
3060 Instantiate a new L<DB::Object::Query::Elements> object, passing it whatever arguments were provided and sharing wit it the value of the L</debug> flag.
3061  
3062 =head2 order
3063  
3064 Provided with a list of parameter and this will format the C<order> clause by calling L</_group_order>
3065  
3066 It returns a new L<DB::Object::Query::Clause> object.
3067  
3068 =for Pod::Coverage pass_error
3069  
3070 =head2 prepare_options
3071  
3072 Sets or gets the options that will be used in L<DB::Object/_cache_this>, which is taked with preparing statement when they are not already cached.
3073  
3074 This method basically handles an hash reference of properties set by L<DB::Object::Query> and their inheriting packages. Currently only PostgreSQL makes use of this with L<DB::Object::Postgres::Query/dollar_placeholder> and L<DB::Object::Postgres::Query/server_prepare>
3075  
3076 =head2 query
3077  
3078 Sets or gets the query string. It returns whatever is set as a regular string.
3079  
3080 =head2 query_reset
3081  
3082 Reset the query object to its nominal value so it can be re-used.
3083  
3084 =head2 query_reset_core_keys
3085  
3086 Returns an L<Module::Generic::Array> object of core object properties shared with inheriting package.
3087  
3088 Those are used to know what properties to reset.
3089  
3090 =head2 query_reset_keys
3091  
3092 Returns an L<Module::Generic::Array> object of object properties shared with inheriting package.
3093  
3094 This contains driver specific properties and together with the ones provided with L</query_reset_core_keys>, they form a whole.
3095  
3096 =head2 query_type
3097  
3098 Sets or gets the query type, such as C<delete>, C<insert>, C<select>, C<update>, etc.
3099  
3100 =head2 query_values
3101  
3102 Sets or gets the query values.
3103  
3104 Returns a L<scalar object|Module::Generic::Scalar>
3105  
3106 =head2 replace
3107  
3108 This is unsupported by default and its implementation is driver specific.
3109  
3110 =head2 reset
3111  
3112 Reset the query object.
3113  
3114 What it does is remove the following object properties: alias local binded binded_group binded_limit binded_order binded_types binded_values binded_where where limit group_by order_by reverse from_unixtime unix_timestamp sorted
3115  
3116 =head2 reset_bind
3117  
3118 Reset the bind values by setting the following object property to an empty anonymous array: binded binded_group binded_limit binded_order binded_types binded_where
3119  
3120 =head2 returning
3121  
3122 This is unsupported by default and its implementation is driver specific.
3123  
3124 =head2 reverse
3125  
3126 Mark the query to use reverse order. This is used by L</order>.
3127  
3128 =head2 select
3129  
3130 Provided with a list or an array reference of columns, and this will format the C<select> statement.
3131  
3132 If the parameters provided is actually a scalar reference, it will be used as is.
3133  
3134 If the parameters provided is an array or array reference, it will be joined using comma to get the list of columns to get, or, if the array is empty, the special C<*> will be used to get all the columns.
3135  
3136 Otherwise, it will use the data parameter provided as is.
3137  
3138 If any alias have been set using L</alias>, they will be added to the list of columns to get.
3139  
3140 if a table alias was set using L</table_alias> it will be set here.
3141  
3142 If the method was called in void context, it will execute immediately the statement object prepared.
3143  
3144 It returns the statement object (DB::Object::Statement).
3145  
3146 =head2 selected_fields
3147  
3148 Sets or gets the string representing the list of columns used in previous C<select> statement.
3149  
3150 Returns a regular string.
3151  
3152 =head2 sort
3153  
3154 Set the query to use normal sorting order.
3155  
3156 =head2 sorted
3157  
3158 Sets or gets the list of sorted columns used in statements. This returns a L<Module::Generic::Array> object.
3159  
3160 =head2 table_alias
3161  
3162 Sets an optional alias for this table to be used in statement.
3163  
3164 This method should be called by L<DB::Object::Tables/as>. If you change this directly, you risk facing some discrepancies between the actual table alias and the one set here.
3165  
3166 Returns the current value.
3167  
3168 =head2 table_object
3169  
3170 Sets or gets the table object. This will return a L<DB::Object::Tables> object
3171  
3172 =head2 tie
3173  
3174 If provided a hash or a hash ref, it sets the list of fields and their corresponding perl variable to bind their values to.
3175  
3176 In list context, it returns the list of those field-variable pair, or a reference to it in scalar context.
3177  
3178 =head2 unix_timestamp
3179  
3180 Provided a list or an array reference of columns, and this sets the columns to be treated for seamless conversion from and to unix time.
3181  
3182 It returns a L<Module::Generic::Array> object.
3183  
3184 =head2 update
3185  
3186 Provided with a list, an array reference, or an hash or hash reference of key-value pairs and this will format the update statement.
3187  
3188 If no parameter is provided, this will return an error.
3189  
3190 This will call L</format_update> to format the parameter provided and use the resulting string in the C<update> statement.
3191  
3192 If any clauses have been defined such as C<where>, C<limit>, etc, they will be properly formatted and added to the statement.
3193  
3194 The resulting formatted query will be saved as the object property L</query>.
3195  
3196 The formatted update columns and values will be saved in the current object property L</query_values>
3197  
3198 If L</update> is called in void context, this will execute the query immediately.
3199  
3200 It returns the statement object (L<DB::Object::Statement>).
3201  
3202 =head2 where
3203  
3204 Build the where clause based on the field-value hash provided by calling L</_where_having>.
3205  
3206 It returns a clause object (L<DB::Object::Query::Clause>).
3207  
3208 =head2 _group_order
3209  
3210 This support method is called by L</group> and L</order> to format those clauses.
3211  
3212 Provided with an object, or a list or an array reference of parameters and this will format the relevant clause.
3213  
3214 it will go through each parameter and if the parameter provided is an L<DB::Object::Fields::Field> object, it will collect its various attribute.
3215  
3216 If the parameter is a scalar reference, it will be used as is.
3217  
3218 If the parameter looks like it contains some field, it will be prepended by an appropriate prefix of table and possible database and schema name, if necessary.
3219  
3220 Otherwise, it will use whatever value was provided as a column and use it.
3221  
3222 It returns a L<DB::Object::Query::Clause> object.
3223  
3224 =head2 _having
3225  
3226 This is called by L</where> and L</having>
3227  
3228 Provided with some data as a list or an array reference and this will format the C<where> or C<having> clause.
3229  
3230 Walking through each parameter provided, if a parameter is a scalar reference, it will be used as is.
3231  
3232 If the parameter looks like it contains some field, it will be prepended by an appropriate prefix of table and possible database and schema name, if necessary.
3233  
3234 If L<DB::Object/bind> is enabled, it will save the value used and use a placeholder.
3235  
3236 It returns a L<DB::Object::Query::Clause> object.
3237  
3238 =head2 _initiate_clause_object
3239  
3240 This instantiate a new L<DB::Object::Query::Clause> object passing it whatever parameters were provided.
3241  
3242 =head2 _limit
3243  
3244 Sets or gets the limit clause object and returns a L<DB::Object::Query::Clause> object.
3245  
3246 =head2 _process_limit
3247  
3248 Provided with some parameters and this will format the C<limit> clause of the query.
3249  
3250 If one parameter was provided, then this will only define the ending limit. The start will be set as L<perlfunc/undef>
3251  
3252 If two parameters are provided, then this will set the start offset and the limit.
3253  
3254 It check each of the start offset and end limit thus set, and if it is a scalar reference, it will be used as is. However, if the parameter is a C<?> it will be used as a placeholder.
3255  
3256 Otherwise, if L<DB::Object/bind> is enabled, this will save the parameter value as a binded value to be passed to L<DN::Object::Statement/execute>
3257  
3258 It returns the C<limit> clause object (DB::Object::Query::Clause)
3259  
3260 =head2 _query_components
3261  
3262 This returns an array reference of formatted clause, in their proper order to be added to query.
3263  
3264 This method is called by L</delete>, L</insert>, L</replace>, L</select> and L</update>
3265  
3266 This method is overriden by driver packages, so check L<DB::Object::Mysql::Query/_query_components>, L<DB::Object::Postgres::Query/_query_components> and L<DB::Object::SQLite::Query/_query_components>
3267  
3268 =head2 _query_type
3269  
3270 Based on the latest formatted query and the object property L</query>, this will return the type of query this is. This can be possibly one of the following: C<alter>, C<create>, C<drop>, C<grant>, C<listen>, C<notify>, C<insert>, C<update>, C<delete>, C<select>, C<truncate>
3271  
3272 =head2 _save_bind
3273  
3274 Provided with a query type and this will collect binded values from various clauses.
3275  
3276 It returns the current object.
3277  
3278 =head2 _value2bind
3279  
3280 If L<DB::Object/use_bind> is enabled, and this will modify the query passed to replace value with placeholders.
3281  
3282 Actually this method is not used anymore and really qui dangerous because parsing sql is quite challenging.
3283  
3284 =head2 _where_having
3285  
3286 This is used to format C<WHERE> and C<HAVING> clause.
3287  
3288 Provided with a query type and clause property name such as C<having> or C<where> and other parameters and this will format the C<where> or C<having> clause and return a new L<DB::Object::Query::Clause> object.
3289  
3290 It checks each parameter passed.
3291  
3292 if the first parameter is a L<DB::Object::Operator> object, it will take it embedded values by calling L<DB::Object::Query::Clause/value>. However, if there are any unknown fields, they will be ignored.
3293  
3294 If the parameter is a scalar reference, it will use it as is.
3295  
3296 If the parameter is a L<DB::Object::Operator> object like L<DB::Object::AND>, L<DB::Object::OR> or L<DB::Object::NOT>, it will recursively process its embedded elements.
3297  
3298 If the parameter is a L<DB::Object::Query::Clause> object, it will be added to the stack of elements.
3299  
3300 If the parameter is a L<DB::Object::Expression> object, it will be added to the stack of elements.
3301  
3302 If the parameter is a L<DB::Object::Fields::Overloaded> object, it will be added as a new L<DB::Object::Query::Clause> to the stack.
3303  
3304 If the parameter is a litteral represented as a string or a scalar reference, then it will be added to the list as-is. For example:
3305  
3306 $tbl->where(
3307 $tbl->fo->status eq 'active',
3308 "LENGTH(?) > 12"
3309 );
3310  
3311 or
3312  
3313 $tbl->where(
3314 $tbl->fo->status eq 'active',
3315 \"LENGTH(?) > 12"
3316 );
3317  
3318 However, make sure to put this expression at the end.
3319  
3320 It then checks parameters two by two, the first one being the column and the second being its value.
3321  
3322 If the value is the operator object L<DB::Object::NOT>, it adds to the stack a new clause object of type C<column IS NOT something>, such as C<column IS NOT NULL>
3323  
3324 if the value is undefined or that the value is equal to C<NULL>, then it adds to the stack a new clause object L<DB::Object::Query::Clause> of type C<column IS NULL>
3325  
3326 If the value is a scalar reference, it will be added as is in a new clause object that is added to the stack.
3327  
3328 If the value is a L<DB::Object::Statement>, L<DB::Object::Statement/fetchrow> will be called and the value fetched will be added as a new clause object to the stack.
3329  
3330 If the value is a perl Regexp object, then it will be formatted in a way suitable to the driver and added to a new clause object and onto the stack.
3331  
3332 If the value looks like some table field embedded inside some SQL function, then it will be added to a new clause object and onto the stack.
3333  
3334 See L<Postgres documentation for more information|https://www.postgresql.org/docs/9.5/functions-matching.html>
3335  
3336 See L<MySQL documentation for more information|https://dev.mysql.com/doc/refman/5.7/en/regexp.html>
3337  
3338 See L<SQLite documentation for more information|https://sqlite.org/lang_expr.html>
3339  
3340 If the column is of type C<bytea>, then a new clause object will be added to the stack with the column value being quoted properly using L<DB::Object/quote>
3341  
3342 All the clause objects in the stack will be merged into one new clause object using L<DB::Object::Query::Clause/merge>
3343  
3344 The resulting final clause object (L<DB::Object::Query::Clause>) is returned.
3345  
3346 =head1 AUTOLOAD
3347  
3348 When the C<AUTOLOAD> is called, it will check if the value of the method used corresponds to an existing database table, and if it does, it returns the value returned by calling L</table> with the table name.
3349  
3350 =head1 SEE ALSO
3351  
3352 L<DBI>
3353  
3354 =head1 AUTHOR
3355  
3356 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
3357  
3358 =head1 COPYRIGHT & LICENSE
3359  
3360 Copyright (c) 2018-2021 DEGUEST Pte. Ltd.
3361  
3362 You can use, copy, modify and redistribute this package and associated
3363 files under the same terms as Perl itself.
3364  
3365 =cut