lib/DB/Object/Postgres.pm

filter: Statementstmt 81.4% 22 / 27 Branchbran 50.0% 1 / 2 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 83.3% 30 / 36 CC 2 SCAR 2.3
CC
2
Cov
79%
BEGIN
2.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.3
« blib/lib/DB/Object/Fields/Overloaded.pm ↑ Summary lib/DB/Object/Fields/Overloaded.pm »
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib//mnt/src/perl/DB-Object/lib/DB/Object/Postgres.pm
4 ## Version v1.6.0
5 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/09/23
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 # This is the subclassable module for driver specific ones.
15 package DB::Object::Postgres;
16 BEGIN
17 1 ▶{
Subroutine BEGIN: called CC=2 SCAR=7.1
18 1 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 warnings::register_categories( 'DB::Object' );
21 1 ▶ use parent qw( DB::Object );
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶ use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶ use vars qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
24 $VERSION
25 $DEBUG $ERROR $MOD_PERL $USE_BIND $USE_CACHE
26 $PLACEHOLDER_REGEXP $DATATYPES_DICT $EXCEPTION_CLASS
27 1 );
28 1 ▶ use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 eval
30 1 {
31 1 require DBD::Pg;
32 0 DBD::Pg->import( ':pg_types' );
33 };
34 1 ▶ die( $@ ) if( $@ );
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 0 1
35 # the 'constant' property in the dictionary hash is added in structure()
36 # <https://www.postgresql.org/docs/13/datatype.html>
37 0 our $DATATYPES_DICT =
38 {
39 bit => {
40 constant => '',
41 is_array => 0,
42 name => 'PG_BIT',
43 re => qr/^bit(?!>\s+varying)/,
44 type => 'bit',
45 },
46 bool => {
47 alias => [qw( boolean )],
48 constant => '',
49 is_array => 0,
50 name => 'PG_BOOL',
51 re => qr/^(boolean|bool)\b/,
52 type => 'bool',
53 },
54 box => {
55 constant => '',
56 is_array => 0,
57 name => 'PG_BOX',
58 re => qr/^box\b/,
59 type => 'box',
60 },
61 bpchar => {
62 constant => '',
63 is_array => 0,
64 name => 'PG_BPCHAR',
65 re => qr/^bpchar\b/,
66 type => 'bpchar',
67 },
68 bytea => {
69 constant => '',
70 is_array => 0,
71 name => 'PG_BYTEA',
72 re => qr/^bytea\b/ ,
73 type => 'bytea',
74 },
75 # Even if the table field type is CHAR, we use PG_VARCHAR, because PG_CHAR is for a single character, and if we used it, it would truncate the data to one character.
76 # <https://github.com/bucardo/dbdpg/issues/103>
77 char => {
78 alias => [qw( character char )],
79 constant => '',
80 is_array => 0,
81 name => 'PG_VARCHAR',
82 re => qr/^(character|char)\b(?![[:blank:]]+varying)/,
83 type => 'char',
84 },
85 cid => {
86 constant => '',
87 is_array => 0,
88 name => 'PG_CID',
89 re => qr/^cid\b/ ,
90 type => 'cid',
91 },
92 cidr => {
93 constant => '',
94 is_array => 0,
95 name => 'PG_CIDR',
96 re => qr/^cidr\b/ ,
97 type => 'cidr',
98 },
99 circle => {
100 constant => '',
101 is_array => 0,
102 name => 'PG_CIRCLE',
103 re => qr/^circle\b/,
104 type => 'circle',
105 },
106 cstring => {
107 constant => '',
108 is_array => 0,
109 name => 'PG_CSTRING',
110 re => qr/^cstring\b/,
111 type => 'cstring',
112 },
113 date => {
114 constant => '',
115 is_array => 0,
116 name => 'PG_DATE',
117 re => qr/^date\b/,
118 type => 'date',
119 },
120 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
121 datemultirange => {
122 constant => '',
123 is_array => 0,
124 name => 'PG_DATEMULTIRANGE',
125 re => qr/^(datemultirange)\b/,
126 type => 'datemultirange',
127 },
128 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
129 daterange => {
130 constant => '',
131 is_array => 0,
132 name => 'PG_DATERANGE',
133 re => qr/^(daterange)\b/,
134 type => 'daterange',
135 },
136 float4 => {
137 alias => [qw( real )],
138 constant => '',
139 is_array => 0,
140 name => 'PG_FLOAT4',
141 re => qr/^(real|float4)\b/,
142 type => 'float4',
143 },
144 float8 => {
145 alias => ['double', 'double precision'],
146 constant => '',
147 is_array => 0,
148 name => 'PG_FLOAT8',
149 re => qr/^(double precision|float8)\b/,
150 type => 'float8',
151 },
152 inet => {
153 constant => '',
154 is_array => 0,
155 name => 'PG_INET',
156 re => qr/^inet\b/,
157 type => 'inet',
158 },
159 int2vector => {
160 constant => '',
161 is_array => 0,
162 name => 'PG_INT2VECTOR',
163 re => qr/^(int2vector)\b/,
164 type => 'int2vector',
165 },
166 int2 => {
167 alias => [qw( smallint smallserial serial2 )],
168 constant => '',
169 is_array => 0,
170 name => 'PG_INT2',
171 re => qr/^(smallint|int2|smallserial|serial2)\b/,
172 type => 'int2',
173 },
174 int4 => {
175 alias => [qw( integer int serial serial4 )],
176 constant => '',
177 is_array => 0,
178 name => 'PG_INT4',
179 re => qr/^(integer|int|int4|serial|serial4)\b/,
180 type => 'int4',
181 },
182 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
183 int4multirange => {
184 constant => '',
185 is_array => 0,
186 name => 'PG_INT4MULTIRANGE',
187 re => qr/^(int4multirange)\b/,
188 type => 'int4multirange',
189 },
190 int4range => {
191 constant => '',
192 is_array => 0,
193 name => 'PG_INT4RANGE',
194 re => qr/^(int4range)\b/,
195 type => 'int4range',
196 },
197 int8 => {
198 alias => [qw( bigint bigserial serial8 )],
199 constant => '',
200 is_array => 0,
201 name => 'PG_INT8',
202 re => qr/^(bigint|int8|bigserial|serial8)\b/,
203 type => 'int8',
204 },
205 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
206 int8multirange => {
207 constant => '',
208 is_array => 0,
209 name => 'PG_INT8MULTIRANGE',
210 re => qr/^(int8multirange)\b/,
211 type => 'int8multirange',
212 },
213 int8range => {
214 constant => '',
215 is_array => 0,
216 name => 'PG_INT8RANGE',
217 re => qr/^(int8range)\b/,
218 type => 'int8range',
219 },
220 interval => {
221 constant => '',
222 is_array => 0,
223 name => 'PG_INTERVAL',
224 re => qr/^interval\b/,
225 type => 'interval',
226 },
227 json => {
228 constant => '',
229 is_array => 0,
230 name => 'PG_JSON',
231 re => qr/^json\b/,
232 type => 'json',
233 },
234 jsonb => {
235 constant => '',
236 is_array => 0,
237 name => 'PG_JSONB',
238 re => qr/^jsonb\b/,
239 type => 'jsonb',
240 },
241 # <https://www.postgresql.org/docs/current/datatype-json.html#DATATYPE-JSONPATH>
242 jsonpath => {
243 constant => '',
244 is_array => 0,
245 name => 'PG_JSONPATH',
246 re => qr/^jsonpath\b/,
247 type => 'jsonpath',
248 },
249 line => {
250 constant => '',
251 is_array => 0,
252 name => 'PG_LINE',
253 re => qr/^line\b/,
254 type => 'line',
255 },
256 lseg => {
257 constant => '',
258 is_array => 0,
259 name => 'PG_LSEG',
260 re => qr/^lseg\b/,
261 type => 'lseg',
262 },
263 macaddr => {
264 constant => '',
265 is_array => 0,
266 name => 'PG_MACADDR',
267 re => qr/^macaddr\b/,
268 type => 'macaddr',
269 },
270 macaddr8 => {
271 constant => '',
272 is_array => 0,
273 name => 'PG_MACADDR8',
274 re => qr/^macaddr8\b/,
275 type => 'macaddr8',
276 },
277 money => {
278 constant => '',
279 is_array => 0,
280 name => 'PG_MONEY',
281 re => qr/^money\b/,
282 type => 'money',
283 },
284 numeric => {
285 alias => [qw( decimal )],
286 constant => '',
287 is_array => 0,
288 name => 'PG_NUMERIC',
289 re => qr/^(numeric|decimal)\b/,
290 type => 'numeric',
291 },
292 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
293 nummultirange => {
294 constant => '',
295 is_array => 0,
296 name => 'PG_NUMMULTIRANGE',
297 re => qr/^(nummultirange)\b/,
298 type => 'nummultirange',
299 },
300 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
301 numrange => {
302 constant => '',
303 is_array => 0,
304 name => 'PG_NUMRANGE',
305 re => qr/^(numrange)\b/,
306 type => 'numrange',
307 },
308 oid => {
309 constant => '',
310 is_array => 0,
311 name => 'PG_OID',
312 re => qr/^(oid)\b/,
313 type => 'oid',
314 },
315 path => {
316 constant => '',
317 is_array => 0,
318 name => 'PG_PATH',
319 re => qr/^path\b/,
320 type => 'path',
321 },
322 pg_lsn => {
323 constant => '',
324 is_array => 0,
325 name => 'PG_PG_LSN',
326 re => qr/^pg_lsn\b/,
327 type => 'pg_lsn',
328 },
329 point => {
330 constant => '',
331 is_array => 0,
332 name => 'PG_POINT',
333 re => qr/^point\b/,
334 type => 'point',
335 },
336 polygon => {
337 constant => '',
338 is_array => 0,
339 name => 'PG_POLYGON',
340 re => qr/^polygon\b/,
341 type => 'polygon',
342 },
343 text => {
344 constant => '',
345 is_array => 0,
346 name => 'PG_TEXT',
347 re => qr/^text\b/,
348 type => 'text',
349 },
350 time => {
351 constant => '',
352 is_array => 0,
353 name => 'PG_TIME',
354 re => qr/^time(\([^\)]+\))?\s+without\s+time\s+zone/,
355 type => 'time',
356 },
357 timestamp => {
358 constant => '',
359 is_array => 0,
360 name => 'PG_TIMESTAMP',
361 re => qr/^timestamp(\([^\)]+\))?\s+without\s+time\s+zone/,
362 type => 'timestamp',
363 },
364 timestamptz => {
365 constant => '',
366 is_array => 0,
367 name => 'PG_TIMESTAMPTZ',
368 re => qr/^(timestamp(\([^\)]+\))?\s+with\s+time\s+zone)|timestamptz/,
369 type => 'timestamptz',
370 },
371 timetz => {
372 constant => '',
373 is_array => 0,
374 name => 'PG_TIMETZ',
375 re => qr/^(time(\([^\)]+\))?\s+with\s+time\s+zone)|timetz/,
376 type => 'timetz',
377 },
378 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
379 tsmultirange => {
380 constant => '',
381 is_array => 0,
382 name => 'PG_TSMULTIRANGE',
383 re => qr/^tsmultirange\b/,
384 type => 'tsmultirange',
385 },
386 tsquery => {
387 constant => '',
388 is_array => 0,
389 name => 'PG_TSQUERY',
390 re => qr/^tsquery\b/,
391 type => 'tsquery',
392 },
393 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
394 tsrange => {
395 constant => '',
396 is_array => 0,
397 name => 'PG_TSRANGE',
398 re => qr/^tsrange\b/,
399 type => 'tsrange',
400 },
401 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
402 tstzmultirange => {
403 constant => '',
404 is_array => 0,
405 name => 'PG_TSTZMULTIRANGE',
406 re => qr/^tstzmultirange\b/,
407 type => 'tstzmultirange',
408 },
409 # <https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-BUILTIN>
410 tstzrange => {
411 constant => '',
412 is_array => 0,
413 name => 'PG_TSTZRANGE',
414 re => qr/^tstzrange\b/,
415 type => 'tstzrange',
416 },
417 tsvector => {
418 constant => '',
419 is_array => 0,
420 name => 'PG_TSVECTOR',
421 re => qr/^tsvector\b/,
422 type => 'tsvector',
423 },
424 txid_snapshot => {
425 constant => '',
426 is_array => 0,
427 name => 'PG_TXID_SNAPSHOT',
428 re => qr/^txid_snapshot\b/,
429 type => 'txid_snapshot',
430 },
431 uuid => {
432 constant => '',
433 is_array => 0,
434 name => 'PG_UUID',
435 re => qr/^uuid\b/,
436 type => 'uuid',
437 },
438 varbit => {
439 alias => ['bit varying'],
440 constant => '',
441 is_array => 0,
442 name => 'PG_VARBIT',
443 re => qr/^(bit\s+varying|varbit)\b/,
444 type => 'varbit',
445 },
446 varchar => {
447 alias => [qw( varchar ), 'character varying'],
448 constant => '',
449 is_array => 0,
450 name => 'PG_VARCHAR',
451 re => qr/^(character varying|varchar)\b/,
452 type => 'varchar',
453 },
454 xml => {
455 constant => '',
456 is_array => 0,
457 name => 'PG_XML',
458 re => qr/^xml\b/,
459 type => 'xml',
460 },
461 };
462 0 our $PLACEHOLDER_REGEXP = qr/(?:(?<![?\w])\?(?![?\w])|(?<!\w)\$(?<index>[1-9]\d*)(?!\w))/;
463 0 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
464 0 our $VERSION = 'v1.6.0';
465 };
466  
467 use strict;
468 use warnings;
469 # require DB::Object::Postgres::Statement;
470 # require DB::Object::Postgres::Tables;
471 # require DB::Object::Postgres::Lo;
472 our $DEBUG = 0;
473 our $USE_BIND = 0;
474 our $USE_CACHE = 0;
475 our $MOD_PERL = 0;
476 if( $INC{ 'Apache/DBI.pm' } &&
477 substr( $ENV{ 'GATEWAY_INTERFACE' } || '', 0, 8 ) eq 'CGI-Perl' )
478 {
479 $MOD_PERL++;
480 }
481 foreach my $type ( keys( %$DATATYPES_DICT ) )
482 {
483 if( CORE::exists( $DATATYPES_DICT->{ $type }->{alias} ) &&
484 ref( $DATATYPES_DICT->{ $type }->{alias} ) eq 'ARRAY' &&
485 scalar( @{$DATATYPES_DICT->{ $type }->{alias}} ) )
486 {
487 foreach my $alias ( @{$DATATYPES_DICT->{ $type }->{alias}} )
488 {
489 next if( CORE::exists( $DATATYPES_DICT->{ $alias } ) );
490 $DATATYPES_DICT->{ $alias } = $DATATYPES_DICT->{ $type };
491 }
492 }
493 }
494  
495 my $keys = $DBD::Pg::EXPORT_TAGS{pg_types};
496 my @constants_to_ignore = qw(
497 PG_ASYNC PG_OLDQUERY_CANCEL PG_OLDQUERY_WAIT PG_ACLITEM PG_ACLITEMARRAY PG_ANY
498 PG_ANYARRAY PG_ANYCOMPATIBLE PG_ANYCOMPATIBLEARRAY PG_ANYCOMPATIBLEMULTIRANGE
499 PG_ANYCOMPATIBLENONARRAY PG_ANYCOMPATIBLERANGE PG_ANYELEMENT PG_ANYENUM PG_ANYMULTIRANGE
500 PG_ANYNONARRAY PG_ANYRANGE PG_EVENT_TRIGGER PG_FDW_HANDLER PG_GTSVECTOR
501 PG_GTSVECTORARRAY PG_INDEX_AM_HANDLER PG_INTERNAL PG_LANGUAGE_HANDLER PG_NAME
502 PG_NAMEARRAY PG_OID8 PG_OID8ARRAY PG_OIDVECTOR PG_OIDVECTORARRAY PG_PG_ATTRIBUTE
503 PG_PG_ATTRIBUTEARRAY PG_PG_BRIN_BLOOM_SUMMARY PG_PG_BRIN_MINMAX_MULTI_SUMMARY
504 PG_PG_CLASS PG_PG_CLASSARRAY PG_PG_DDL_COMMAND PG_PG_DEPENDENCIES PG_PG_MCV_LIST
505 PG_PG_NDISTINCT PG_PG_NODE_TREE PG_PG_PROC PG_PG_PROCARRAY PG_PG_SNAPSHOT
506 PG_PG_SNAPSHOTARRAY PG_PG_TYPE PG_PG_TYPEARRAY PG_RECORD PG_RECORDARRAY PG_REFCURSOR
507 PG_REFCURSORARRAY PG_REGCLASS PG_REGCLASSARRAY PG_REGCOLLATION PG_REGCOLLATIONARRAY
508 PG_REGCONFIG PG_REGCONFIGARRAY PG_REGDATABASE PG_REGDATABASEARRAY PG_REGDICTIONARY
509 PG_REGDICTIONARYARRAY PG_REGNAMESPACE PG_REGNAMESPACEARRAY PG_REGOPER PG_REGOPERARRAY
510 PG_REGOPERATOR PG_REGOPERATORARRAY PG_REGPROC PG_REGPROCARRAY PG_REGPROCEDURE
511 PG_REGPROCEDUREARRAY PG_REGROLE PG_REGROLEARRAY PG_REGTYPE PG_REGTYPEARRAY
512 PG_TABLE_AM_HANDLER PG_TID PG_TIDARRAY PG_TRIGGER PG_TSM_HANDLER PG_UNKNOWN PG_VOID
513 PG_XID PG_XID8 PG_XID8ARRAY PG_XIDARRAY
514 );
515 foreach my $c ( @$keys )
516 {
517 next if( scalar( grep( /^$c$/, @constants_to_ignore ) ) );
518 if( $c =~ /^PG_(\w+)$/ )
519 {
520 my $type = lc( $1 );
521 my $is_array = 0;
522 if( substr( $type, -5 ) eq 'array' )
523 {
524 $is_array++;
525 $type = substr( $type, 0, ( length( $type ) - 5 ) );
526 }
527 my $code = \&{"DBD::Pg::$c"};
528 my $val = $code->();
529 if( !CORE::exists( $DATATYPES_DICT->{ $type } ) )
530 {
531 warn( "Unknown PostgreSQL constant DBD::Pg::${c}" ) if( warnings::enabled( 'DB::Object' ) );
532 next;
533 }
534 elsif( $is_array )
535 {
536 my $copy = {};
537 my $keys = [keys( %{$DATATYPES_DICT->{ $type }} )];
538 @$copy{ @$keys } = @{$DATATYPES_DICT->{ $type }}{ @$keys };
539 $copy->{type} = "${type}array";
540 $copy->{name} = $c;
541 $copy->{constant} = $val;
542 $copy->{re} = qr/^(${type}array)\b/;
543 $copy->{is_array} = $is_array;
544 $DATATYPES_DICT->{ "${type}array" } = $copy;
545 next;
546 }
547 $DATATYPES_DICT->{ $type }->{is_array} = $is_array;
548 $DATATYPES_DICT->{ $type }->{constant} = $val;
549 }
550 }
551  
552 # sub new is inherited from DB::Object
553 sub init
554 {
555 my $self = shift( @_ );
556 $self->{_exception_class} = $EXCEPTION_CLASS;
557 $self->SUPER::init( @_ ) || return( $self->pass_error );
558 $self->{driver} = 'Pg';
559 return( $self );
560 }
561  
562 # Get/set alias
563 # sub alias
564  
565 # sub as_string
566  
567 # sub avoid
568  
569 sub attribute($;$@)
570 {
571 my $self = shift( @_ );
572 # $h->{AttributeName} = ...; # set/write
573 # ... = $h->{AttributeName}; # get/read
574 # 1 means that the attribute may be modified
575 # 0 mneas that the attribute may only be read
576 my $name = shift( @_ ) if( @_ == 1 );
577 my %arg = ( @_ );
578 my %attr =
579 (
580 ActiveKids => 0,
581 AutoCommit => 1,
582 AutoInactiveDestroy => 1,
583 CachedKids => 0,
584 ChildHandles => 0,
585 ChopBlanks => 1,
586 CursorName => 0,
587 Driver => 0,
588 ErrCount => 1,
589 Executed => 0,
590 FetchHashKeyName => 1,
591 HandleError => 1,
592 HandleSetErr => 1,
593 InactiveDestroy => 1,
594 Kids => 0,
595 NAME => 0,
596 NULLABLE => 0,
597 NUM_OF_FIELDS => 0,
598 NUM_OF_PARAMS => 0,
599 # Current database name
600 Name => 0,
601 PRECISION => 0,
602 PrintError => 1,
603 PrintWarn => 1,
604 Profile => 1,
605 RaiseError => 1,
606 # Specifies if the current database connection should be in read-only mode or not.
607 ReadOnly => 1,
608 RowCacheSize => 0,
609 RowsInCache => 0,
610 SCALE => 0,
611 ShowErrorStatement => 1,
612 Statement => 0,
613 TYPE => 0,
614 Taint => 1,
615 TaintIn => 1,
616 TaintOut => 1,
617 TraceLevel => 1,
618 Type => 1,
619 Username => 0,
620 Warn => 1,
621 pg_INV_READ => 0,
622 pg_INV_WRITE => 0,
623 pg_async_status => 0,
624 # If true, boolean values will be returned as the characters 't' and 'f' instead of '1' and '0'.
625 pg_bool_tf => 1,
626 pg_db => 0,
627 pg_default_port => 0,
628 pg_enable_utf8 => 1,
629 # Valid entries are 0, 1 and 2
630 pg_errorlevel => 1,
631 pg_expand_array => 1,
632 pg_host => 0,
633 pg_lib_version => 0,
634 pg_options => 0,
635 pg_pass => 0,
636 pg_pid => 0,
637 # When true, question marks inside of statements are not treated as placeholders, e.g. geometric operators
638 pg_placeholder_dollaronly => 1,
639 # When true, colons inside of statements are not treated as placeholders
640 pg_placeholder_nocolons => 1,
641 pg_port => 0,
642 pg_prepare_now => 1,
643 pg_protocol => 0,
644 # Indicates if DBD::Pg should attempt to use server-side prepared statements. On by default
645 pg_server_prepare => 1,
646 pg_server_version => 0,
647 pg_socket => 0,
648 pg_standard_conforming_strings => 0,
649 pg_switch_prepared => 1,
650 pg_user => 0,
651 # Not used
652 # LongReadLen => 1,
653 # LongTruncOk => 1,
654 # CompatMode => 1,
655 );
656 # Only those attribute exist
657 # Using an a non existing attribute produce an exception, so we better avoid
658 if( $name )
659 {
660 return( $self->{dbh}->{ $name } ) if( exists( $attr{ $name } ) );
661 }
662 else
663 {
664 my $value;
665 while( ( $name, $value ) = each( %arg ) )
666 {
667 # We intend to modifiy the value of an attribute
668 # we are allowed to modify this value if it is true
669 if( exists( $attr{ $name } ) &&
670 defined( $value ) &&
671 $attr{ $name } )
672 {
673 $self->{dbh}->{ $name } = $value;
674 }
675 }
676 }
677 }
678  
679 # sub available_drivers(@)
680  
681 sub begin_work($;$@)
682 {
683 my $self = shift( @_ );
684 local $@;
685 my $rv = eval
686 {
687 return( $self->{dbh}->begin_work( @_ ) );
688 };
689 if( $@ )
690 {
691 return( $self->error( "Error calling begin_work(). Have you forgotten to turn on AutoCommit?: $@" ) );
692 }
693 elsif( !$rv && $self->{dbh}->err )
694 {
695 return( $self->error({ code => $self->{dbh}->err, message => $self->{dbh}->errstr }) );
696 }
697  
698 if( defined( $rv ) )
699 {
700 $self->_transaction_started;
701 return( $rv || 1 );
702 }
703 return;
704 }
705  
706 # This method is common to DB::Object and DB::Object::Statement
707 # sub bind
708  
709 # sub cache
710  
711 # sub check_driver(@;$@)
712  
713 sub commit($;$@)
714 {
715 my $self = shift( @_ );
716 local $@;
717 my $rv = eval
718 {
719 return( $self->{dbh}->commit( @_ ) );
720 };
721 if( $@ )
722 {
723 return( $self->error( "Error calling commit(): $@" ) );
724 }
725 elsif( !$rv && $self->{dbh}->err )
726 {
727 return( $self->error({ code => $self->{dbh}->err, message => $self->{dbh}->errstr }) );
728 }
729  
730 if( defined( $rv ) )
731 {
732 $self->_transaction_finished;
733 return( $rv || 1 );
734 }
735 return;
736 }
737  
738 # connect(9 is inherited by DB::Object
739  
740 # sub copy
741  
742 # See also datatype_to_constant()
743 # NOTE: sub constant_to_datatype is inherited from DB::Object
744  
745 # See also constant_to_datatype()
746 # NOTE: sub datatype_to_constant is inherited from DB::Object
747  
748 sub create_db
749 {
750 my $self = shift( @_ );
751 my $name = shift( @_ ) || return( $self->error( "No database name to create was provided." ) );
752 my $opts = $self->_get_args_as_hash( @_ );
753 my $params = [];
754 # https://www.postgresql.org/docs/9.5/sql-createdatabase.html
755 push( @$params, sprintf( 'OWNER=%s', $opts->{owner} ) ) if( $opts->{owner} );
756 push( @$params, sprintf( 'TEMPLATE=%s', $opts->{template} ) ) if( $opts->{template} );
757 push( @$params, sprintf( 'ENCODING=%s', $opts->{encoding} ) ) if( $opts->{encoding} );
758 push( @$params, sprintf( 'LC_COLLATE=%s', $opts->{lc_collate} ) ) if( $opts->{lc_collate} );
759 push( @$params, sprintf( 'LC_CTYPE=%s', $opts->{lc_ctype} ) ) if( $opts->{lc_ctype} );
760 push( @$params, sprintf( 'TABLESPACE=%s', $opts->{tablespace} ) ) if( $opts->{tablespace} );
761 push( @$params, sprintf( 'ALLOW_CONNECTIONS=%s', $opts->{allowcon} ? 'true' : 'false' ) ) if( length( $opts->{allowcon} ) );
762 push( @$params, sprintf( 'CONNECTION LIMIT=%s', $opts->{connlimit} ) ) if( length( $opts->{connlimit} ) );
763 push( @$params, sprintf( 'IS_TEMPLATE=%s', $opts->{istemplate} ? 'true' : 'false' ) ) if( length( $opts->{istemplate} ) );
764 my $sql = "CREATE DATABASE $name";
765 if( scalar( @$params ) )
766 {
767 $sql .= ' WITH ' . join( ' ', @$params );
768 }
769 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
770 my( $sth, $rc );
771 # try-catch
772 local $@;
773 $sth = eval
774 {
775 $dbh->prepare( $sql );
776 };
777 if( $@ )
778 {
779 return( $self->error( "An error occured while preparing SQL query to create database: ", $@ ) );
780 }
781 $sth or return( $self->error( "An error occured while preparing SQL query to create database: ", $dbh->errstr ) );
782  
783 # try-catch
784 $rc = eval
785 {
786 $sth->execute;
787 };
788 if( $@ )
789 {
790 return( $self->error( "An error occured while executing SQL query to create database: ", $@ ) );
791 }
792 $rc or return( $self->error( "An error occured while executing SQL query to create database: ", $sth->errstr ) );
793  
794 # try-catch
795 eval
796 {
797 $sth->finish;
798 };
799 if( $@ )
800 {
801 return( $self->error( "An unexpected error occurred while trying to finish the SQL query to create database: ", $@, "\n$sql" ) );
802 }
803  
804 my $ref = {};
805 # my @keys = qw( host port login passwd schema opt debug );
806 my $ok_params = $self->_connection_parameters;
807 foreach my $key ( @$ok_params )
808 {
809 if( my $coderef = $self->can( $key ) )
810 {
811 $ref->{ $key } = $coderef->( $self );
812 }
813 }
814 $ref->{database} = $name;
815 $dbh = $self->connect( $ref ) || return( $self->error( "I could create the database \"$name\" but oddly enough, I could not connect to it with user \"$ref->{login}\" on host \"$ref->{host}\" with port \"$ref->{port}\"." ) );
816 return( $dbh );
817 }
818  
819 sub create_table
820 {
821 my $self = shift( @_ );
822 my $name = shift( @_ ) || return( $self->error( "No table name to create was provided." ) );
823 my $opts = $self->_get_args_as_hash( @_ );
824 return( $self->error( "Table \"$name\" already exists in the database." ) ) if( $self->table_exists( $name ) );
825 my $schema = $self->schema;
826 my $sql = $opts->{sql} || return( $self->error( "No sql query was provided to create table \"$name\"." ) );
827 # The schema is missing
828 if( $schema )
829 {
830 $sql =~ s/\b(CREATE[[:blank:]]+(?:.*?)\bTABLE(?:[[:blank:]]+IF[[:blank:]]+NOT[[:blank:]]+EXISTS)?)[[:blank:]]+$name\b/$1 ${schema}.${name}/si;
831 }
832 my $rv = $self->do( $sql ) || return( $self->error( "An error occured while executing sql query to create table \"$name\": ", $self->errstr, "\nOriginal query was: $sql" ) );
833 return( $rv );
834 }
835  
836 # sub create_table($;%)
837  
838 # See DB::Object
839 # sub data_sources($;\%)
840  
841 # sub data_type
842  
843 # NOTE: sub datatype_dict is inherited
844  
845 # NOTE: sub datatypes is in inherited
846  
847 # sub database
848  
849 sub databases
850 {
851 my $self = shift( @_ );
852 # return( $self->error( "Not connected to PostgreSQL server yet. Issue $dbh->connect first." ) ) if( !$self->{ 'dbh' } );
853 my $dbh;
854 # If there is no connection yet, then create one using the postgres login.
855 # There should not be a live user and database just to check what databases there are.
856 if( !$self->{dbh} )
857 {
858 # try-catch
859 local $@;
860 $dbh = eval
861 {
862 $self->connect;
863 };
864 if( $@ )
865 {
866 return( $self->error( "Error trying to connect to the PostgreSQL server: $@" ) );
867 }
868 $dbh or return( $self->pass_error );
869 }
870 else
871 {
872 $dbh = $self;
873 }
874 my $temp = $dbh->do( "SELECT datname FROM pg_database" )->fetchall_arrayref;
875 return( $self->error( $dbh->errstr ) ) if( !$temp );
876 my @dbases = map( $_->[0], @$temp );
877 return( @dbases );
878 }
879  
880 # delete() is inherited from DB::Object
881 # sub delete
882  
883 # sub disconnect($)
884  
885 # sub do($;$@)
886  
887 # sub enhance
888  
889 # See DB::Object
890 # sub err(@)
891 # Meaning of the error code
892 # 0 Empty query string
893 # 1 A command that returns no data successfully completed.
894 # 2 A command that returns data successfully completed.
895 # 3 A COPY OUT command is still in progress.
896 # 4 A COPY IN command is still in progress.
897 # 5 A bad response was received from the backend.
898 # 6 A nonfatal error occurred (a notice or warning message)
899 # 7 A fatal error was returned: the last query failed.
900  
901 # See DB::Object
902 # sub errno
903  
904 # See DB::Object
905 # sub errmesg
906  
907 # See DB::Object
908 # sub errstr(@)
909 # Affected by the pg_errorlevel setting
910  
911 # sub fatal
912  
913 # sub from_unixtime
914  
915 # Inherited from DB::Object
916 # sub format_statement($;\%\%@)
917  
918 # sub format_update($;%)
919  
920 sub func
921 {
922 my $self = shift( @_ );
923 my $table = shift( @_ );
924 # e.g. table_attributes to get the detail information on table columns
925 my $func_name = shift( @_ );
926 # Returns:
927 # NAME attribute name
928 # TYPE attribute type
929 # SIZE attribute size (-1 for variable size)
930 # NULLABLE flag nullable
931 # DEFAULT default value
932 # CONSTRAINT constraint
933 # PRIMARY_KEY flag is_primary_key
934 # REMARKS attribute description
935 return( $self->{ 'dbh' }->func( $table, $func_name ) );
936 }
937  
938 # See DB::Object
939 # sub getdefault($;%)
940  
941 # sub group
942  
943 sub get_sql_type
944 {
945 my $self = shift( @_ );
946 my $type = shift( @_ ) || return( $self->error( "No sql type was provided to get its constant." ) );
947 $type = lc( $type );
948 if( CORE::exists( $DATATYPES_DICT->{ $type } ) &&
949 $type ne $DATATYPES_DICT->{ $type }->{type} )
950 {
951 $type = $DATATYPES_DICT->{ $type }->{type};
952 }
953 my $const;
954 if( substr( $type, 0, 3 ) eq 'pg_' )
955 {
956 $const = $self->{dbh}->can( "DBD::Pg::\U${type}\E" );
957 }
958 else
959 {
960 $const = $self->{dbh}->can( "DBD::Pg::PG_\U${type}\E" );
961 }
962 return( '' ) if( !defined( $const ) );
963 return( $const->() );
964 }
965  
966 # Specific to Postgres
967 sub having
968 {
969 my $self = shift( @_ );
970 my $q = $self->_reset_query;
971 return( $q->having( @_ ) );
972 }
973  
974 # See DB::Object
975 # sub insert
976  
977 sub large_object
978 {
979 my $self = shift( @_ );
980 return( $self->error( "large_object() cannot be called as a class function." ) ) if( !ref( $self ) );
981 $self->_load_class( 'DB::Object::Postgres::Lo' ) || return( $self->pass_error );
982 # Parameter is a bitmask mode
983 return( DB::Object::Postgres::Lo->new( $self->{dbh} ) );
984 }
985  
986 # Must be superseded, or better yet, the one in DB::Object should probably be changed to ours
987 sub last_insert_id
988 {
989 my $self = shift( @_ );
990 my $table = shift( @_ ) || $self->{ 'table' };
991 return( $self->{ 'dbh' }->last_insert_id( undef, undef, $table, undef ) );
992 }
993  
994 # http://www.postgresql.org/docs/9.3/interactive/queries-limit.html
995 # See DB::Object::Postgres::Query
996 # sub limit
997  
998 # sub local
999  
1000 # http://www.postgresql.org/docs/current/static/sql-lock.html
1001 sub lock
1002 {
1003 my $self = shift( @_ );
1004 my $table = shift( @_ ) || return( $self->error( "You must provide a table name to lock onto." ) );
1005 # ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE |
1006 # SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE
1007 my $mode = shift( @_ ) || undef();
1008 my $nowait= shift( @_ );
1009 my $query = "LOCK TABLE $table";
1010 $query .= " IN $mode MODE" if( defined( $mode ) );
1011 $query .= " NOWAIT" if( $nowait );
1012 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1013 my $sth = $dbh->prepare( $query ) ||
1014 return( $self->error( "Error while preparing query to get lock on table '$table': ", $dbh->errstr() ) );
1015 $sth->execute() ||
1016 return( $self->error( "Error while executing query to get lock on table '$table': ", $sth->errstr() ) );
1017 my $res = $sth->fetchrow;
1018 $sth->finish();
1019 # We do not really need to track that information.
1020 # $self->{ '_locks' } ||= [];
1021 # push( @{ $self->{ '_locks' } }, $table ) if( $res && $res ne 'NULL' );
1022 return( $res eq 'NULL' ? ( wantarray() ? () : undef() ) : $res );
1023 }
1024  
1025 sub make_schema
1026 {
1027 my $self = shift( @_ );
1028 my $db = shift( @_ ) || $self->{ 'database' };
1029 my $dbh;
1030 if( $self->{ 'dbh' } )
1031 {
1032 $dbh = $self;
1033 }
1034 else
1035 {
1036 $dbh = $self->connect( { 'login' => 'postgres', 'database' => $db } ) || return( $self->error( "Cannot connect to Postgres database $db: " . $self->error ) );
1037 }
1038 my $tables = $dbh->tables;
1039 return( $self->error( "There is no table in database $db." ) ) if( !@$tables );
1040 my @schema_tables = ();
1041 my $max_field_size = <<SQL;
1042 SELECT MAX(LENGTH(a.attname)) AS "max_length"
1043 FROM pg_class c, pg_attribute a, pg_authid o
1044 WHERE c.relkind IN ('r', 'v', 'm', 'f') AND a.attrelid=c.oid AND c.relowner=o.oid AND o.rolname != 'postgres'
1045 SQL
1046 my $inherited_fields = <<SQL;
1047 SELECT c.relname AS table, a.attname AS field
1048 FROM pg_class c
1049 JOIN pg_inherits i ON c.oid = i.inhrelid
1050 JOIN pg_attribute a ON i.inhparent = a.attrelid
1051 WHERE attnum > 0
1052 SQL
1053 my $table_info = <<SQL;
1054 SELECT c.oid, c.relchecks, c.relkind, c.relhasindex, c.relhasrules, c.relhastriggers, c.relhasoids, '', c.reltablespace, CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, c.relpersistence FROM pg_catalog.pg_class c
1055 LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)
1056 WHERE c.relname ~ '^(%s)\$'
1057 SQL
1058 my $field_info = <<SQL;
1059 SELECT a.attname,
1060 pg_catalog.format_type(a.atttypid, a.atttypmod),
1061 (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
1062 FROM pg_catalog.pg_attrdef d
1063 WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),
1064 a.attnotnull, a.attnum,
1065 (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t
1066 WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation,
1067 NULL AS indexdef,
1068 NULL AS attfdwoptions
1069 FROM pg_catalog.pg_attribute a
1070 WHERE a.attrelid = ? AND a.attnum > 0 AND NOT a.attisdropped
1071 ORDER BY a.attnum
1072 SQL
1073 my $get_constraints = <<SQL;
1074 SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),
1075 pg_catalog.pg_get_constraintdef(con.oid, true), contype, condeferrable, condeferred, c2.reltablespace
1076 FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
1077 LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))
1078 WHERE c.oid = ? AND c.oid = i.indrelid AND i.indexrelid = c2.oid
1079 ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname
1080 SQL
1081 my $get_check_constraint = <<SQL;
1082 SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true)
1083 FROM pg_catalog.pg_constraint r
1084 WHERE r.conrelid = ? AND r.contype = 'c'
1085 ORDER BY 1
1086 SQL
1087 my $get_fkey_constraint = <<SQL;
1088 SELECT conname,
1089 pg_catalog.pg_get_constraintdef(r.oid, true) as condef
1090 FROM pg_catalog.pg_constraint r
1091 WHERE r.conrelid = ? AND r.contype = 'f' ORDER BY 1
1092 SQL
1093 my $inheritance = "SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhparent AND i.inhrelid = ? ORDER BY inhseqno";
1094 my $get_tbl_comment = "SELECT description FROM pg_description WHERE (SELECT relname FROM pg_class WHERE oid=objoid) = ? and objsubid = 0";
1095 my $get_field_comment = "SELECT d.description, a.attname FROM pg_description d, pg_attribute a WHERE (SELECT relname FROM pg_class WHERE oid=d.objoid) = ? AND a.attnum=d.objsubid AND a.attrelid=d.objoid AND d.objsubid > 0";
1096  
1097 # Get the max size of the fields to properly format the schema
1098 my $sth = $dbh->{dbh}->prepare_cached( $max_field_size ) || return( $self->error( $dbh->{dbh}->errstr ) );
1099 $sth->execute() || return( $self->error( $sth->errstr ) );
1100 my $fsize = $sth->fetchrow;
1101 $sth->finish;
1102  
1103 # Get the list of all inherited fields per table, so we can exclude them in the schema we produce.
1104 $sth = $dbh->{dbh}->prepare_cached( $inherited_fields ) || return( $self->error( $dbh->{dbh}->errstr ) );
1105 $sth->execute() || return( $self->error( $sth->errstr ) );
1106 my $all = $sth->fetchall_arrayref( {} );
1107 my $inherited = {};
1108 foreach my $h ( @$all )
1109 {
1110 $inherited->{ $h->{ 'table' } } = [] if( !exists( $inherited->{ $h->{ 'table' } } ) );
1111 push( @{$inherited->{ $h->{ 'table' } }}, $h->{ 'field' } );
1112 }
1113 $sth->finish;
1114  
1115 foreach my $t ( @$tables )
1116 {
1117 my @table_def = ( "CREATE TABLE $t (" );
1118 # Get table overall information
1119 $dbh->bind( 0 );
1120 $sth = $dbh->{dbh}->prepare_cached( sprintf( $table_info, $t ) ) || return( $self->error( $dbh->{dbh}->errstr ) );
1121 $sth->execute() || return( $self->error( $sth->errstr ) );
1122 my $tbl_info = $sth->fetchrow_hashref();
1123 $sth->finish;
1124 $dbh->bind( 1 );
1125  
1126 # Get field info.
1127 $sth = $dbh->{Dbh}->prepare_cached( $field_info ) || return( $self->error( $dbh->{dbh}->errstr ) );
1128 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1129 my $rows = $sth->fetchall_arrayref( {} );
1130 foreach my $r ( @$rows )
1131 {
1132 next if( exists( $inherited->{ $t } ) && grep( /^$r->{ 'attname' }$/, @{$inherited->{ $t }} ) );
1133 my @col_def = ( sprintf( "\t%-${fsize}s %s", $r->{ 'attname' }, uc( $r->{ 'format_type' } ) ) );
1134 push( @col_def, 'NOT NULL' ) if( $r->{ 'attnotnull' } );
1135 if( $r->{ 'format_type' } =~ /^(integer|int|boolean|decimal)$/i )
1136 {
1137 push( @col_def, sprintf( 'DEFAULT %s', $r->{ 'substring' } ) ) if( $r->{ 'substring' } );
1138 }
1139 else
1140 {
1141 push( @col_def, sprintf( "DEFAULT '%s'", $r->{ 'substring' } ) ) if( $r->{ 'substring' } );
1142 }
1143 push( @table_def, join( " ", @col_def ) );
1144 }
1145 $sth->finish;
1146 my @constraints = ();
1147 my @index = ();
1148 # Get primary key and unique index constraints
1149 $sth = $dbh->{dbh}->prepare_cached( $get_constraints ) || return( $self->error( $dbh->{dbh}->errstr ) );
1150 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1151 $rows = $sth->fetchall_arrayref( {} );
1152 foreach my $r ( @$rows )
1153 {
1154 if( $r->{ 'indisprimary' } || $r->{ 'indisunique' } )
1155 {
1156 push( @constraints, sprintf( "\tCONSTRAINT %s %s", @$r{ qw( relname pg_get_constraintdef ) } ) );
1157 }
1158 else
1159 {
1160 push( @index, sprintf( 'CREATE INDEX %s;', $r->{ 'pg_get_indexdef' } ) );
1161 }
1162 }
1163 $sth->finish;
1164 # Get CHECK constraints
1165 $sth = $dbh->{dbh}->prepare_cached( $get_check_constraint ) || return( $self->error( $dbh->{dbh}->errstr ) );
1166 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1167 $rows = $sth->fetchall_arrayref( {} );
1168 foreach my $r ( @$rows )
1169 {
1170 push( @constraints, sprintf( "\tCONSTRAINT %s %s", @$r{ qw( conname pg_get_constraintdef ) } ) );
1171 }
1172 $sth->finish;
1173 # Get foreign key constraints
1174 $sth = $dbh->{dbh}->prepare_cached( $get_fkey_constraint ) || return( $self->error( $dbh->{dbh}->errstr ) );
1175 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1176 $rows = $sth->fetchall_arrayref( {} );
1177 foreach my $r ( @$rows )
1178 {
1179 push( @constraints, sprintf( "\tCONSTRAINT %s %s", @$r{ qw( conname condef ) } ) );
1180 }
1181 $sth->finish;
1182 push( @table_def, @constraints );
1183  
1184 # Get table inheritance
1185 $sth = $dbh->{dbh}->prepare_cached( $inheritance ) || return( $self->error( $dbh->{dbh}->errstr ) );
1186 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1187 $rows = $sth->fetchall_arrayref( {} );
1188 my @inherit = map{ $_->{ 'oid' } } @$rows;
1189 $sth->finish;
1190  
1191 # Add a comma at the end of each line now we know how many there are.
1192 for( my $i = 0; $i < $#table_def; $i++ )
1193 {
1194 $table_def[ $i ] .= ",";
1195 }
1196  
1197 if( @inherit )
1198 {
1199 push( @table_def, sprintf( ') INHERITS (%s);', join( ", ", @inherit ) ) );
1200 }
1201 else
1202 {
1203 push( @table_def, ');' );
1204 }
1205  
1206 # Put here the table indexes
1207 push( @table_def, @index );
1208  
1209 # Get comments on the table itself, if any
1210 $sth = $dbh->{dbh}->prepare_cached( $get_tbl_comment ) || return( $self->error( $sth->{dbh}->errstr ) );
1211 $sth->execute( $t ) || return( $self->error( $sth->errstr ) );
1212 my $ref = $sth->fetchrow_hashref();
1213 $sth->finish;
1214 push( @table_def, sprintf( "COMMENT ON TABLE %s IS '%s';", $t, $ref->{ 'description' } ) ) if( $ref->{ 'description' } );
1215  
1216 # Get comments for each field
1217 $sth = $dbh->{dbh}->prepare_cached( $get_field_comment ) || return( $self->error( $sth->{dbh}->errstr ) );
1218 $sth->execute( $t ) || return( $self->error( $sth->errstr ) );
1219 $rows = $sth->fetchall_arrayref( {} );
1220 $sth->finish;
1221 foreach my $r ( @$rows )
1222 {
1223 push( @table_def, sprintf( "COMMENT ON COLUMN %s.%s IS '%s';", $t, @$r{ qw( attname description ) } ) );
1224 }
1225 push( @schema_tables, join( "\n", @table_def ) );
1226 }
1227 return( wantarray() ? @schema_tables : join( "\n\n", @schema_tables ) );
1228 }
1229  
1230 # sub no_bind
1231  
1232 # sub no_cache
1233  
1234 # sub order
1235  
1236 # See DB::Object
1237 # sub param
1238  
1239 sub pg_notifies
1240 {
1241 my $self = shift( @_ );
1242 my $dbh;
1243 if( $self->{dbh} )
1244 {
1245 $dbh = $self->{dbh};
1246 }
1247 elsif( $self->can( 'database_object' ) )
1248 {
1249 $dbh = $self->database_object ||
1250 return( $self->error( "No database object is set on this table object." ) );
1251 $dbh = $dbh->{dbh} || return( $self->error( "No database handler is set on our database object." ) );
1252 }
1253 else
1254 {
1255 return( $self->error( "The object of class ", ( ref( $self ) || $self ), " has no property 'dbh'." ) );
1256 }
1257  
1258 # try-catch
1259 local $@;
1260 my $ref = eval
1261 {
1262 $dbh->pg_notifies;
1263 };
1264 if( $@ )
1265 {
1266 return( $self->error( "Error calling PostgreSQL function pg_notifies: $@" ) );
1267 }
1268 elsif( !$ref && $dbh->err )
1269 {
1270 $self->error({ code => $dbh->err, message => $dbh->errstr });
1271 }
1272 return( $ref );
1273 }
1274  
1275 sub pg_ping(@)
1276 {
1277 my $self = shift( @_ );
1278 local $@;
1279 my $rv = eval
1280 {
1281 return( $self->{dbh}->pg_ping( @_ ) );
1282 };
1283 if( $@ )
1284 {
1285 return( $self->error( "Error calling pg_ping: $@" ) );
1286 }
1287 elsif( !$rv && $self->{dbh}->err )
1288 {
1289 $self->error({ code => $self->{dbh}->err, message => $self->{dbh}->errstr });
1290 }
1291 return( $rv );
1292 }
1293  
1294 # See DB::Object
1295 # sub ping(@)
1296  
1297 # See DB::Object
1298 # sub prepare($;$)
1299  
1300 # See DB::Object
1301 # sub prepare_cached
1302  
1303 # sub query($$)
1304  
1305 sub query_object { return( shift->_set_get_object( 'query_object', 'DB::Object::Postgres::Query', @_ ) ); }
1306  
1307 # sub quote will be automatically loaded via AUTOLOADER
1308  
1309 sub quote
1310 {
1311 my $self = shift( @_ );
1312 my( $str, $type ) = @_;
1313 # my $dbh = $self->{dbh} || return( $self->error( "No database handler was set." ) );
1314 my $dbh;
1315 unless( $dbh = $self->{dbh} )
1316 {
1317 return( $self->SUPER::quote( $str ) );
1318 }
1319 $type = { pg_type => $type } if( $type && ref( $type ) ne 'HASH' );
1320 return( $dbh->quote( $str, $type ) );
1321 }
1322  
1323 # This can return an empty string on success, so use defined() to distinguish success from failure.
1324 sub release
1325 {
1326 my $self = shift( @_ );
1327 local $@;
1328 my $rv = eval
1329 {
1330 return( $self->{dbh}->pg_release( @_ ) );
1331 };
1332 if( $@ )
1333 {
1334 return( $self->error( "Error calling release: $@" ) );
1335 }
1336 elsif( !defined( $rv ) && $self->{dbh}->err )
1337 {
1338 return( $self->error({ code => $self->{dbh}->err, message => $self->{dbh}->errstr }) );
1339 }
1340 if( defined( $rv ) )
1341 {
1342 $self->_transaction_started;
1343 return( $rv || 1 );
1344 }
1345 return;
1346 }
1347  
1348 sub replace
1349 {
1350 return( shift->error( "Replace queries are not supported in PostgreSQL" ) );
1351 }
1352  
1353 # sub reset
1354  
1355 # sub reverse
1356  
1357 # sub rollback will be automatically loaded via AUTOLOADER
1358  
1359 # Specific to Postgres
1360 sub returning
1361 {
1362 my $self = shift( @_ );
1363 my $q = $self->_reset_query;
1364 return( $q->returning( @_ ) );
1365 }
1366  
1367 sub rollback
1368 {
1369 my $self = shift( @_ );
1370 local $@;
1371 my $rv = eval
1372 {
1373 return( $self->{dbh}->rollback( @_ ) );
1374 };
1375 if( $@ )
1376 {
1377 return( $self->error( "Error calling rollback: $@" ) );
1378 }
1379 elsif( !defined( $rv ) && $self->{dbh}->err )
1380 {
1381 return( $self->error({ code => $self->{dbh}->err, message => $self->{dbh}->errstr }) );
1382 }
1383 if( defined( $rv ) )
1384 {
1385 $self->_transaction_finished;
1386 return( $rv || 1 );
1387 }
1388 return;
1389 }
1390  
1391 # This can return an empty string on success, so use defined() to distinguish success from failure.
1392 sub rollback_to(@)
1393 {
1394 my $self = shift( @_ );
1395 local $@;
1396 my $rv = eval
1397 {
1398 return( $self->{dbh}->pg_rollback_to( @_ ) );
1399 };
1400 if( $@ )
1401 {
1402 return( $self->error( "Error calling rollback_to: $@" ) );
1403 }
1404 elsif( !$rv && $self->{dbh}->err )
1405 {
1406 return( $self->error({ code => $self->{dbh}->err, message => $self->{dbh}->errstr }) );
1407 }
1408 if( defined( $rv ) )
1409 {
1410 $self->_transaction_started;
1411 return( $rv || 1 );
1412 }
1413 return;
1414 }
1415  
1416 # This can return an empty string on success, so use defined() to distinguish success from failure.
1417 sub savepoint(@)
1418 {
1419 my $self = shift( @_ );
1420 local $@;
1421 my $rv = eval
1422 {
1423 return( $self->{dbh}->pg_savepoint( @_ ) );
1424 };
1425 if( $@ )
1426 {
1427 return( $self->error( "Error calling savepoint: $@" ) );
1428 }
1429 elsif( !$rv && $self->{dbh}->err )
1430 {
1431 return( $self->error({ code => $self->{dbh}->err, message => $self->{dbh}->errstr }) );
1432 }
1433 if( defined( $rv ) )
1434 {
1435 $self->_transaction_started;
1436 return( $rv || 1 );
1437 }
1438 return;
1439 }
1440  
1441 sub schema { return( shift->_set_get_scalar( 'schema', @_ ) ); }
1442  
1443 sub search_path
1444 {
1445 my $self = shift( @_ );
1446 if( @_ )
1447 {
1448 my $val = @_ == 1
1449 ? $self->_is_array( $_[0] )
1450 ? shift( @_ )
1451 : [ @_ ]
1452 : [ @_ ];
1453 my $arg = sprintf( '"%s"', join( '", "', @$val ) );
1454 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1455 my $sth = $dbh->prepare_cached( "SET search_path = $arg" ) || return( $self->error( "Unable to prepare sql query to set search path: ", $dbh->errstr() ) );
1456 my $rc = $sth->execute() || return( $self->error( "Unable to execute sql query to set search path: ", $self->errstr() ) );
1457 $sth->finish;
1458 return( $rc );
1459 }
1460 else
1461 {
1462 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1463 my $sth = $dbh->prepare_cached( "SHOW search_path" ) || return( $self->error( "Unable to prepare sql query to get search path: ", $dbh->errstr() ) );
1464 my $rc = $sth->execute() || return( $self->error( "Unable to execute sql query to set search path: ", $self->errstr() ) );
1465 my $val = $sth->fetchrow;
1466 $sth->finish;
1467 my $arr = $self->new_array( [ split( /\,[[:blank:]]*/, $val ) ] );
1468 # Removing surrounding quotes
1469 for( my $i = 0; $i < scalar( @$arr ); $i++ )
1470 {
1471 $arr->[$i] =~ s/^\"|\"$//g;
1472 }
1473 return( $arr );
1474 }
1475 }
1476  
1477 # See DB::Object; _query_component is superseded and this makes the select customised to Posgres needs
1478 # sub select
1479  
1480 # See DB::Object
1481 # sub set
1482  
1483 # See DB::Object
1484 # sub sort
1485  
1486 # Was previously getfd()
1487 sub socket
1488 {
1489 return( shift->{dbh}->{pg_socket} );
1490 }
1491  
1492 # See DB::Object
1493 # sub stat
1494  
1495 # See DB::Object
1496 # sub state(@)
1497  
1498 # See DB::Object
1499 # sub table
1500  
1501 # See DB::Object
1502 sub table_exists
1503 {
1504 my $self = shift( @_ );
1505 my $table = shift( @_ ) ||
1506 return( $self->error( "You must provide a table name to access the table methods." ) );
1507 my $opts = $self->_get_args_as_hash( @_ );
1508 my $schema = $self->schema || $opts->{schema} || '';
1509 my $cache_tables = $self->cache_tables;
1510 my $tables_in_cache = $cache_tables->get({
1511 host => $self->host,
1512 driver => $self->driver,
1513 port => $self->port,
1514 database => $self->database,
1515 });
1516 foreach my $this ( @$tables_in_cache )
1517 {
1518 if( $this->{name} eq $table &&
1519 (
1520 ( $schema && $this->{schema} eq $schema ) ||
1521 ( !$schema || $opts->{anywhere} )
1522 ) )
1523 {
1524 return(1);
1525 }
1526 }
1527 # We did not find it, so let's try by checking directly the database
1528 my $def = $self->table_info( $table ) || return;
1529 return(1) if( scalar( @$def ) );
1530 return(0);
1531 }
1532  
1533 sub table_info
1534 {
1535 my $self = shift( @_ );
1536 my $table = shift( @_ ) ||
1537 return( $self->error( "You must provide a table name to access the table methods." ) );
1538 my $opts = $self->_get_args_as_hash( @_ );
1539 my $schema = $self->schema || $opts->{schema} || '';
1540 my $sql = <<'EOT';
1541 SELECT
1542 n.nspname AS "schema"
1543 ,c.relname AS "name"
1544 ,CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' WHEN 'p' THEN 'table' END AS "type"
1545 ,pg_catalog.pg_get_userbyid(c.relowner) AS "owner"
1546 FROM pg_catalog.pg_class c
1547 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1548 WHERE n.nspname = ANY(regexp_split_to_array((SELECT REPLACE(setting,'"$user"', (SELECT CURRENT_USER)) FROM pg_catalog.pg_settings WHERE name = 'search_path'), '\,\s*')) AND c.relname = ?
1549 EOT
1550 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1551 my $sth = $dbh->prepare_cached( $sql ) || return( $self->error( "An error occured while preparing query to check if table \"$table\" exists in our database: ", $dbh->errstr ) );
1552 $sth->execute( $table ) || return( $self->error( "An error occured while executing query to check if table \"$table\" exists in our database: ", $sth->errstr ) );
1553 my $all = $sth->fetchall_arrayref( {} );
1554 $sth->finish;
1555 return( [] ) if( !scalar( @$all ) );
1556 return( $all ) if( !$schema || $opts->{anywhere} );
1557 foreach my $ref ( @$all )
1558 {
1559 return( $ref ) if( $ref->{schema} eq $schema );
1560 }
1561 return( [] );
1562 }
1563  
1564 # See DB::Object
1565 # sub table_push
1566  
1567 # See DB::Object
1568 # sub tables
1569  
1570 sub tables_info
1571 {
1572 my $self = shift( @_ );
1573 my $db = shift( @_ ) || $self->{database};
1574 my @tables = ();
1575 # Parameters are: ?, schema, table, and type
1576 # my $sth = $self->{ 'dbh' }->table_info( undef, undef, $table, "TABLE,VIEW" );
1577 # The original query was fetched by connecting to Postgres with psql -E and executing the command \z
1578 # This revised query will fetch only tables, views, materialised view and foreign tables, but will avoid the mysterious view called sequence_setvals
1579 # my $query = <<SQL;
1580 # SELECT n.nspname as "schema",
1581 # c.relname as "name"
1582 # FROM pg_catalog.pg_class c
1583 # LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1584 # WHERE c.relkind IN ('r', 'v', 'm', 'f')
1585 # AND n.nspname !~ '^pg_' AND pg_catalog.pg_table_is_visible(c.oid) AND c.relname != 'sequence_setvals'
1586 # ORDER BY c.oid
1587 # SQL
1588 # AND n.nspname OPERATOR(pg_catalog.~) '^((auth|public))$'
1589 my $query = <<'EOT';
1590 SELECT
1591 n.nspname as "schema"
1592 ,c.relname as "name"
1593 ,CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' WHEN 'p' THEN 'table' END as "type"
1594 ,pg_catalog.pg_get_userbyid(c.relowner) as "owner"
1595 FROM pg_catalog.pg_class c
1596 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1597 WHERE c.relkind IN ('r','p','s','v','m','f','')
1598 AND n.nspname !~ '^(pg_|information_schema$)'
1599 AND c.relname != 'sequence_setvals'
1600 ORDER BY 1,2
1601 EOT
1602 my $sth = $self->{dbh}->prepare_cached( $query ) || return( $self->error( sprintf( "Error while preparing query $query: %s", $self->{dbh}->errstr ) ) );
1603 $sth->execute() || return( $self->error( sprintf( "Error while executing query $query: %s", $sth->errstr ) ) );
1604 my $all = $sth->fetchall_arrayref( {} );
1605 return( $all );
1606 }
1607  
1608 # See DB::Object
1609 # sub tables_refresh
1610  
1611 # See DB::Object
1612 # sub tie
1613  
1614 sub trace($;@)
1615 {
1616 my $self = shift( @_ );
1617 # Value is a numeric level; see parse_trace_flag.
1618 return( $self->error( "Trace can only be used on active connection. Use connect first." ) ) if( !$self->{dbh} );
1619 if( @_ )
1620 {
1621 # my( $opt, $filename ) = @_;
1622 $self->{dbh}->trace( @_ );
1623 }
1624 return( $self->{dbh}->trace );
1625 }
1626  
1627 sub trace_msg(@)
1628 {
1629 my $self = shift( @_ );
1630 return( $self->error( "Trace can only be used on active connection. Use connect first." ) ) if( !$self->{dbh} );
1631 # $dbh->trace_msg( $message_text, $min_level );
1632 return( $self->{dbh}->trace_msg( @_ ) );
1633 }
1634  
1635 # sub unix_timestamp
1636  
1637 sub unlock
1638 {
1639 shift->error( "unlock() does not work with Postgres." );
1640 }
1641  
1642 # See DB::Object
1643 # sub update
1644  
1645 # See DB::Object
1646 # sub use
1647  
1648 # See DB::Object
1649 # sub use_cache
1650  
1651 # See DB::Object
1652 # sub use_bind
1653  
1654 sub variables
1655 {
1656 return( shift->error( "variables is currently unsupported in Postgres" ) );
1657 }
1658  
1659 # See DB::Object
1660 # sub where
1661  
1662 # https://www.postgresql.org/docs/10/sql-show.html
1663 # show something exists since at lease from 7.1
1664 sub version
1665 {
1666 my $self = shift( @_ );
1667 # If we already have the information, let's use our cache instead of making a query
1668 return( $self->{_db_version} ) if( length( $self->{_db_version} ) );
1669 # e.g. 10.4
1670 my $sql = 'SHOW server_version';
1671 my $sth = $self->do( $sql ) || return( $self->error( "Unable to issue the sql statement '$sql' to get the server version: ", $self->errstr ) );
1672 my $ver = $sth->fetchrow;
1673 $sth->finish;
1674 # e.g.:
1675 # 12.1 (Ubuntu 12.1-1.pgdg16.04+1)
1676 # 10.4
1677 $ver =~ s/^(\d+(?:\.\S+)?).*?$/$1/;
1678 # We cache it
1679 $self->{_db_version} = version->parse( $ver );
1680 return( $ver );
1681 }
1682  
1683 sub _check_connect_param
1684 {
1685 my $self = shift( @_ );
1686 my $param = $self->SUPER::_check_connect_param( @_ ) || return( $self->pass_error );
1687 # This is also what the psql command line tool does
1688 $param->{login} = ( getpwuid( $> ) )[0] if( !$param->{login} );
1689 $param->{database} = 'postgres' if( !$param->{database} );
1690 # By default
1691 $param->{port} = 5432 if( !CORE::exists( $param->{port} ) );
1692 return( $param );
1693 }
1694  
1695 # Called from connect once all check was done to see if there are default to set
1696 sub _check_default_option
1697 {
1698 my $self = shift( @_ );
1699 my $opts = $self->_get_args_as_hash( @_ );
1700 return( $self->error( "Provided option is not a hash reference." ) ) if( !$self->_is_hash( $opts => 'strict' ) );
1701 $opts->{client_encoding} = 'utf8' if( !CORE::exists( $opts->{client_encoding} ) );
1702 # Enabled but with auto-guess
1703 $opts->{pg_enable_utf8} = -1 if( !CORE::exists( $opts->{pg_enable_utf8} ) && ( $opts->{client_encoding} eq 'utf8' || $opts->{client_encoding} eq 'utf-8' ) );
1704 return( $opts );
1705 }
1706  
1707 # Called by _check_connect_param
1708 sub _connection_options
1709 {
1710 my $self = shift( @_ );
1711 my $param = shift( @_ );
1712 my @pg_params = grep( /^pg_/, keys( %$param ) );
1713 my $opt = $self->SUPER::_connection_options( $param ) || return( $self->pass_error );
1714 @$opt{ @pg_params } = @$param{ @pg_params };
1715 return( $opt );
1716 }
1717  
1718 # NOTE: sub _connection_params2hash_driver is not necessary here. We use our parent's one.
1719  
1720 # Called by _check_connect_param
1721 sub _connection_parameters
1722 {
1723 my $self = shift( @_ );
1724 my $param = shift( @_ );
1725 my $core = $self->new_array( [qw(
1726 db login passwd host port driver database schema server opt uri debug
1727 cache_connections cache_dir cache_query cache_table connect_via unknown_field
1728 use_cache id
1729 )] );
1730 my @pg_params = grep( /^pg_/, keys( %$param ) );
1731 # See DBD::Pg for the list of valid parameters
1732 $core->push( @pg_params );
1733 my $core_fields = $self->{_core_fields} || [];
1734 $core->push( @$core_fields );
1735 return( $core->unique(1) );
1736 }
1737  
1738 sub _dsn
1739 {
1740 my $self = shift( @_ );
1741 my @params = ();
1742 # See pg_service.conf
1743 if( $self->{service} )
1744 {
1745 @params = ( sprintf( 'dbi:%s:%s', @$self{ qw( driver service ) } ) );
1746 }
1747 else
1748 {
1749 # It ends with ':'
1750 @params = ( sprintf( 'dbi:%s:', $self->{driver} ) );
1751 }
1752 push( @params, sprintf( 'dbname=%s', $self->{database} ) ) if( $self->{database} );
1753 push( @params, sprintf( 'host=%s', $self->{host} ) ) if( $self->{host} );
1754 push( @params, sprintf( 'port=%d', $self->{port} ) ) if( $self->{port} );
1755 # push( @params, "options=$options" ) if( length( $options ) );
1756 return( join( ';', @params ) );
1757 }
1758  
1759 # NOTE: _cache_this -> See DB::Object
1760 # sub _cache_this
1761  
1762 # NOTE _clean_statement -> DB::Object
1763 # sub _clean_statement
1764  
1765 # NOTE _cleanup -> DB::Object
1766 # sub _cleanup
1767  
1768 # NOTE _dbi_connect -> DB::Object
1769 # sub _dbi_connect
1770  
1771 # NOTE _make_sth -> DB::Object
1772 # sub _make_sth
1773  
1774 sub _placeholder_regexp { return( $PLACEHOLDER_REGEXP ) }
1775  
1776 # Moved to DB::Object::Postgres::Query
1777 # sub _query_components
1778  
1779 # See DB::Object. The meat of it is really in DB::Object::Query
1780 # sub _reset_query
1781  
1782 # See DB::Object
1783 # sub _save_bind
1784  
1785 # See DB::Object
1786 # sub _value2bind
1787  
1788 # AUTOLOAD is inherited
1789 # AUTOLOAD
1790  
1791 # NOTE: DESTROY
1792 DESTROY
1793 {
1794 # <https://perldoc.perl.org/perlobj#Destructors>
1795 CORE::local( $., $@, $!, $^E, $? );
1796 CORE::return if( ${^GLOBAL_PHASE} eq 'DESTRUCT' );
1797 my $self = CORE::shift( @_ );
1798 CORE::return if( !CORE::defined( $self ) );
1799 my $class = ref( $self ) || $self;
1800 if( $self->{sth} )
1801 {
1802 # print( STDERR "DESTROY(): Terminating sth '$self' for query:\n$self->{ 'query' }\n" ) if( $DEBUG );
1803 $self->{sth}->finish();
1804 }
1805 elsif( $self->{dbh} && $class =~ /^DB\:\:Object\:\:Postgres$/ )
1806 {
1807 local( $SIG{__WARN__} ) = sub{};
1808 # $self->{ 'dbh' }->disconnect();
1809 $self->disconnect();
1810 }
1811 my $locks = $self->{_locks};
1812 if( $locks && $self->_is_array( $locks ) )
1813 {
1814 foreach my $name ( @$locks )
1815 {
1816 $self->unlock( $name );
1817 }
1818 }
1819 }
1820  
1821 1;
1822 # NOTE: POD
1823 __END__
« blib/lib/DB/Object/Fields/Overloaded.pm ↑ Summary lib/DB/Object/Fields/Overloaded.pm »