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

filter: Statementstmt 0.0% 0 / 328 Branchbran 0.0% 0 / 184 Conditioncond 0.0% 0 / 124 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 675 CC 93 SCAR 65.3
CC
93
Cov
0%
format_statement
1560.0
on_conflict
552.0
_query_components
306.0
CRAP 688.8
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Postgres/Query.pm
4 ## Version v0.4.1
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/03/26
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::Postgres::Query;
16 BEGIN
17 {
18 use strict;
19 use warnings;
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.1';
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->param( 'multi_db' );
167 my $multi_db = $tbl_o->prefix_database;
168 my $prefix = $tbl_o->prefix;
169 my $db = $tbl_o->database;
170 my $field_prefix = $tbl_o->query_object->table_alias ? $tbl_o->query_object->table_alias : $prefix;
171 my $fields_ref = $tbl_o->fields;
172 my $ok_list = CORE::join( '|', keys( %$fields_ref ) );
173 my $tables = CORE::join( '|', @{$tbl_o->database_object->tables} );
174 my $struct = $tbl_o->structure || return( $self->pass_error( $tbl_o->error ) );
175 my $types = $tbl_o->types;
176 my $types_const = $tbl_o->types_const;
177 my $query_type = $self->{query_type};
178 my @sorted = ();
179 my @types = ();
180 if( $self->query_type eq 'insert' &&
181 @$args &&
182 !( @$args % 2 ) )
183 {
184 for( my $i = 0; $i < @$args; $i += 2 )
185 {
186 push( @sorted, $args->[ $i ] ) if( exists( $order->{ $args->[ $i ] } ) );
187 $data->{ $args->[ $i ] } = $args->[ $i + 1 ] if( !exists( $data->{ $args->[ $i ] } ) );
188 }
189 }
190 @sorted = sort{ $order->{ $a }->pos <=> $order->{ $b }->pos } keys( %$order ) if( !@sorted );
191 # 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
192 # But or that we need to know the order of the fields.
193 $self->{sorted} = \@sorted;
194 my $placeholder_re = $tbl_o->database_object->_placeholder_regexp;
195 my $elems = $self->new_elements( debug => $self->debug );
196  
197 foreach my $field ( @sorted )
198 {
199 next if( defined( $struct->{ $field } ) && $struct->{ $field } =~ /\bSERIAL\b/i );
200 my $elem = $self->new_element;
201 if( exists( $data->{ $field } ) )
202 {
203 my $value = $data->{ $field };
204 if( $self->_is_a( $value, "${base_class}::Statement" ) )
205 {
206 $elem->value( '(' . $value->as_string . ')' );
207 # push( @format_values, '(' . $value->as_string . ')' );
208 # push( @$binded, $value->query_object->binded_values->list ) if( $value->query_object->binded_values->length );
209 # # $self->binded_types->push( $value->query_object->binded_types_as_param );
210 # push( @types, $value->query_object->binded_types->list ) if( $value->query_object->binded_types->length );
211 $elem->elements( $value->query_object->elements );
212 }
213 # This is for insert or update statement types
214 elsif( exists( $from_unix->{ $field } ) )
215 {
216 # push( @format_values, sprintf( "FROM_UNIXTIME('%s') AS $field", $data->{ $field } ) );
217 if( $bind )
218 {
219 # push( @$binded, $value );
220 # push( @format_values, $self->format_from_epoch({ value => $value, bind => 1 }) );
221 if( CORE::exists( $types_const->{ $field } ) )
222 {
223 # CORE::push( @types, $types_const->{ $field }->{constant} );
224 # PG_INT4
225 # CORE::push( @types, $self->database_object->get_sql_type( 'int4' ) );
226 $elem->type( $self->database_object->get_sql_type( 'int4' ) );
227 }
228 # else
229 # {
230 # CORE::push( @types, '' );
231 # }
232 if( $value =~ /($placeholder_re)/ )
233 {
234 $elem->placeholder( $1 );
235 if( defined( $+{index} ) )
236 {
237 $elem->index( $+{index} );
238 }
239 $elem->format( $value );
240 }
241 else
242 {
243 $elem->value( $value );
244 }
245 $elem->format( $self->format_from_epoch({ value => $value, bind => 1 }) );
246 }
247 else
248 {
249 if( $value =~ /^$placeholder_re$/ )
250 {
251 $elem->format( $self->format_from_epoch({ value => $value, bind => 1 }) );
252 if( CORE::exists( $types_const->{ $field } ) )
253 {
254 # CORE::push( @types, $types_const->{ $field }->{constant} );
255 # PG_INT4
256 # CORE::push( @types, $self->database_object->get_sql_type( 'int4' ) );
257 $elem->type( $self->database_object->get_sql_type( 'int4' ) );
258 }
259 # else
260 # {
261 # CORE::push( @types, '' );
262 # }
263 }
264 else
265 {
266 $elem->format( $self->format_from_epoch({ value => $value, bind => 0 }) );
267 }
268 }
269 }
270 elsif( ref( $value ) eq 'SCALAR' )
271 {
272 push( @format_values, $$value );
273 }
274 elsif( $value =~ /($placeholder_re)/ )
275 {
276 $elem->placeholder( $1 );
277 $elem->format( $value );
278 if( defined( $+{index} ) )
279 {
280 $elem->index( $+{index} );
281 }
282 # push( @format_values, $1 );
283 # CORE::push( @types, $types_const->{ $field } ? $types_const->{ $field }->{constant} : '' );
284 if( CORE::exists( $types_const->{ $field } ) )
285 {
286 # CORE::push( @types, $types_const->{ $field }->{constant} );
287 $elem->type( $types_const->{ $field }->{constant} );
288 }
289 # else
290 # {
291 # CORE::push( @types, '' );
292 # }
293 }
294 elsif( $struct->{ $field } =~ /^\s*\bBLOB\b/i )
295 {
296 # push( @format_values, '?' );
297 # push( @$binded, $value );
298 $elem->placeholder( '?' );
299 $elem->format( '?' );
300 $elem->value( $value );
301 my $const;
302 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
303 {
304 # CORE::push( @types, DBD::Pg::PG_BYTEA );
305 # CORE::push( @types, $const );
306 $elem->type( $const );
307 }
308 # else
309 # {
310 # CORE::push( @types, '' );
311 # }
312 }
313 # If the value itself looks like a field name or like a SQL function
314 # or simply if bind option is inactive
315 # This stinks too much. It is way too complex to parse or guess a sql query
316 # use a scalar reference instead to pass value as is
317 # elsif( $value =~ /(?:\.|\A)(?:$ok_list)\b/ ||
318 # $value =~ /[a-zA-Z_]{3,}\([^\)]*\)/ ||
319 # $value eq '?' )
320 # {
321 # push( @format_values, $value );
322 # }
323 elsif( !$bind )
324 {
325 my $const;
326 $elem->value( $value );
327 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
328 {
329 # push( @format_values, $tbl_o->database_object->quote( $value, DBD::Pg::PG_BYTEA ) );
330 # push( @format_values, $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
331 $elem->format( $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
332 }
333 # Value is a hash and the data type is json, so we transform this value into a json data
334 elsif( $self->_is_hash( $value => 'strict' ) && ( lc( $types->{ $field } ) eq 'jsonb' || lc( $types->{ $field } ) eq 'json' ) )
335 {
336 my $this_json = $self->_encode_json( $value );
337 # push( @format_values, $tbl_o->database_object->quote( $this_json, ( lc( $types->{ $field } ) eq 'jsonb' ? DBD::Pg::PG_JSONB : DBD::Pg::PG_JSON ) ) );
338 # push( @format_values, $tbl_o->database_object->quote( $this_json, { pg_type => $self->database_object->get_sql_type( $types->{ $field } ) } ) );
339 $elem->format( $tbl_o->database_object->quote( $this_json, { pg_type => $self->database_object->get_sql_type( $types->{ $field } ) } ) );
340 }
341 else
342 {
343 # push( @format_values, sprintf( "'%s'", quotemeta( $value ) ) );
344 # push( @format_values, sprintf( "%s", $tbl_o->database_object->quote( $value ) ) );
345 $elem->format( sprintf( "%s", $tbl_o->database_object->quote( $value ) ) );
346 }
347 }
348 # We do this before testing for param binding because DBI puts quotes around SET number :-(
349 elsif( $value =~ /^\d+$/ && $struct->{ $field } =~ /\bSET\(/i )
350 {
351 # push( @format_values, $value );
352 $elem->format( $value );
353 }
354 elsif( $value =~ /^\d+$/ &&
355 $struct->{ $field } =~ /\bENUM\(/i &&
356 ( $query_type eq 'insert' || $query_type eq 'update' ) )
357 {
358 # push( @format_values, "'$value'" );
359 $elem->format( "'$value'" );
360 }
361 # Otherwise, bind option is enabled, we bind parameter
362 elsif( $bind )
363 {
364 # push( @format_values, '?' );
365 # push( @$binded, $value );
366 $elem->placeholder( '?' );
367 $elem->format( '?' );
368 $elem->value( $value );
369 my $const;
370 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
371 {
372 # CORE::push( @types, $const );
373 $elem->type( $const );
374 }
375 # else
376 # {
377 # CORE::push( @types, '' );
378 # }
379 }
380 # In last resort, we handle the formatting ourself
381 else
382 {
383 # push( @format_values, "'" . quotemeta( $value ) . "'" );
384 my $const;
385 if( lc( $types->{ $field } ) eq 'bytea' && ( $const = $self->database_object->get_sql_type( 'bytea' ) ) )
386 {
387 # push( @format_values, $tbl_o->database_object->quote( $value, DBD::Pg::PG_BYTEA ) );
388 # push( @format_values, $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
389 $elem->format( $tbl_o->database_object->quote( $value, { pg_type => $const } ) );
390 }
391 else
392 {
393 # push( @format_values, $tbl_o->database_object->quote( $value ) );
394 $elem->format( $tbl_o->database_object->quote( $value ) );
395 }
396 }
397 }
398  
399 if( $field_prefix )
400 {
401 $field =~ s{
402 (?<![\.\"])\b($ok_list)\b(\s*)?(?!\.)
403 }
404 {
405 my( $field, $spc ) = ( $1, $2 );
406 if( $` =~ /\s+(?:AS|FROM)\s+$/i )
407 {
408 "${field}${spc}";
409 }
410 elsif( $query_type eq 'select' && $prefix )
411 {
412 "${field_prefix}.${field}${spc}";
413 }
414 else
415 {
416 "${field}${spc}";
417 }
418 }gex;
419 $field =~ s/(?<!\.)($tables)(?:\.)/$db\.$1\./g if( $multi_db );
420 # push( @format_fields, $field );
421 }
422 # else
423 # {
424 # push( @format_fields, $field );
425 # }
426 $elem->field( $field );
427 $elems->push( $elem );
428 }
429 # TODO: Remove the following line as it is obsolete as of 2023-07-23
430 $self->binded_types->push( @types ) if( scalar( @types ) );
431 if( !wantarray() && scalar( @{$self->{_extra}} ) )
432 {
433 foreach my $this ( @{$self->{_extra}} )
434 {
435 $elems->push({
436 field => $this,
437 debug => $self->debug,
438 });
439 }
440 }
441 return( $elems );
442 }
443  
444 # _having is in DB::Object::Query
445 # sub having { return( shift->_having( @_ ) ); }
446 sub having { return( shift->_where_having( 'having', 'having', @_ ) ); }
447  
448 # http://www.postgresql.org/docs/9.3/interactive/queries-limit.html
449 sub limit
450 {
451 my $self = shift( @_ );
452 my $limit = $self->{limit};
453 if( @_ )
454 {
455 # Returns a DB::Object::Query::Clause
456 $limit = $self->_process_limit( @_ ) ||
457 return( $self->pass_error );
458 if( CORE::length( $limit->metadata->limit // '' ) )
459 {
460 $limit->generic( CORE::length( $limit->metadata->offset // '' ) ? 'OFFSET ? LIMIT ?' : 'LIMIT ?' );
461 # %s works for integer, and also for numbered placeholders like $1 or ?1, or regular placeholder like ?
462 $limit->value(
463 CORE::length( $limit->metadata->offset // '' )
464 ? sprintf( "OFFSET %s LIMIT %s", $limit->metadata->offset, $limit->metadata->limit )
465 : sprintf( "LIMIT %s", $limit->metadata->limit )
466 );
467 }
468 }
469  
470 if( !$limit && want( 'OBJECT' ) )
471 {
472 return( $self->new_null( type => 'object' ) );
473 }
474 return( $limit );
475 }
476  
477 # https://www.postgresql.org/docs/10/sql-insert.html
478 # $q->on_conflict({
479 # target => 'id',
480 # action => 'nothing',
481 # action => 'update',
482 # fields => { a => 'some value', b => 'some other' },
483 # });
484 sub on_conflict
485 {
486 my $self = shift( @_ );
487 my $opts = {};
488 $self->{_on_conflict} = {} if( ref( $self->{_on_conflict} ) ne 'HASH' );
489 if( @_ )
490 {
491 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
492 my $ver = $tbl_o->database_object->version;
493 if( version->parse( $ver ) < version->parse( '9.4' ) )
494 {
495 return( $self->error( "PostgreSQL version is $ver, but version 9.5 or higher is required to use this on conflict clause." ) );
496 }
497 $opts = $self->_get_args_as_hash( @_ );
498 my $hash = {};
499 my @comp = ( 'ON CONFLICT' );
500 if( $opts->{target} )
501 {
502 $hash->{target} = $opts->{target};
503 # Example: ON CONFLICT ON CONSTRAINT customers_name_key DO NOTHING;
504 if( $hash->{target} =~ /^(on[[:blank:]]+constraint)(.*?)$/i )
505 {
506 $hash->{target} = "\U$1\E$2";
507 push( @comp, $hash->{target} );
508 }
509 # a reference to a scalar was provided, so we set the value as is
510 elsif( ref( $hash->{target} ) eq 'SCALAR' )
511 {
512 push( @comp, $$hash->{target} );
513 }
514 elsif( $self->_is_array( $hash->{target} ) )
515 {
516 push( @comp, sprintf( '(%s)', join( ',', @{$hash->{target}} ) ) );
517 }
518 else
519 {
520 push( @comp, sprintf( '(%s)', $hash->{target} ) );
521 }
522 }
523 # https://www.postgresql.org/docs/10/sql-insert.html#SQL-ON-CONFLICT
524 elsif( $opts->{action} ne 'nothing' )
525 {
526 return( $self->error( "No target was specified for the on conflict clause." ) );
527 }
528  
529 if( $opts->{where} )
530 {
531 $hash->{where} = $opts->{where};
532 push( @comp, 'WHERE ' . $opts->{where} );
533 }
534  
535 # action => update
536 if( $opts->{action} )
537 {
538 if( $opts->{action} eq 'update' )
539 {
540 $hash->{action} = $opts->{action};
541 # return( $self->error( "No fields to update was provided for on conflict do update" ) ) if( !$opts->{fields} );
542 # No fields provided, so we take it from the initial insert and build the update list instead
543 if( !$opts->{fields} )
544 {
545 $self->{_on_conflict_callback} = sub
546 {
547 my $f_ref = $self->{_args};
548 # Need to account for placeholders
549 # Let's check values only
550 $self->is_upsert(1);
551 my $elems = $self->format_update( $f_ref );
552 my $inherited_fields = $elems->formats->join( ', ' );
553 push( @comp, 'DO UPDATE SET' );
554 push( @comp, $inherited_fields );
555 $hash->{query} = join( ' ', @comp );
556 $self->{_on_conflict} = $hash;
557 $self->{on_conflict} = join( ' ', @comp );
558 $self->elements->push( $elems->elements->list );
559 # Usable only once
560 CORE::delete( $self->{_on_conflict_callback} );
561 };
562 # Return empty, not undef; undef is error
563 return( '' );
564 }
565 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} );
566 if( $self->_is_hash( $opts->{fields} => 'strict' ) )
567 {
568 return( $self->error( "Fields property to update for on conflict do update clause contains no fields!" ) ) if( !scalar( keys( %{$opts->{fields}} ) ) );
569 }
570 elsif( $self->_is_array( $opts->{fields} ) )
571 {
572 return( $self->error( "Fields property to update for on conflict do update clause contains no fields!" ) ) if( !scalar( @{$opts->{fields}} ) );
573 }
574  
575 if( $self->_is_array( $opts->{fields} ) )
576 {
577 my $this = $opts->{fields};
578 my $new = {};
579 foreach my $f ( @$this )
580 {
581 $new->{ $f } = \( 'EXCLUDED.' . $f );
582 }
583 $opts->{fields} = $new;
584 }
585 # Here the user will use the special table 'excluded'
586 $hash->{fields} = $opts->{fields};
587  
588 my $q = [];
589  
590 foreach my $k ( sort( keys( %{$opts->{fields}} ) ) )
591 {
592 push( @$q, sprintf( '%s = %s', $k, ref( $opts->{fields}->{ $k } ) eq 'SCALAR' ? ${$opts->{fields}->{ $k }} : $tbl_o->database_object->quote( $opts->{fields}->{ $k } ) ) );
593 }
594 if( scalar( @$q ) )
595 {
596 push( @comp, 'DO UPDATE SET' );
597 push( @comp, join( ", ", @$q ) );
598 }
599 else
600 {
601 return( $self->error( "An on conflict do update clause was specified, but I could not get a list of fields to update." ) );
602 }
603 }
604 elsif( $opts->{action} eq 'nothing' || $opts->{action} eq 'ignore' )
605 {
606 $hash->{action} = $opts->{action};
607 push( @comp, 'DO NOTHING' );
608 }
609 else
610 {
611 return( $self->error( "Unknown action '$opts->{action}' for on conflict clause." ) );
612 }
613 }
614 else
615 {
616 return( $self->error( "No action was specified for the on conflict clause." ) );
617 }
618 $hash->{query} = join( ' ', @comp );
619 $self->{_on_conflict} = $hash;
620 $self->{on_conflict} = $self->new_clause({ value => join( ' ', @comp ) });
621 }
622 # We are being called possibly by _query_components
623 # If we have a callback, we execute it
624 if( $self->{_on_conflict_callback} && !scalar( @_ ) )
625 {
626 # This will use the insert components set up to format our on conflict clause properly
627 # The callback is needed, because the query formatting occurs after the calling of our method on_conflict()
628 $self->{_on_conflict_callback}->();
629 }
630 return( $self->{on_conflict} );
631 }
632  
633 sub reset
634 {
635 my $self = shift( @_ );
636 if( !$self->{query_reset} )
637 {
638 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 )];
639 CORE::delete( @$self{ @$keys } );
640 $self->{query_reset}++;
641 $self->{enhance} = 1;
642 }
643 return( $self );
644 }
645  
646 sub reset_bind
647 {
648 my $self = shift( @_ );
649 my @f = qw( binded binded_where binded_group binded_having binded_order binded_limit );
650 foreach my $field ( @f )
651 {
652 $self->{ $field } = [];
653 }
654 return( $self );
655 }
656  
657 sub returning
658 {
659 my $self = shift( @_ );
660 my $tbl_o = $self->{table_object} || return( $self->error( "No table object is set." ) );
661 if( @_ )
662 {
663 my $pg_version = $self->database_object->version;
664 return( $self->error( "Cannot use returning for PostgreSQL version lower than 8.2. This server version is: $pg_version" ) ) if( $pg_version < '8.2' );
665 # It could be a field name or a wildcard
666 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] ) );
667 $self->{returning} = $self->new_clause( value => shift( @_ ) );
668 }
669 return( $self->{returning} );
670 }
671  
672 sub server_prepare
673 {
674 my $self = shift( @_ );
675 if( @_ )
676 {
677 $self->prepare_options->set( 'pg_server_prepare' => shift( @_ ) );
678 }
679 return( $self->prepare_options->get( 'pg_server_prepare' ) );
680 }
681  
682 sub _query_components
683 {
684 my $self = shift( @_ );
685 my $type = ( @_ > 0 && lc( shift( @_ ) ) ) || $self->_query_type() || return( $self->error( "You must specify a query type: select, insert, update or delete" ) );
686 my $opts = $self->_get_args_as_hash( @_ );
687 # ok options:
688 # 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.
689 $opts->{no_bind_copy} //= 0;
690 my( $where, $group, $having, $sort, $order, $limit, $returning, $on_conflict );
691  
692 $where = $self->where();
693 if( $type eq 'select' )
694 {
695 $group = $self->group;
696 $having = $self->having;
697 $sort = $self->reverse ? 'DESC' : $self->sort ? 'ASC' : '';
698 $order = $self->order;
699 }
700 $limit = $self->limit;
701 $returning = $self->returning;
702 $on_conflict = $self->on_conflict;
703 my @query = ();
704 push( @query, "WHERE $where" ) if( $where && $type ne 'insert' );
705 if( $where && $where->elements->length )
706 {
707 # $self->binded_types->push( $where->bind->types->list ) unless( $opts->{no_bind_copy} );
708 $self->elements->push( $where ) unless( $opts->{no_bind_copy} );
709 }
710 push( @query, "GROUP BY $group" ) if( $group && $type eq 'select' );
711 push( @query, "HAVING $having" ) if( $having && $type eq 'select' );
712 push( @query, "ORDER BY $order" ) if( $order && $type eq 'select' );
713 push( @query, $sort ) if( $sort && $order && $type eq 'select' );
714 if( $limit && $type eq 'select' )
715 {
716 push( @query, "$limit" );
717 # if( $limit->bind->types->length )
718 if( $limit->elements->length )
719 {
720 # $self->binded_types->push( $limit->bind->types->list ) unless( $opts->{no_bind_copy} );
721 $self->elements->push( $limit ) unless( $opts->{no_bind_copy} );
722 }
723 }
724 if( $on_conflict )
725 {
726 if( $type eq 'insert' )
727 {
728 push( @query, $on_conflict );
729 }
730 else
731 {
732 warn( "Warning only: the PostgreSQL ON CONFLICT clause is only supported for INSERT queries. Your query was of type \"$type\".\n" );
733 }
734 }
735 push( @query, "RETURNING $returning" ) if( $returning && ( $type eq 'insert' || $type eq 'update' || $type eq 'delete' ) );
736 return( \@query );
737 }
738  
739 1;
740 # NOTE: POD
741 __END__
742  
743 =encoding utf-8
744  
745 =head1 NAME
746  
747 DB::Object::Postgres::Query - Query Object for PostgreSQL
748  
749 =head1 SYNOPSIS
750  
751 use DB::Object::Postgres::Query;
752 my $this = DB::Object::Postgres::Query->new || die( DB::Object::Postgres::Query->error, "\n" );
753  
754 =head1 VERSION
755  
756 v0.4.1
757  
758 =head1 DESCRIPTION
759  
760 This is a Postgres specific query object.
761  
762 =head1 METHODS
763  
764 =head2 binded_having
765  
766 Sets or gets the array object (L<Module::Generic::Array>) for the binded value in C<HAVING> clauses.
767  
768 =head2 binded_types_as_param
769  
770 Returns an array object (L<Module::Generic::Array>) of binded params types.
771  
772 =head2 dollar_placeholder
773  
774 Provided with a true value, and this will set the placeholder to be a dollar, such as C<$1>, C<$2>, etc for this query only.
775  
776 It returns the current boolean value.
777  
778 =head2 format_from_epoch
779  
780 This takes the parameters I<bind> and I<value> and returns a formatted C<TO_TIMESTAMP> expression.
781  
782 =head2 format_statement
783  
784 This method is called to format C<select>, C<delete> and C<insert> query.
785  
786 It takes the following parameters
787  
788 =over 4
789  
790 =item I<data>
791  
792 =item I<order>
793  
794 =item I<table>
795  
796 =back
797  
798 It uses the parameters passed to L<DB::Object::Query/select>, L<DB::Object::Query/delete> and L<DB::Object::Query/insert> and format them properly.
799  
800 If no arguments were passed to those query methods, it will use a default sorted columns instead.
801  
802 In list context, this returns the fields and values formatted as string, and in scalar context it returns the fields formatted.
803  
804 =head2 format_to_epoch
805  
806 This takes the parameters I<bind>, I<value> and I<quote> and returns a formatted expression to returns the epoch value out of the given field.
807  
808 =head2 having
809  
810 Calls L<DB::Object::Query/_where_having> to build a C<having> clause.
811  
812 =head2 limit
813  
814 Build a new L<DB::Object::Query::Clause> clause object by calling L</_process_limit> and return it.
815  
816 =head2 on_conflict
817  
818 Provided with some options and this will build a C<ON CONFLICT> clause (L<DB::Object::Query::Clause>). This is only available for PostgreSQL version 9.5 or above.
819  
820 =over 4
821  
822 =item C<action>
823  
824 Valid value can be C<nothing> and in which case, nothing will be done by the database upon conflict.
825  
826 INSERT INTO distributors (did, dname) VALUES (7, 'Redline GmbH')
827 ON CONFLICT (did) DO NOTHING;
828  
829 or
830  
831 INSERT INTO distributors (did, dname) VALUES (9, 'Antwerp Design')
832 ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;
833  
834 Value can also be C<ignore> instructing the database to simply ignore conflict.
835  
836 If the value is C<update>, then this will set a callback routine to format an update statement using L<DB::Object::Query/format_update>
837  
838 If the original C<insert> or C<update> uses placeholders, then the C<DO UPDATE> will also use the same placeholders and the L<DB::Object::Statement> object will act accordingly when being provided the binded values. That is, it will double them to allocate those binded value also for the C<DO UPDATE> part of the query.
839  
840 The callback will be called by L<DB::Object::Query/insert> or L<DB::Object::Query/update>, because the L</on_conflict> relies on query columns being previously set.
841  
842 =item C<fields>
843  
844 An array (or array object) of fields to use with I<action> set to C<update>
845  
846 $q->on_conflict({
847 target => 'name',
848 action => 'update,
849 fields => [qw( first_name last_name )],
850 });
851  
852 This will turn the C<DO UPDATE> prepending each field with the special keyword C<EXCLUDED>
853  
854 INSERT INTO distributors (did, dname)
855 VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
856 ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;
857  
858 =item C<target>
859  
860 Target can be a table column.
861  
862 $q->on_conflict({
863 target => 'name',
864 action => 'ignore',
865 });
866  
867 or it can also be a constraint name:
868  
869 $q->on_conflict({
870 target => 'on constraint my_table_idx_name',
871 action => 'ignore',
872 });
873  
874 Value for I<target> can also be a scalar reference and it will be used as-is
875  
876 $q->on_conflict({
877 target => \'on constraint my_table_idx_name',
878 action => 'ignore',
879 });
880  
881 Value for I<target> can also be an array or array object (like L<Module::Generic::Array>) and the array will be joined using a comma.
882  
883 If no I<target> argument was provided, then I<action> must be set to C<nothing> or this will return an error.
884  
885 =item C<where>
886  
887 You can also provide a C<WHERE> expression in the conflict and it will be added literally.
888  
889 $q->on_conflict({
890 target => 'did',
891 action => 'ignore',
892 where => 'is_active',
893 });
894  
895 INSERT INTO distributors (did, dname) VALUES (10, 'Conrad International')
896 ON CONFLICT (did) WHERE is_active DO NOTHING;
897  
898 =back
899  
900 See L<PostgreSQL documentation for more information|https://www.postgresql.org/docs/9.5/sql-insert.html>.
901  
902 =head2 reset
903  
904 If the object property C<query_reset> is not already set, this will remove the following properties from the current query object, set L<DB::Object::Query/enhance> to true and return the query object.
905  
906 Properties removed are: alias local binded binded_values binded_where binded_limit binded_group binded_having binded_order where limit group_by on_conflict _on_conflict order_by reverse from_unixtime unix_timestamp sorted
907  
908 =head2 reset_bind
909  
910 Reset all the following object properties to an anonymous array: binded binded_where binded_group binded_having binded_order binded_limit
911  
912 =head2 returning
913  
914 This feature is available with PostgreSQL version 8.2 or above, otherwise an error is returned.
915  
916 It expects a string that is used to build the C<RETURNING> clause.
917  
918 # will instruct the database to return all the table columns
919 $q->returning( '*' );
920  
921 or
922  
923 $q->returning( 'id' );
924  
925 But don't pass a reference:
926  
927 $q->returning( [qw( id name age )] );
928  
929 It returns a new L<DB::Object::Postgres::Query::Clause> object.
930  
931 See L<PostgreSQL documentation for more information|https://www.postgresql.org/docs/9.5/dml-returning.html>
932  
933 =head2 server_prepare
934  
935 Sets or gets the boolean value for whether you want the sql statement to be prepared server-side or not.
936  
937 Please see the warnings about this breaking change implemented since version 9.40 L<DBD::Pg/prepare>.
938  
939 Since PostgreSQL does not see the parameters that are passed at statement execution, it is possible it misinterpret. Consider this:
940  
941 my $ip = '192.168.2.12';
942 my $ip_tbl = $dbh->ip_registry;
943 # Check if the ip match an ip block
944 my $P = $dbh->placeholder( type => 'inet' );
945 $ip_tbl->where( $dbh->OR( $ip_tbl->fo->ip_addr == "INET $P", "INET $P" << $ip_tbl->fo->ip_addr ) );
946 $sth = $ip_tbl->select || die( "An error occurred while trying to format query to check if ip is in the registry." );
947 $sth->exec( $ip, $ip ) || die( "An error occurred while trying to execute query to check if ip is in the registry: ", $sth->error );
948  
949 This would yield the server error: C<syntax error at or near "$1">
950  
951 The solution would be to de-activate server prepare for this query only:
952  
953 $ip_tbl->query_object->server_prepare(0);
954  
955 =head2 _query_components
956  
957 This is called by the various query methods like L<DB::Object::Query/select>, L<DB::Object::Query/insert>, L<DB::Object::Query/update>, L<DB::Object::Query/delete>
958  
959 It will get the various query components (group, having, sort, order, limit) that have been set and add them formatted to an array that is returned.
960  
961 This version of L</_query_components> exists here to provide PostgreSQL specific implementation. See also the generic one in L<DB::Object::Query/_query_components>
962  
963 =head1 SEE ALSO
964  
965 L<perl>
966  
967 =head1 AUTHOR
968  
969 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
970  
971 =head1 COPYRIGHT & LICENSE
972  
973 Copyright (c) 2019-2021 DEGUEST Pte. Ltd.
974  
975 You can use, copy, modify and redistribute this package and associated
976 files under the same terms as Perl itself.
977  
978 =cut