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

filter: Statementstmt 0.0% 0 / 206 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 65 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 404 CC 50 SCAR 43.2
CC
50
Cov
0%
disable_trigger
110.0
dump
110.0
only
110.0
CRAP 75.3
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Postgres/Statement.pm
4 ## Version v0.302.0
5 ## Copyright(c) 2022 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2023/11/07
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 # This package's purpose is to automatically terminate the statement object and
16 # separate them from the connection object (DB::Object).
17 # Connection object last longer than statement objects
18 ##----------------------------------------------------------------------------
19 package DB::Object::Postgres::Statement;
20 BEGIN
21 {
22 use strict;
23 use warnings;
24 use parent qw( DB::Object::Statement DB::Object::Postgres );
25 use vars qw( $VERSION $DEBUG );
26 use DBD::Pg ':pg_types';
27 our $DEBUG = 0;
28 our $VERSION = 'v0.302.0';
29 };
30  
31 use strict;
32 use warnings;
33  
34 # NOTE: sub bind_param is inherited from DB::Object::Statement
35 # sub bind_param
36  
37 # sub commit is called by dbh, so it is in DB::Object::Postgres
38  
39 sub disable_trigger
40 {
41 my $self = shift( @_ );
42 my $opts = $self->_get_args_as_hash( @_ );
43 $opts->{all} //= 0;
44 $opts->{name} //= '';
45 my $query = $self->{query} ||
46 return( $self->error( "No query found to temporarily disable trigger." ) );
47 my $q = $self->query_object;
48 my $tables = $q->join_tables->length ? $q->join_tables : $self->new_array( $q->table_object );
49 my( $before, $after );
50 if( $tables->length > 1 )
51 {
52 $before = $tables->map(sub
53 {
54 my $tbl = shift( @_ );
55 return( 'ALTER TABLE ' . $tbl->name . ' DISABLE TRIGGER ' . ( $opts->{all} ? 'ALL' : 'USER' ) . ';' );
56 })->join( ' ' );
57 $after = $tables->map(sub
58 {
59 my $tbl = shift( @_ );
60 return( 'ALTER TABLE ' . $tbl->name . ' ENABLE TRIGGER ' . ( $opts->{all} ? 'ALL' : 'USER' ) . ';' );
61 })->join( ' ' );
62 }
63 else
64 {
65 my $tbl = $q->table_object;
66 $before = 'ALTER TABLE ' . $tbl->name . ' DISABLE TRIGGER ' . ( $opts->{name} ? $opts->{name} : $opts->{all} ? 'ALL' : 'USER' ) . ';';
67 $after = 'ALTER TABLE ' . $tbl->name . ' ENABLE TRIGGER ' . ( $opts->{name} ? $opts->{name} : $opts->{all} ? 'ALL' : 'USER' ) . ';';
68 }
69 my $new = "${before} ${query}; ${after}";
70 $q->query( $new );
71 my $sth = $self->table_object->_cache_this( $q ) ||
72 return( $self->error( "Error while preparing new query temporarily disabling triggers:\n$new" ) );
73 if( !defined( wantarray() ) )
74 {
75 $sth->execute() ||
76 return( $self->error( "Error while executing new query temporarily disabling triggers:\n$new" ) );
77 }
78 return( $sth );
79 }
80  
81 # Customised for Postgres
82 sub distinct
83 {
84 my $self = shift( @_ );
85 my $what = @_ > 1 ? join( ', ', @_ ) : shift( @_ );
86 my $query = $self->{query} ||
87 return( $self->error( "No query to set as to be ignored." ) );
88  
89 my $type = uc( ( $query =~ /^\s*(\S+)\s+/ )[ 0 ] );
90 # ALTER for table alteration statements (DB::Object::Tables
91 my @allowed = qw( SELECT );
92 my $allowed = CORE::join( '|', @allowed );
93 if( !scalar( grep{ /^$type$/i } @allowed ) )
94 {
95 return( $self->error( "You may not flag statement of type \U$type\E to be distinct:\n$query" ) );
96 }
97 # Incompatible. Do not bother going further
98 return( $self ) if( $query =~ /^[[:blank:]]*(?:$allowed)[[:blank:]]+(?:DISTINCT|ALL)[[:blank:]]+/i );
99 my $clause = defined( $what ) ? "DISTINCT ON ($what)" : "DISTINCT";
100  
101 $query =~ s/^([[:blank:]]*)($allowed)([[blank:]]+)/$1$2 $clause /;
102 # my $sth = $self->prepare( $query ) ||
103 # $self->{ 'query' } = $query;
104 # saving parameters to bind later on must have been done previously
105 my $sth = $self->_cache_this( $query ) ||
106 return( $self->error( "Error while preparing new ignored query:\n$query" ) );
107 if( !defined( wantarray() ) )
108 {
109 $sth->execute ||
110 return( $self->error( "Error while executing new ignored query:\n$query" ) );
111 }
112 return( $sth );
113 }
114  
115 # Customised for Postgres
116 sub dump
117 {
118 my $self = shift( @_ );
119 my $args = $self->_get_args_as_hash( @_ );
120 my $vsep = ",";
121 my $hsep = "\n";
122 my $width = 35;
123 $self->_load_class( 'IO::File' ) || return( $self->pass_error );
124 my $fh = IO::File->new;
125 $fh->fdopen( fileno( STDOUT ), "w" );
126 $vsep = $args->{vsep} if( exists( $args->{vsep} ) );
127 $hsep = $args->{hsep} if( exists( $args->{hsep} ) );
128 $width = $args->{width} if( exists( $args->{width} ) );
129 my @fields = ();
130 # my $fields_ref = $self->{sth}->FETCH( 'NAME' );
131 my $fields_ref = $self->{sth}->{NAME};
132 if( defined( $fields_ref ) && ref( $fields_ref ) eq 'ARRAY' )
133 {
134 @fields = @$fields_ref;
135 }
136 else
137 {
138 return( $self->error( "No array reference of fields could be retrieved from statement '$self->{sth}'." ) );
139 }
140 return( $self->error( "No query to dump." ) ) if( !exists( $self->{sth} ) );
141 if( exists( $args->{file} ) )
142 {
143 $self->_load_class( 'DateTime' ) || return( $self->pass_error );
144 # new_file is inherited from Module::Generic and calls Module::Generic::File
145 my $file = $self->new_file( $args->{file} );
146 $fh = $file->open( '>', { binmode => 'utf8' }) ||
147 return( $self->error( "Unable to open file $file in write mode: ", $file->error ) );
148 # my @header = sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields );
149 my @header = sort{ $a <=> $b } @fields;
150 my $date = DateTime->now;
151 my $table = $self->{table};
152 $fh->printf( "# Generated on %s for table $table\n", $date->strftime( '%c' ) );
153 $fh->print( "# ", CORE::join( "\t", @header ), "\n" );
154 my @data = ();
155 while( @data = $self->fetchrow() )
156 {
157 $fh->print( CORE::join( "\t", @data ), "\n" );
158 }
159 $fh->close();
160 $self->finish();
161 return( $self );
162 }
163 elsif( exists( $args->{fh} ) )
164 {
165 if( !fileno( $args->{fh} ) )
166 {
167 return( $self->error( "The file descriptor provided does not seem to be valid (not open)" ) );
168 }
169 $fh = IO::File->new_from_fd( $args->{fh}, 'w' ) || return( $self->error( $! ) );
170 }
171 my $max = 0;
172 # foreach my $field ( keys( %$fields ) )
173 foreach my $field ( @fields )
174 {
175 $max = length( $field ) if( length( $field ) > $max );
176 }
177 my $template = '';
178 # foreach my $field ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) )
179 foreach my $field ( @fields )
180 {
181 $template .= "$field" . ( '.' x ( $max - length( $field ) ) ) . ": %s\n";
182 }
183 $template .= "\n";
184 my @data = ();
185 while( @data = $self->fetchrow )
186 {
187 $fh->printf( $template, @data );
188 }
189 $self->finish;
190 return( $self );
191 }
192  
193 # NOTE: sub execute is inherited from DB::Object::Statement
194 # sub execute
195  
196 # NOTE: sub executed is inherited from DB::Object::Statement
197 # sub executed
198  
199 # NOTE: sub fetchall_arrayref is inherited from DB::Object::Statement
200 # sub fetchall_arrayref($@)
201  
202 # NOTE: sub fetchcol is inherited from DB::Object::Statement
203 # sub fetchcol($;$)
204  
205 # NOTE: sub fetchhash is inherited from DB::Object::Statement
206 # sub fetchhash(@)
207  
208 # NOTE: sub fetchrow is inherited from DB::Object::Statement
209 # sub fetchrow(@)
210  
211 # NOTE: field_types -> TYPE
212 # <https://metacpan.org/pod/DBI#TYPE>
213 sub field_types { return( shift->_get_statement_attribute( 'pg_type' ) ); }
214  
215 # NOTE: sub finish is inherited from DB::Object::Statement
216 # sub finish
217  
218 sub ignore
219 {
220 return( shift->error( "INSERT | UPDATE | ALTER IGNORE is not supported by Postgres." ) );
221 }
222  
223 # NOTE: sub join is inherited from DB::Object::Statement
224 # sub join
225  
226 # NOTE: sub object is inherited from DB::Object::Statement
227 # sub object
228  
229 sub last_insert_id
230 {
231 my $self = shift( @_ );
232 return( $self->database_object->last_insert_id( undef(), undef(), $self->table_object->name, undef() ) );
233 }
234  
235 sub name
236 {
237 my $self = shift( @_ );
238 if( @_ )
239 {
240 $self->{sth}->{pg_prepare_name} = shift( @_ );
241 }
242 return( $self->{sth}->{pg_prepare_name} );
243 }
244  
245 sub only
246 {
247 my $self = shift( @_ );
248 my $q = $self->query_object || return( $self->error( "No query formatter object was set" ) );
249 my $table = $self->{table} || $q->table_object->name ||
250 return( $self->error( "No table provided to perform select statement." ) );
251 my $tbl_o = $q->table_object || $self->{table_object} || return( $self->error( "No table object is set." ) );
252 my $db = $tbl_o->database();
253 my $multi_db = $tbl_o->param( 'multi_db' );
254 my $type = uc( ( $self->{query} =~ /^(SELECT|DELETE|INSERT|UPDATE)\b/i )[0] );
255 my @query = ();
256 if( $type eq 'SELECT' )
257 {
258 my $fields = $q->selected_fields;
259 @query = $multi_db ? ( "SELECT $fields FROM ONLY $db.$table" ) : ( "SELECT $fields FROM ONLY $table" );
260 }
261 elsif( $type eq 'DELETE' )
262 {
263 @query = $multi_db ? ( "DELETE FROM ONLY $db.$table" ) : ( "DELETE FROM ONLY $table" );
264 }
265 elsif( $type eq 'UPDATE' )
266 {
267 my $qv = $q->query_values ||
268 return( $self->error( "Something went wrong. No query values found. Please investigate." ) );
269 return( $self->error( "I was expecting a scalar reference for uery values, but got instead '$qv'." ) ) if( !$self->_is_scalar( $qv ) );
270 my $values = $$qv;
271 @query = ( "UPDATE ONLY $table SET $values" );
272 }
273 # Other type such as INSERT or TRUNCATE are not applicable, so we just ignore if we were ever called by mistake.
274 else
275 {
276 return( $self );
277 }
278 my $clauses = $q->_query_components;
279 push( @query, @$clauses ) if( @$clauses );
280 my $query = $q->{query} = CORE::join( ' ', @query );
281 my $sth = $tbl_o->_cache_this( $q );
282 if( !defined( $sth ) )
283 {
284 return( $self->error( "Error while preparing query to select on table '$self->{table}':\n$query", $self->errstr() ) );
285 }
286 if( !defined( wantarray() ) )
287 {
288 $sth->execute ||
289 return( $self->error( "Error while executing query to select:\n", $self->as_string(), $sth->errstr() ) );
290 }
291 return( $sth );
292 }
293  
294 sub priority
295 {
296 return( shift->error( "Priority is not supported in Postgres." ) );
297 }
298  
299 # rollback is called using the dbh handler and is located in DB::Object::Postgres
300  
301 # NOTE: sub rows is inherited from DB::Object::Statement
302 # sub rows(@)
303  
304 # NOTE: sub undo is inherited from DB::Object::Statement
305 # sub undo
306  
307 # Does nothing in Postgres. This is a Mysql feature
308 sub wait
309 {
310 return( shift( @_ ) );
311 }
312  
313 sub _convert_datetime2object
314 {
315 my $self = shift( @_ );
316 my $opts = $self->_get_args_as_hash( @_ );
317 my $sth = $opts->{statement} || return( $self->error( "No statement handler was provided to convert data from json to perl." ) );
318 # my $data = $opts->{data} || return( $self->error( "No data was provided to convert from json to perl." ) );
319 return( $opts->{data} ) if( !CORE::length( $opts->{data} ) );
320 return( $opts->{data} ) if( !$sth->rows );
321 my $data = $opts->{data};
322 # my $names = $sth->FETCH('NAME');
323 # my $types = $sth->FETCH('pg_type');
324 # Get the cached field names and types that we stored after executing the query, but before we finished reading the statement
325 my $names = $self->_cache_field_names;
326 my $types = $self->_cache_field_types;
327 my $mode = ref( $data );
328  
329 for( my $i = 0; $i < scalar( @$names ); $i++ )
330 {
331 if( $types->[$i] eq PG_DATE ||
332 $types->[$i] eq PG_TIMESTAMP ||
333 $types->[$i] eq 'date' ||
334 $types->[$i] eq 'timestamp' )
335 {
336 if( $mode eq 'ARRAY' )
337 {
338 for( my $j = 0; $j < scalar( @$data ); $j++ )
339 {
340 next if( !$data->[ $j ]->{ $names->[ $i ] } );
341 my $dt = $self->_convert_string2datetime( $data->[ $j ]->{ $names->[ $i ] } );
342 if( !defined( $dt ) )
343 {
344 warn( $self->error );
345 }
346 $data->[ $j ]->{ $names->[ $i ] } = $dt;
347 }
348 }
349 elsif( $mode eq 'HASH' )
350 {
351 next if( !$data->{ $names->[ $i ] } );
352 my $dt = $self->_convert_string2datetime( $data->{ $names->[ $i ] } );
353 if( !defined( $dt ) )
354 {
355 warn( $self->error );
356 }
357 $data->{ $names->[ $i ] } = $dt;
358 }
359 }
360 }
361 return( $data );
362 }
363  
364 sub _convert_json2hash
365 {
366 my $self = shift( @_ );
367 my $opts = $self->_get_args_as_hash( @_ );
368 # $self->debug( 3 );
369 # my( $pack, $file, $line ) = caller( 1 );
370 # my $sub = ( caller( 2 ) )[3];
371 # $data can be either hash pr array
372 my $sth = $opts->{statement} || return( $self->error( "No statement handler was provided to convert data from json to perl." ) );
373 # my $data = $opts->{data} || return( $self->error( "No data was provided to convert from json to perl." ) );
374 return( $opts->{data} ) if( !CORE::length( $opts->{data} ) );
375 my $data = $opts->{data};
376 # my $names = $sth->FETCH('NAME');
377 # my $types = $sth->FETCH('pg_type');
378 my $names = $self->_cache_field_names;
379 my $types = $self->_cache_field_types;
380 my $mode = ref( $data );
381 for( my $i = 0; $i < scalar( @$names ); $i++ )
382 {
383 if( $types->[$i] eq PG_JSON || $types->[$i] eq PG_JSONB || $types->[$i] eq 'json' || $types->[$i] eq 'jsonb' )
384 {
385 if( $self->_is_array( $data ) )
386 {
387 for( my $j = 0; $j < scalar( @$data ); $j++ )
388 {
389 next if( !$data->[ $j ]->{ $names->[ $i ] } );
390 my $ref = $self->_decode_json( $data->[ $j ]->{ $names->[ $i ] } );
391 $data->[ $j ]->{ $names->[ $i ] } = $ref if( $ref );
392 }
393 }
394 elsif( $self->_is_hash( $data => 'strict' ) )
395 {
396 my $ref = $self->_decode_json( $data->{ $names->[ $i ] } );
397 $data->{ $names->[ $i ] } = $ref if( $ref );
398 }
399 }
400 }
401 return( $data );
402 }
403  
404 # NOTE: DESTROY
405 DESTROY
406 {
407 # Do nothing but existing so it is handled by this package
408 # print( STDERR "DESTROY'ing statement $self ($self->{ 'query' })\n" );
409 };
410  
411 1;
412 # NOTE: POD
413 __END__
414  
415 =encoding utf-8
416  
417 =head1 NAME
418  
419 DB::Object::Postgres::Statement - PostgreSQL Statement Object
420  
421 =head1 SYNOPSIS
422  
423 use DB::Object::Postgres::Statement;
424 my $this = DB::Object::Postgres::Statement->new ||
425 die( DB::Object::Postgres::Statement->error, "\n" );
426  
427 =head1 VERSION
428  
429 v0.302.0
430  
431 =head1 DESCRIPTION
432  
433 This is a PostgreSQL specific statement object class. It inherits from L<DB::Object::Statement>
434  
435 =head1 METHODS
436  
437 =head2 disable_trigger
438  
439 Provided some hash or hash reference of options and this will modify the current query to temporarily disable trigger and return a new statement handler object.
440  
441 If it is called in void context, then the statement is executed immediately and returned, otherwise it is just returned.
442  
443 For example, let's say you have a table C<properties> and you do not want properties to be removed, but instead marked as C<deleted> and to achieve that you create a table trigger that is triggered B<before> the C<delete> query is executed and does instead an C<update> setting the property C<status> to C<deleted>.
444  
445 CREATE TABLE properties (
446 id SERIAL NOT NULL
447 ,name VARCHAR(255) NOT NULL
448 ,status VARCHAR(12) NOT NULL DEFAULT 'active'
449 ,CONSTRAINT pk_properties PRIMARY KEY(id)
450 ,CONSTRAINT idx_properties UNIQUE(name)
451 );
452  
453 CREATE OR REPLACE FUNCTION f_properties_table() RETURNS TRIGGER AS $$
454 BEGIN
455 UPDATE properties SET status = 'deleted' WHERE name = OLD.name;
456 -- To prevent the original query from being executed
457 RETURN NULL;
458 END;
459 $$ LANGUAGE 'plpgsql';
460  
461 DROP TRIGGER IF EXISTS t_properties_table ON properties;
462 CREATE TRIGGER t_properties_table
463 BEFORE DELETE ON properties
464 FOR EACH ROW EXECUTE PROCEDURE f_properties_table();
465  
466 If you issued a query like:
467  
468 $tbl->insert( name => 'max_connections', status => 'active' );
469  
470 And then, to remove it:
471  
472 $tbl->where( $tbl->fo->name == 'max_connections' );
473 $tbl->delete;
474  
475 The trigger will prevent that property from being removed and instead the row's status will be changed to C<deleted>, but if you B<really> wanted to force remove that property, you would do:
476  
477 $tbl->where( $tbl->fo->name == 'max_connections' );
478 $tbl->delete->disable_trigger;
479  
480 And this would execute the following query:
481  
482 ALTER TABLE properties DISABLE TRIGGER USER; DELETE FROM properties WHERE name = 'max_connections'; ALTER TABLE properties ENABLE TRIGGER USER;
483  
484 =head2 distinct
485  
486 Provided with an optional column and called upon a C<SELECT> query and this will modify the query to add the keyword C<DISTINCT>
487  
488 $sth->distinct;
489 # produces SELECT DISTINCT....
490 $sth->distinct( 'name' );
491 # produces SELECT DISTINCT ON (name)....
492  
493 =head2 dump
494  
495 This will dump the result of the query to STDOUT or to a file if I<file> argument is provided, or if a filehandle is provided with I<fh>, it will be used to print out the data.
496  
497 It takes also a I<vsep>, which defaults to a command and a I<hsep> which defaults to a new line.
498  
499 It returns the current object.
500  
501 =for Pod::Coverage field_types
502  
503 =head2 ignore
504  
505 This returns an error as C<INSERT> | C<UPDATE> | C<ALTER IGNORE> is not supported by PostgreSQL.
506  
507 =head2 last_insert_id
508  
509 Will call L<DB::Object/last_insert_id> with the necessary parameters to get the last inserted table id.
510  
511 =head2 name
512  
513 Sets or gets the name of the prepared statement. The name set will show up in the PostgreSQL server log.
514  
515 See L<DBD::Pg/prepare>
516  
517 =head2 only
518  
519 Upon being called, this will add the keyword C<ONLY> to the query.
520  
521 If the original query type is C<SELECT>, this will become something like:
522  
523 SELECT some_columns, other FROM ONLY some_table
524  
525 For C<DELETE> query it would be like:
526  
527 DELETE FROM ONLY some_table
528  
529 For C<UPDATE> query, it would look like:
530  
531 UPDATE ONLY some_table
532  
533 It returns the current statement object.
534  
535 See L<PostgreSQL documentation for more information|https://www.postgresql.org/docs/9.5/sql-select.html>
536  
537 =head2 priority
538  
539 This is unsupported under PostgreSQL and if used returns an error.
540  
541 =head2 wait
542  
543 This is unsupported under PostgreSQL and it will be silently ignore, returning the current object.
544  
545 =head1 SEE ALSO
546  
547 L<DB::Object::Statement>, L<DB::Object>, L<DB::Object::Postgres::Query>
548  
549 =head1 AUTHOR
550  
551 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
552  
553 =head1 COPYRIGHT & LICENSE
554  
555 Copyright (c) 2019-2023 DEGUEST Pte. Ltd.
556  
557 You can use, copy, modify and redistribute this package and associated
558 files under the same terms as Perl itself.
559  
560 =cut