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

filter: Statementstmt 0.0% 0 / 346 Branchbran 0.0% 0 / 202 Conditioncond 0.0% 0 / 127 MC/DCmcdc 0.0% 0 / 75 Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 792 CC 102 SCAR 65.9
CC
102
Cov
0%
format_statement
1722.0
on_conflict
552.0
_query_components
380.0
CRAP 724.2
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Postgres/Query.pm
4 ## Version v0.4.2
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/08/05
9 ## All rights reserved
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.##
13 ##----------------------------------------------------------------------------##
14 package DB::Object::Postgres::Query;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'DB::Object' );
20 use parent qw( DB::Object::Query );
21 use vars qw( $VERSION $DEBUG $EXCEPTION_CLASS );
22 use Wanted;
23 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
24 our $VERSION = 'v0.4.2';
25 };
26  
27 use strict;
28 use warnings;
29  
30 sub init
31 {
32 my $self = shift( @_ );
33 $self->{having} = '';
34 $self->{_init_strict_use_sub} = 1;
35 $self->{_exception_class} = $EXCEPTION_CLASS;
36 $self->SUPER::init( @_ ) || return( $self->pass_error );
37 $self->{binded_having} = [];
38 $self->{query_reset_keys} = [qw( alias binded binded_values binded_where binded_limit binded_group binded_having binded_order from_unixtime group_by limit local _on_conflict on_conflict order_by reverse sorted unix_timestamp where )];
39 return( $self );
40 }
41  
42 sub binded_having { return( shift->_set_get_array_as_object( 'binded_having', @_ ) ); }
43  
44 # sub binded_types_as_param
45 # {
46 # my $self = shift( @_ );
47 # my $types = $self->binded_types;
48 # my $params = $self->new_array;
49 # foreach my $t ( @$types )
50 # {
51 # if( CORE::length( $t ) )
52 # {
53 # $params->push( { pg_type => $t } );
54 # }
55 # else
56 # {
57 # $params->push( '' );
58 # }
59 # }
60 # return( $params );
61 # }
62  
63 sub binded_types_as_param
64 {
65 my $self = shift( @_ );
66 my $params = $self->new_array;
67 $self->elements->foreach(sub
68 {
69 my $elem = shift( @_ );
70 my $type;
71 if( $elem && $elem->as_is )
72 {
73 return;
74 }
75 elsif( $elem && defined( $type = $elem->type ) )
76 {
77 $params->push( { pg_type => $type } );
78 }
79 else
80 {
81 $params->push( '' );
82 }
83 });
84 return( $params );
85 }
86  
87 sub dollar_placeholder
88 {
89 my $self = shift( @_ );
90 if( @_ )
91 {
92 $self->prepare_options->set( 'pg_placeholder_dollaronly' => shift( @_ ) );
93 }
94 return( $self->prepare_options->get( 'pg_placeholder_dollaronly' ) );
95 }
96  
97 sub format_from_epoch
98 {
99 my $self = shift( @_ );
100 my $opts = $self->_get_args_as_hash( @_ );
101 if( $opts->{bind} )
102 {
103 return( "TO_TIMESTAMP(?)" );
104 }
105 else
106 {
107 return( sprintf( "TO_TIMESTAMP(%s)", $opts->{value} ) );
108 }
109 }
110  
111 sub format_to_epoch
112 {
113 my $self = shift( @_ );
114 my $opts = $self->_get_args_as_hash( @_ );
115 if( $opts->{bind} )
116 {
117 # 2020-10-11: ABSTIME is deprecated in PostgreSQL 12
118 # https://www.postgresql.org/docs/12/release-12.html
119 # return( "'?'::ABSTIME::INTEGER" );
120 # We use instead the more standard way which works back from PostgreSQL 7.1
121 return( "EXTRACT( EPOCH FROM '?'::TIMESTAMP )::INTEGER" );
122 }
123 else
124 {
125 # return( sprintf( "%s::ABSTIME::INTEGER", $opts->{quote} ? "'" . $opts->{value} . "'" : $opts->{value} ) );
126 return( sprintf( "EXTRACT( EPOCH FROM %s::TIMESTAMP )::INTEGER", $opts->{quote} ? "'" . $opts->{value} . "'" : $opts->{value} ) );
127 }
128 }
129  
130 # NOTE: For select or insert queries
131 sub format_statement
132 {
133 my $self = shift( @_ );
134 my $opts = $self->_get_args_as_hash( @_ );
135 my $tbl_o = $self->table_object || return( $self->error( "No table object is set." ) );
136 # Should we use bind statement?
137 my $bind = $tbl_o->use_bind;
138 $opts->{data} = $self->{_default} if( !$opts->{data} );
139 $opts->{order} = $self->{_fields} if( !$opts->{order} );
140 $opts->{table} = $tbl_o->name if( !$opts->{table} );
141 local $_;
142 my $data = $opts->{data};
143 my $order = $opts->{order};
144 my $table = $opts->{table};
145 my $from_unix = {};
146 my $unixtime = {};
147 my $args = $self->{_args};
148 my $fields = '';
149 my $values = '';
150 my $base_class = $self->base_class;
151 $from_unix = $self->{_from_unix};
152 if( !%$from_unix )
153 {
154 my $times = $self->from_unixtime();
155 map{ $from_unix->{ $_ }++ } @$times;
156 }
157  
158 if( $self->_is_array( $unixtime ) )
159 {
160 my %hash = map{ $_ => 1 } @$unixtime;
161 $unixtime = \%hash;
162 }
163 my @format_fields = ();
164 my @format_values = ();
165 my $binded = $self->{binded_values} = [];
166 my $multi_db = $tbl_o->prefix_database;
167 my $prefix = $tbl_o->prefix;
168 my $db = $tbl_o->database;
169 my $field_prefix = $tbl_o->query_object->table_alias ? $tbl_o->query_object->table_alias : $prefix;
170 my $fields_ref = $tbl_o->fields;
171 my $ok_list = CORE::join( '|', keys( %$fields_ref ) );
172 my $tables = CORE::join( '|', @{$tbl_o->database_object->tables} );
173 my $struct = $tbl_o->structure || return( $self->pass_error( $tbl_o->error ) );
174 my $types = $tbl_o->types;
175 my $types_const = $tbl_o->types_const;
176 my $query_type = $self->{query_type};
177 my @sorted = ();
178 my @types = ();
179 if( $self->query_type eq 'insert' &&
180 @$args &&
181 !( @$args % 2 ) )
182 {
183 for( my $i = 0; $i < @$args; $i += 2 )
184 {
185 push( @sorted, $args->[ $i ] ) if( exists( $order->{ $args->[ $i ] } ) );
186 $data->{ $args->[ $i ] } = $args->[ $i + 1 ] if( !exists( $data->{ $args->[ $i ] } ) );
187 }
188 }
189 @sorted = sort{ $order->{ $a }->pos <=> $order->{ $b }->pos } keys( %$order ) if( !@sorted );
190 # 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
191 # But or that we need to know the order of the fields.
192 $self->{sorted} = \@sorted;
193 my $placeholder_re = $tbl_o->database_object->_placeholder_regexp;
194 my $elems = $self->new_elements( debug => $self->debug );
195  
196 foreach my $field ( @sorted )
197 {
198 next if( defined( $struct->{ $field } ) && $struct->{ $field } =~ /\bSERIAL\b/i );
199 my $elem = $self->new_element;
200 if( exists( $data->{ $field } ) )
201 {
202 my $value = $data->{ $field };
203 if( $self->_is_a( $value, "${base_class}::Statement" ) )
204 {
205 $elem->value( '(' . $value->as_string . ')' );
206 # push( @format_values, '(' . $value->as_string . ')' );
207 # push( @$binded, $value->query_object->binded_values->list ) if( $value->query_object->binded_values->length );
208 # # $self->binded_types->push( $value->query_object->binded_types_as_param );
209 # push( @types, $value->query_object->binded_types->list ) if( $value->query_object->binded_types->length );
210 $elem->elements( $value->query_object->elements );
211 }
212 # This is for insert or update statement types
213 elsif( exists( $from_unix->{ $field } ) )
214 {
215 # push( @format_values, sprintf( "FROM_UNIXTIME('%s') AS $field", $data->{ $field } ) );
216 if( $bind )
217 {
218 # push( @$binded, $value );
219 # push( @format_values, $self->format_from_epoch({ value => $value, bind => 1 }) );
220 if( CORE::exists( $types_const->{ $field } ) )
221 {
222 # CORE::push( @types, $types_const->{ $field }->{constant} );
223 # PG_INT4
224 # CORE::push( @types, $self->database_object->get_sql_type( 'int4' ) );
225 $elem->type( $self->database_object->get_sql_type( 'int4' ) );
226 }
227 # else
228 # {
229 # CORE::push( @types, '' );
230 # }
231 if( $value =~ /($placeholder_re)/ )
232 {
233 $elem->placeholder( $1 );
234 if( defined( $+{index} ) )
235 {
236 $elem->index( $+{index} );
237 }
238 $elem->format( $value );
239 }
240 else
241 {
242 $elem->value( $value );
243 }
244 $elem->format( $self->format_from_epoch({ value => $value, bind => 1 }) );
245 }
246 else
247 {
248 if( $value =~ /^$placeholder_re$/ )
249 {
250 $elem->format( $self->format_from_epoch({ value => $value, bind => 1 }) );
251 if( CORE::exists( $types_const->{ $field } ) )
252 {
253 # CORE::push( @types, $types_const->{ $field }->{constant} );
254 # PG_INT4
255 # CORE::push( @types, $self->database_object->get_sql_type( 'int4' ) );
256 $elem->type( $self->database_object->get_sql_type( 'int4' ) );
257 }
258 # else
259 # {
260 # CORE::push( @types, '' );
261 # }
262 }
263 else
264 {
265 $elem->format( $self->format_from_epoch({ value => $value, bind => 0 }) );
266 }
267 }
268 }
269 elsif( ref( $value ) eq 'SCALAR' )
270 {
271 push( @format_values, $$value );
272 }
273 elsif( $value =~ /($placeholder_re)/ )
274 {
275 $elem->placeholder( $1 );
276 $elem->format( $value );
277 if( defined( $+{index} ) )
278 {
279 $elem->index( $+{index} );
280 }
281 # push( @format_values, $1 );
282 # CORE::push( @types, $types_const->{ $field } ? $types_const->{ $field }->{constant} : '' );
283 if( CORE::exists( $types_const->{ $field } ) )
284 {
285 # CORE::push( @types, $types_const->{ $field }->{constant} );
286 $elem->type( $types_const->{ $field }->{constant} );
287 }
288 # else
289 # {
290 # CORE::push( @types, '' );
291 # }
292 }
293 elsif( $struct->{ $field } =~ /^\s*\bBLOB\b/i )
294 {
295 # push( @format_values, '?' );
296 # push( @$binded, $value );
297 $elem->placeholder( '?' );
298 $elem->format( '?' );
299 $elem->value( $value );
300 my $const;
301 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
302 {
303 # CORE::push( @types, DBD::Pg::PG_BYTEA );
304 # CORE::push( @types, $const );
305 $elem->type( $const );
306 }
307 # else
308 # {
309 # CORE::push( @types, '' );
310 # }
311 }
312 # If the value itself looks like a field name or like a SQL function
313 # or simply if bind option is inactive
314 # This stinks too much. It is way too complex to parse or guess a sql query
315 # use a scalar reference instead to pass value as is
316 # elsif( $value =~ /(?:\.|\A)(?:$ok_list)\b/ ||
317 # $value =~ /[a-zA-Z_]{3,}\([^\)]*\)/ ||
318 # $value eq '?' )
319 # {
320 # push( @format_values, $value );
321 # }
322 elsif( !$bind )
323 {
324 my $const;
325 $elem->value( $value );
326 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
327 {
328 # push( @format_values, $tbl_o->database_object->quote( $value, DBD::Pg::PG_BYTEA ) );
329 # push( @format_values, $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
330 $elem->format( $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
331 }
332 # Value is a hash and the data type is json, so we transform this value into a json data
333 elsif( $self->_is_hash( $value => 'strict' ) && ( lc( $types->{ $field } ) eq 'jsonb' || lc( $types->{ $field } ) eq 'json' ) )
334 {
335 my $this_json = $self->_encode_json( $value );
336 # push( @format_values, $tbl_o->database_object->quote( $this_json, ( lc( $types->{ $field } ) eq 'jsonb' ? DBD::Pg::PG_JSONB : DBD::Pg::PG_JSON ) ) );
337 # push( @format_values, $tbl_o->database_object->quote( $this_json, { pg_type => $self->database_object->get_sql_type( $types->{ $field } ) } ) );
338 $elem->format( $tbl_o->database_object->quote( $this_json, { pg_type => $self->database_object->get_sql_type( $types->{ $field } ) } ) );
339 }
340 else
341 {
342 # push( @format_values, sprintf( "'%s'", quotemeta( $value ) ) );
343 # push( @format_values, sprintf( "%s", $tbl_o->database_object->quote( $value ) ) );
344 $elem->format( sprintf( "%s", $tbl_o->database_object->quote( $value ) ) );
345 }
346 }
347 # We do this before testing for param binding because DBI puts quotes around SET number :-(
348 elsif( $value =~ /^\d+$/ && $struct->{ $field } =~ /\bSET\(/i )
349 {
350 # push( @format_values, $value );
351 $elem->format( $value );
352 }
353 elsif( $value =~ /^\d+$/ &&
354 $struct->{ $field } =~ /\bENUM\(/i &&
355 ( $query_type eq 'insert' || $query_type eq 'update' ) )
356 {
357 # push( @format_values, "'$value'" );
358 $elem->format( "'$value'" );
359 }
360 # Otherwise, bind option is enabled, we bind parameter
361 elsif( $bind )
362 {
363 # push( @format_values, '?' );
364 # push( @$binded, $value );
365 $elem->placeholder( '?' );
366 $elem->format( '?' );
367 $elem->value( $value );
368 my $const;
369 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
370 {
371 # CORE::push( @types, $const );
372 $elem->type( $const );
373 }
374 # else
375 # {
376 # CORE::push( @types, '' );
377 # }
378 }
379 # In last resort, we handle the formatting ourself
380 else
381 {
382 # push( @format_values, "'" . quotemeta( $value ) . "'" );
383 my $const;
384 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
385 {
386 # push( @format_values, $tbl_o->database_object->quote( $value, DBD::Pg::PG_BYTEA ) );
387 # push( @format_values, $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
388 $elem->format( $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
389 }
390 else
391 {
392 # push( @format_values, $tbl_o->database_object->quote( $value ) );
393 $elem->format( $tbl_o->database_object->quote( $value ) );
394 }
395 }
396 }
397  
398 if( $field_prefix )
399 {
400 $field =~ s{
401 (?<![\.\"])\b($ok_list)\b(\s*)?(?!\.)
402 }
403 {
404 my( $field, $spc ) = ( $1, $2 );
405 if( $` =~ /\s+(?:AS|FROM)\s+$/i )
406 {
407 "${field}${spc}";
408 }
409 elsif( $query_type eq 'select' && $prefix )
410 {
411 "${field_prefix}.${field}${spc}";
412 }
413 else
414 {
415 "${field}${spc}";
416 }
417 }gex;
418 $field =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
419 # push( @format_fields, $field );
420 }
421 # else
422 # {
423 # push( @format_fields, $field );
424 # }
425 # If the field provided is just a string, we trade it for a table field object, because it will provide us with more information to format the query in DB::Object::Statement, such as to turn a hash reference into JSON, or a DateTime::Lite object into a suitable format
426 $elem->field( $self->_is_a( $field => 'DB::Object::Fields::Field' )
427 ? $field
428 : exists( $fields_ref->{ $field } )
429 ? $tbl_o->fields( $field )
430 : $field
431 );
432 $elems->push( $elem );
433 }
434 # TODO: Remove the following line as it is obsolete as of 2023-07-23
435 $self->binded_types->push( @types ) if( scalar( @types ) );
436 if( !wantarray() && scalar( @{$self->{_extra}} ) )
437 {
438 foreach my $this ( @{$self->{_extra}} )
439 {
440 $elems->push({
441 field => $this,
442 debug => $self->debug,
443 });
444 }
445 }
446 return( $elems );
447 }
448  
449 # _having is in DB::Object::Query
450 # sub having { return( shift->_having( @_ ) ); }
451 sub having { return( shift->_where_having( 'having', 'having', @_ ) ); }
452  
453 # <http://www.postgresql.org/docs/9.3/interactive/queries-limit.html>
454 sub limit
455 {
456 my $self = shift( @_ );
457 my $limit = $self->{limit};
458 if( @_ )
459 {
460 # Returns a DB::Object::Query::Clause
461 $limit = $self->_process_limit( @_ ) ||
462 return( $self->pass_error );
463 if( CORE::length( $limit->metadata->limit // '' ) )
464 {
465 $limit->generic( CORE::length( $limit->metadata->offset // '' ) ? 'OFFSET ? LIMIT ?' : 'LIMIT ?' );
466 # %s works for integer, and also for numbered placeholders like $1 or ?1, or regular placeholder like ?
467 $limit->value(
468 CORE::length( $limit->metadata->offset // '' )
469 ? sprintf( "OFFSET %s LIMIT %s", $limit->metadata->offset, $limit->metadata->limit )
470 : sprintf( "LIMIT %s", $limit->metadata->limit )
471 );
472 }
473 }
474  
475 if( !$limit && want( 'OBJECT' ) )
476 {
477 return( $self->new_null( type => 'object' ) );
478 }
479 return( $limit );
480 }
481  
482 # FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE
483 # This feature is available since PostgreSQL version 9.3
484 # <https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE>
485 sub lock
486 {
487 my $self = shift( @_ );
488 my $lock = $self->{lock};
489 if( @_ )
490 {
491 require version;
492 if( $self->database_object->version < version->parse( '9.3' ) )
493 {
494 warn( "This feature is only available in PostgreSQL version 9.3 and above." ) if( $self->_warnings_enabled( 'DB::Object' ) );
495 }
496 # Supported, case insensitive:
497 # For update
498 # For no key update
499 # For share
500 # For key share
501 # update
502 # no key update
503 # share
504 # key share
505 my $str = shift( @_ );
506 if( $str !~ /^(?:For[[:blank:]\h]+)?(update|no[[:blank:]\h]+key[[:blank:]\h]+update|share|key[[:blank:]\h]+share)/i )
507 {
508 return( $self->error( "Unsupported argument for locking. See https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE" ) );
509 }
510 unless( $str =~ /^For[[:blank:]\h]+/i )
511 {
512 $str = 'FOR ' . $str;
513 }
514 $lock = $self->{lock} = uc( $str );
515 }
516 return( $lock );
517 }
518  
519 # https://www.postgresql.org/docs/10/sql-insert.html
520 # $q->on_conflict({
521 # target => 'id',
522 # action => 'nothing',
523 # action => 'update',
524 # fields => { a => 'some value', b => 'some other' },
525 # });
526 sub on_conflict
527 {
528 my $self = shift( @_ );
529 my $opts = {};
530 $self->{_on_conflict} = {} if( ref( $self->{_on_conflict} ) ne 'HASH' );
531 if( @_ )
532 {
533 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
534 my $ver = $tbl_o->database_object->version;
535 if( version->parse( $ver ) < version->parse( '9.4' ) )
536 {
537 return( $self->error( "PostgreSQL version is $ver, but version 9.5 or higher is required to use this on conflict clause." ) );
538 }
539 $opts = $self->_get_args_as_hash( @_ );
540 my $hash = {};
541 my @comp = ( 'ON CONFLICT' );
542 if( $opts->{target} )
543 {
544 $hash->{target} = $opts->{target};
545 # Example: ON CONFLICT ON CONSTRAINT customers_name_key DO NOTHING;
546 if( $hash->{target} =~ /^(on[[:blank:]]+constraint)(.*?)$/i )
547 {
548 $hash->{target} = "\U$1\E$2";
549 push( @comp, $hash->{target} );
550 }
551 # a reference to a scalar was provided, so we set the value as is
552 elsif( ref( $hash->{target} ) eq 'SCALAR' )
553 {
554 push( @comp, $$hash->{target} );
555 }
556 elsif( $self->_is_array( $hash->{target} ) )
557 {
558 push( @comp, sprintf( '(%s)', join( ',', @{$hash->{target}} ) ) );
559 }
560 else
561 {
562 push( @comp, sprintf( '(%s)', $hash->{target} ) );
563 }
564 }
565 # https://www.postgresql.org/docs/10/sql-insert.html#SQL-ON-CONFLICT
566 elsif( $opts->{action} ne 'nothing' )
567 {
568 return( $self->error( "No target was specified for the on conflict clause." ) );
569 }
570  
571 if( $opts->{where} )
572 {
573 $hash->{where} = $opts->{where};
574 push( @comp, 'WHERE ' . $opts->{where} );
575 }
576  
577 # action => update
578 if( $opts->{action} )
579 {
580 if( $opts->{action} eq 'update' )
581 {
582 $hash->{action} = $opts->{action};
583 # return( $self->error( "No fields to update was provided for on conflict do update" ) ) if( !$opts->{fields} );
584 # No fields provided, so we take it from the initial insert and build the update list instead
585 if( !$opts->{fields} )
586 {
587 $self->{_on_conflict_callback} = sub
588 {
589 my $f_ref = $self->{_args};
590 # Need to account for placeholders
591 # Let's check values only
592 $self->is_upsert(1);
593 my $elems = $self->format_update( $f_ref );
594 my $inherited_fields = $elems->formats->join( ', ' );
595 push( @comp, 'DO UPDATE SET' );
596 push( @comp, $inherited_fields );
597 $hash->{query} = join( ' ', @comp );
598 $self->{_on_conflict} = $hash;
599 $self->{on_conflict} = join( ' ', @comp );
600 $self->elements->push( $elems->elements->list );
601 # Usable only once
602 CORE::delete( $self->{_on_conflict_callback} );
603 };
604 # Return empty, not undef; undef is error
605 return( '' );
606 }
607 return( $self->error( "Fields property to update for on conflict do update clause is not a hash reference nor an array of fields." ) ) if( !$self->_is_hash( $opts->{fields} => 'strict' ) && !$self->_is_array( $opts->{fields} ) && !$self->{_on_conflict_callback} );
608 if( $self->_is_hash( $opts->{fields} => 'strict' ) )
609 {
610 return( $self->error( "Fields property to update for on conflict do update clause contains no fields!" ) ) if( !scalar( keys( %{$opts->{fields}} ) ) );
611 }
612 elsif( $self->_is_array( $opts->{fields} ) )
613 {
614 return( $self->error( "Fields property to update for on conflict do update clause contains no fields!" ) ) if( !scalar( @{$opts->{fields}} ) );
615 }
616  
617 if( $self->_is_array( $opts->{fields} ) )
618 {
619 my $this = $opts->{fields};
620 my $new = {};
621 foreach my $f ( @$this )
622 {
623 $new->{ $f } = \( 'EXCLUDED.' . $f );
624 }
625 $opts->{fields} = $new;
626 }
627 # Here the user will use the special table 'excluded'
628 $hash->{fields} = $opts->{fields};
629  
630 my $q = [];
631  
632 foreach my $k ( sort( keys( %{$opts->{fields}} ) ) )
633 {
634 push( @$q, sprintf( '%s = %s', $k, ref( $opts->{fields}->{ $k } ) eq 'SCALAR' ? ${$opts->{fields}->{ $k }} : $tbl_o->database_object->quote( $opts->{fields}->{ $k } ) ) );
635 }
636 if( scalar( @$q ) )
637 {
638 push( @comp, 'DO UPDATE SET' );
639 push( @comp, join( ", ", @$q ) );
640 }
641 else
642 {
643 return( $self->error( "An on conflict do update clause was specified, but I could not get a list of fields to update." ) );
644 }
645 }
646 elsif( $opts->{action} eq 'nothing' || $opts->{action} eq 'ignore' )
647 {
648 $hash->{action} = $opts->{action};
649 push( @comp, 'DO NOTHING' );
650 }
651 else
652 {
653 return( $self->error( "Unknown action '$opts->{action}' for on conflict clause." ) );
654 }
655 }
656 else
657 {
658 return( $self->error( "No action was specified for the on conflict clause." ) );
659 }
660 $hash->{query} = join( ' ', @comp );
661 $self->{_on_conflict} = $hash;
662 $self->{on_conflict} = $self->new_clause({ value => join( ' ', @comp ) });
663 }
664 # We are being called possibly by _query_components
665 # If we have a callback, we execute it
666 if( $self->{_on_conflict_callback} && !scalar( @_ ) )
667 {
668 # This will use the insert components set up to format our on conflict clause properly
669 # The callback is needed, because the query formatting occurs after the calling of our method on_conflict()
670 $self->{_on_conflict_callback}->();
671 }
672 return( $self->{on_conflict} );
673 }
674  
675 sub reset
676 {
677 my $self = shift( @_ );
678 if( !$self->{query_reset} )
679 {
680 my $keys = [qw( alias binded binded_values binded_where binded_limit binded_group binded_having binded_order from_unixtime group_by limit local _on_conflict on_conflict order_by reverse sorted unix_timestamp where )];
681 CORE::delete( @$self{ @$keys } );
682 $self->{query_reset}++;
683 # $self->{enhance} = 1;
684 }
685 return( $self );
686 }
687  
688 sub reset_bind
689 {
690 my $self = shift( @_ );
691 my @f = qw( binded binded_where binded_group binded_having binded_order binded_limit );
692 foreach my $field ( @f )
693 {
694 $self->{ $field } = [];
695 }
696 return( $self );
697 }
698  
699 sub returning
700 {
701 my $self = shift( @_ );
702 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
703 if( @_ )
704 {
705 my $pg_version = $self->database_object->version;
706 return( $self->error( "Cannot use returning for PostgreSQL version lower than 8.2. This server version is: $pg_version" ) ) if( $pg_version < '8.2' );
707 # It could be a field name or a wildcard
708 return( $self->error( "A reference was provided (", ref( $_[0] ), "), but I was expecting a string, which could be a field name or even a star (*) indicating all fields." ) ) if( ref( $_[0] ) );
709 $self->{returning} = $self->new_clause( value => shift( @_ ) );
710 }
711 return( $self->{returning} );
712 }
713  
714 sub server_prepare
715 {
716 my $self = shift( @_ );
717 if( @_ )
718 {
719 $self->prepare_options->set( 'pg_server_prepare' => shift( @_ ) );
720 }
721 return( $self->prepare_options->get( 'pg_server_prepare' ) );
722 }
723  
724 sub _query_components
725 {
726 my $self = shift( @_ );
727 my $type = ( @_ > 0 && lc( shift( @_ ) ) ) || $self->_query_type() || return( $self->error( "You must specify a query type: select, insert, update or delete" ) );
728 my $opts = $self->_get_args_as_hash( @_ );
729 # ok options:
730 # no_bind_copy: because join for example does it already and this would duplicate the binded types, so we use this option to tell this method to set an exception. Kind of a hack that needs clean-up in the future from a design point of view.
731 $opts->{no_bind_copy} //= 0;
732 my( $where, $group, $having, $sort, $order, $limit, $returning, $on_conflict, $lock );
733  
734 $where = $self->where();
735 if( $type eq 'select' )
736 {
737 $group = $self->group;
738 $having = $self->having;
739 $sort = $self->reverse ? 'DESC' : $self->sort ? 'ASC' : '';
740 $order = $self->order;
741 # <https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE>
742 $lock = $self->lock;
743 }
744 $limit = $self->limit;
745 $returning = $self->returning;
746 $on_conflict = $self->on_conflict;
747 my @query = ();
748 push( @query, "WHERE $where" ) if( $where && $type ne 'insert' );
749 if( $where && $where->elements->length )
750 {
751 # $self->binded_types->push( $where->bind->types->list ) unless( $opts->{no_bind_copy} );
752 $self->elements->push( $where ) unless( $opts->{no_bind_copy} );
753 }
754 push( @query, "GROUP BY $group" ) if( $group && $type eq 'select' );
755 push( @query, "HAVING $having" ) if( $having && $type eq 'select' );
756 push( @query, "ORDER BY $order" ) if( $order && $type eq 'select' );
757 push( @query, $sort ) if( $sort && $order && $type eq 'select' );
758 if( $limit && $type eq 'select' )
759 {
760 push( @query, "$limit" );
761 # if( $limit->bind->types->length )
762 if( $limit->elements->length )
763 {
764 # $self->binded_types->push( $limit->bind->types->list ) unless( $opts->{no_bind_copy} );
765 $self->elements->push( $limit ) unless( $opts->{no_bind_copy} );
766 }
767 }
768 if( $on_conflict )
769 {
770 if( $type eq 'insert' )
771 {
772 push( @query, $on_conflict );
773 }
774 else
775 {
776 warn( "Warning only: the PostgreSQL ON CONFLICT clause is only supported for INSERT queries. Your query was of type \"$type\"." ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
777 }
778 }
779  
780 if( $returning && ( $type eq 'insert' || $type eq 'update' || $type eq 'delete' ) )
781 {
782 push( @query, "RETURNING $returning" );
783 }
784 elsif( $lock && $type eq 'select' )
785 {
786 push( @query, $lock );
787 }
788 return( \@query );
789 }
790  
791 1;
792 # NOTE: POD
793 __END__