lib/DB/Object/Postgres.pm

filter: Statementstmt 80.7% 21 / 26 Branchbran 50.0% 1 / 2 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 82.8% 29 / 35 CC 2 SCAR 3.8
CC
2
Cov
79%
BEGIN
2.9
BEGIN
1.0
BEGIN
1.0
CRAP 1.5
« blib/lib/DB/Object/Fields/Overloaded.pm ↑ Summary lib/DB/Object/Fields/Overloaded.pm »
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Postgres.pm
4 ## Version v1.5.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 # This is the subclassable module for driver specific ones.
16 package DB::Object::Postgres;
17 BEGIN
18 {
19 1 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
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(
24 $VERSION
25 $DEBUG $ERROR $MOD_PERL $USE_BIND $USE_CACHE
26 $PLACEHOLDER_REGEXP $DATATYPES_DICT $EXCEPTION_CLASS
27 1 ▶ );
Subroutine BEGIN: called CC=1 SCAR=0.0
28 1 ▶ use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 eval
30 1 ▶ {
Subroutine BEGIN: called CC=2 SCAR=10.5
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.5.1';
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_OIDVECTOR PG_OIDVECTORARRAY PG_PG_ATTRIBUTE PG_PG_ATTRIBUTEARRAY
503 PG_PG_BRIN_BLOOM_SUMMARY PG_PG_BRIN_MINMAX_MULTI_SUMMARY PG_PG_CLASS PG_PG_CLASSARRAY
504 PG_PG_DDL_COMMAND PG_PG_DEPENDENCIES PG_PG_MCV_LIST PG_PG_NDISTINCT PG_PG_NODE_TREE
505 PG_PG_PROC PG_PG_PROCARRAY PG_PG_SNAPSHOT PG_PG_SNAPSHOTARRAY PG_PG_TYPE
506 PG_PG_TYPEARRAY PG_RECORD PG_RECORDARRAY PG_REFCURSOR PG_REFCURSORARRAY PG_REGCLASS
507 PG_REGCLASSARRAY PG_REGCOLLATION PG_REGCOLLATIONARRAY PG_REGCONFIG PG_REGCONFIGARRAY
508 PG_REGDICTIONARY PG_REGDICTIONARYARRAY PG_REGNAMESPACE PG_REGNAMESPACEARRAY PG_REGOPER
509 PG_REGOPERARRAY PG_REGOPERATOR PG_REGOPERATORARRAY PG_REGPROC PG_REGPROCARRAY
510 PG_REGPROCEDURE PG_REGPROCEDUREARRAY PG_REGROLE PG_REGROLEARRAY PG_REGTYPE
511 PG_REGTYPEARRAY PG_TABLE_AM_HANDLER PG_TID PG_TIDARRAY PG_TRIGGER PG_TSM_HANDLER
512 PG_UNKNOWN PG_VOID PG_XID PG_XID8 PG_XID8ARRAY PG_XIDARRAY
513 );
514 foreach my $c ( @$keys )
515 {
516 next if( scalar( grep( /^$c$/, @constants_to_ignore ) ) );
517 if( $c =~ /^PG_(\w+)$/ )
518 {
519 my $type = lc( $1 );
520 my $is_array = 0;
521 if( substr( $type, -5 ) eq 'array' )
522 {
523 $is_array++;
524 $type = substr( $type, 0, ( length( $type ) - 5 ) );
525 }
526 my $code = \&{"DBD::Pg::$c"};
527 my $val = $code->();
528 if( !CORE::exists( $DATATYPES_DICT->{ $type } ) )
529 {
530 warn( "Unknown PostgreSQL constant DBD::Pg::${c}" ) if( DB::Object::Postgres->_is_warnings_enabled( 'DB::Object' ) );
531 next;
532 }
533 elsif( $is_array )
534 {
535 my $copy = {};
536 my $keys = [keys( %{$DATATYPES_DICT->{ $type }} )];
537 @$copy{ @$keys } = @{$DATATYPES_DICT->{ $type }}{ @$keys };
538 $copy->{type} = "${type}array";
539 $copy->{name} = $c;
540 $copy->{constant} = $val;
541 $copy->{re} = qr/^(${type}array)\b/;
542 $copy->{is_array} = $is_array;
543 $DATATYPES_DICT->{ "${type}array" } = $copy;
544 next;
545 }
546 $DATATYPES_DICT->{ $type }->{is_array} = $is_array;
547 $DATATYPES_DICT->{ $type }->{constant} = $val;
548 }
549 }
550  
551 # sub new is inherited from DB::Object
552 sub init
553 {
554 my $self = shift( @_ );
555 $self->{_exception_class} = $EXCEPTION_CLASS;
556 $self->SUPER::init( @_ ) || return( $self->pass_error );
557 $self->{driver} = 'Pg';
558 return( $self );
559 }
560  
561 # Get/set alias
562 # sub alias
563  
564 # sub as_string
565  
566 # sub avoid
567  
568 sub attribute($;$@)
569 {
570 my $self = shift( @_ );
571 # $h->{AttributeName} = ...; # set/write
572 # ... = $h->{AttributeName}; # get/read
573 # 1 means that the attribute may be modified
574 # 0 mneas that the attribute may only be read
575 my $name = shift( @_ ) if( @_ == 1 );
576 my %arg = ( @_ );
577 my %attr =
578 (
579 ActiveKids => 0,
580 AutoCommit => 1,
581 AutoInactiveDestroy => 1,
582 CachedKids => 0,
583 ChildHandles => 0,
584 ChopBlanks => 1,
585 CursorName => 0,
586 Driver => 0,
587 ErrCount => 1,
588 Executed => 0,
589 FetchHashKeyName => 1,
590 HandleError => 1,
591 HandleSetErr => 1,
592 InactiveDestroy => 1,
593 Kids => 0,
594 NAME => 0,
595 NULLABLE => 0,
596 NUM_OF_FIELDS => 0,
597 NUM_OF_PARAMS => 0,
598 # Current database name
599 Name => 0,
600 PRECISION => 0,
601 PrintError => 1,
602 PrintWarn => 1,
603 Profile => 1,
604 RaiseError => 1,
605 # Specifies if the current database connection should be in read-only mode or not.
606 ReadOnly => 1,
607 RowCacheSize => 0,
608 RowsInCache => 0,
609 SCALE => 0,
610 ShowErrorStatement => 1,
611 Statement => 0,
612 TYPE => 0,
613 Taint => 1,
614 TaintIn => 1,
615 TaintOut => 1,
616 TraceLevel => 1,
617 Type => 1,
618 Username => 0,
619 Warn => 1,
620 pg_INV_READ => 0,
621 pg_INV_WRITE => 0,
622 pg_async_status => 0,
623 # If true, boolean values will be returned as the characters 't' and 'f' instead of '1' and '0'.
624 pg_bool_tf => 1,
625 pg_db => 0,
626 pg_default_port => 0,
627 pg_enable_utf8 => 1,
628 # Valid entries are 0, 1 and 2
629 pg_errorlevel => 1,
630 pg_expand_array => 1,
631 pg_host => 0,
632 pg_lib_version => 0,
633 pg_options => 0,
634 pg_pass => 0,
635 pg_pid => 0,
636 # When true, question marks inside of statements are not treated as placeholders, e.g. geometric operators
637 pg_placeholder_dollaronly => 1,
638 # When true, colons inside of statements are not treated as placeholders
639 pg_placeholder_nocolons => 1,
640 pg_port => 0,
641 pg_prepare_now => 1,
642 pg_protocol => 0,
643 # Indicates if DBD::Pg should attempt to use server-side prepared statements. On by default
644 pg_server_prepare => 1,
645 pg_server_version => 0,
646 pg_socket => 0,
647 pg_standard_conforming_strings => 0,
648 pg_switch_prepared => 1,
649 pg_user => 0,
650 # Not used
651 # LongReadLen => 1,
652 # LongTruncOk => 1,
653 # CompatMode => 1,
654 );
655 # Only those attribute exist
656 # Using an a non existing attribute produce an exception, so we better avoid
657 if( $name )
658 {
659 return( $self->{dbh}->{ $name } ) if( exists( $attr{ $name } ) );
660 }
661 else
662 {
663 my $value;
664 while( ( $name, $value ) = each( %arg ) )
665 {
666 # We intend to modifiy the value of an attribute
667 # we are allowed to modify this value if it is true
668 if( exists( $attr{ $name } ) &&
669 defined( $value ) &&
670 $attr{ $name } )
671 {
672 $self->{dbh}->{ $name } = $value;
673 }
674 }
675 }
676 }
677  
678 # sub available_drivers(@)
679  
680 sub begin_work($;$@)
681 {
682 my $self = shift( @_ );
683 $self->{transaction} = 1;
684 return( $self->{dbh}->begin_work( @_ ) );
685 }
686  
687 # This method is common to DB::Object and DB::Object::Statement
688 # sub bind
689  
690 # sub cache
691  
692 # sub check_driver(@;$@)
693  
694 sub commit($;$@)
695 {
696 my $self = shift( @_ );
697 $self->{transaction} = 0;
698 return( $self->{dbh}->commit( @_ ) );
699 }
700  
701 # connect(9 is inherited by DB::Object
702  
703 # sub copy
704  
705 # See also datatype_to_constant()
706 # NOTE: sub constant_to_datatype is inherited from DB::Object
707  
708 # See also constant_to_datatype()
709 # NOTE: sub datatype_to_constant is inherited from DB::Object
710  
711 sub create_db
712 {
713 my $self = shift( @_ );
714 my $name = shift( @_ ) || return( $self->error( "No database name to create was provided." ) );
715 my $opts = $self->_get_args_as_hash( @_ );
716 my $params = [];
717 # https://www.postgresql.org/docs/9.5/sql-createdatabase.html
718 push( @$params, sprintf( 'OWNER=%s', $opts->{owner} ) ) if( $opts->{owner} );
719 push( @$params, sprintf( 'TEMPLATE=%s', $opts->{template} ) ) if( $opts->{template} );
720 push( @$params, sprintf( 'ENCODING=%s', $opts->{encoding} ) ) if( $opts->{encoding} );
721 push( @$params, sprintf( 'LC_COLLATE=%s', $opts->{lc_collate} ) ) if( $opts->{lc_collate} );
722 push( @$params, sprintf( 'LC_CTYPE=%s', $opts->{lc_ctype} ) ) if( $opts->{lc_ctype} );
723 push( @$params, sprintf( 'TABLESPACE=%s', $opts->{tablespace} ) ) if( $opts->{tablespace} );
724 push( @$params, sprintf( 'ALLOW_CONNECTIONS=%s', $opts->{allowcon} ? 'true' : 'false' ) ) if( length( $opts->{allowcon} ) );
725 push( @$params, sprintf( 'CONNECTION LIMIT=%s', $opts->{connlimit} ) ) if( length( $opts->{connlimit} ) );
726 push( @$params, sprintf( 'IS_TEMPLATE=%s', $opts->{istemplate} ? 'true' : 'false' ) ) if( length( $opts->{istemplate} ) );
727 my $sql = "CREATE DATABASE $name";
728 if( scalar( @$params ) )
729 {
730 $sql .= ' WITH ' . join( ' ', @$params );
731 }
732 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
733 my( $sth, $rc );
734 # try-catch
735 local $@;
736 $sth = eval
737 {
738 $dbh->prepare( $sql );
739 };
740 if( $@ )
741 {
742 return( $self->error( "An error occured while preparing SQL query to create database: ", $@ ) );
743 }
744 $sth or return( $self->error( "An error occured while preparing SQL query to create database: ", $dbh->errstr ) );
745  
746 # try-catch
747 $rc = eval
748 {
749 $sth->execute;
750 };
751 if( $@ )
752 {
753 return( $self->error( "An error occured while executing SQL query to create database: ", $@ ) );
754 }
755 $rc or return( $self->error( "An error occured while executing SQL query to create database: ", $sth->errstr ) );
756  
757 # try-catch
758 eval
759 {
760 $sth->finish;
761 };
762 if( $@ )
763 {
764 return( $self->error( "An unexpected error occurred while trying to finish the SQL query to create database: ", $@, "\n$sql" ) );
765 }
766  
767 my $ref = {};
768 my @keys = qw( host port login passwd schema opt debug );
769 @$ref{ @keys } = @$self{ @keys };
770 $ref->{database} = $name;
771 $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}\"." ) );
772 return( $dbh );
773 }
774  
775 sub create_table
776 {
777 my $self = shift( @_ );
778 my $name = shift( @_ ) || return( $self->error( "No table name to create was provided." ) );
779 my $opts = $self->_get_args_as_hash( @_ );
780 return( $self->error( "Table \"$name\" already exists in the database." ) ) if( $self->table_exists( $name ) );
781 my $schema = $self->schema;
782 my $sql = $opts->{sql} || return( $self->error( "No sql query was provided to create table \"$name\"." ) );
783 # The schema is missing
784 if( $schema )
785 {
786 $sql =~ s/\b(CREATE[[:blank:]]+(?:.*?)\bTABLE(?:[[:blank:]]+IF[[:blank:]]+NOT[[:blank:]]+EXISTS)?)[[:blank:]]+$name\b/$1 ${schema}.${name}/si;
787 }
788 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" ) );
789 return( $rv );
790 }
791  
792 # sub create_table($;%)
793  
794 # See DB::Object
795 # sub data_sources($;\%)
796  
797 # sub data_type
798  
799 # NOTE: sub datatype_dict is inherited
800  
801 # NOTE: sub datatypes is in inherited
802  
803 # sub database
804  
805 sub databases
806 {
807 my $self = shift( @_ );
808 # return( $self->error( "Not connected to PostgreSQL server yet. Issue $dbh->connect first." ) ) if( !$self->{ 'dbh' } );
809 my $dbh;
810 # If there is no connection yet, then create one using the postgres login.
811 # There should not be a live user and database just to check what databases there are.
812 if( !$self->{dbh} )
813 {
814 # try-catch
815 local $@;
816 $dbh = eval
817 {
818 $self->connect;
819 };
820 if( $@ )
821 {
822 return( $self->error( "Error trying to connect to the PostgreSQL server: $@" ) );
823 }
824 $dbh or return( $self->pass_error );
825 }
826 else
827 {
828 $dbh = $self;
829 }
830 my $temp = $dbh->do( "SELECT datname FROM pg_database" )->fetchall_arrayref;
831 return( $self->error( $dbh->errstr ) ) if( !$temp );
832 my @dbases = map( $_->[0], @$temp );
833 return( @dbases );
834 }
835  
836 # delete() is inherited from DB::Object
837 # sub delete
838  
839 # sub disconnect($)
840  
841 # sub do($;$@)
842  
843 # sub enhance
844  
845 # See DB::Object
846 # sub err(@)
847 # Meaning of the error code
848 # 0 Empty query string
849 # 1 A command that returns no data successfully completed.
850 # 2 A command that returns data successfully completed.
851 # 3 A COPY OUT command is still in progress.
852 # 4 A COPY IN command is still in progress.
853 # 5 A bad response was received from the backend.
854 # 6 A nonfatal error occurred (a notice or warning message)
855 # 7 A fatal error was returned: the last query failed.
856  
857 # See DB::Object
858 # sub errno
859  
860 # See DB::Object
861 # sub errmesg
862  
863 # See DB::Object
864 # sub errstr(@)
865 # Affected by the pg_errorlevel setting
866  
867 # sub fatal
868  
869 # sub from_unixtime
870  
871 # Inherited from DB::Object
872 # sub format_statement($;\%\%@)
873  
874 # sub format_update($;%)
875  
876 sub func
877 {
878 my $self = shift( @_ );
879 my $table = shift( @_ );
880 # e.g. table_attributes to get the detail information on table columns
881 my $func_name = shift( @_ );
882 # Returns:
883 # NAME attribute name
884 # TYPE attribute type
885 # SIZE attribute size (-1 for variable size)
886 # NULLABLE flag nullable
887 # DEFAULT default value
888 # CONSTRAINT constraint
889 # PRIMARY_KEY flag is_primary_key
890 # REMARKS attribute description
891 return( $self->{ 'dbh' }->func( $table, $func_name ) );
892 }
893  
894 # See DB::Object
895 # sub getdefault($;%)
896  
897 # sub group
898  
899 sub get_sql_type
900 {
901 my $self = shift( @_ );
902 my $type = shift( @_ ) || return( $self->error( "No sql type was provided to get its constant." ) );
903 $type = lc( $type );
904 if( CORE::exists( $DATATYPES_DICT->{ $type } ) &&
905 $type ne $DATATYPES_DICT->{ $type }->{type} )
906 {
907 $type = $DATATYPES_DICT->{ $type }->{type};
908 }
909 my $const;
910 if( substr( $type, 0, 3 ) eq 'pg_' )
911 {
912 $const = $self->{dbh}->can( "DBD::Pg::\U${type}\E" );
913 }
914 else
915 {
916 $const = $self->{dbh}->can( "DBD::Pg::PG_\U${type}\E" );
917 }
918 return( '' ) if( !defined( $const ) );
919 return( $const->() );
920 }
921  
922 # Specific to Postgres
923 sub having
924 {
925 my $self = shift( @_ );
926 my $q = $self->_reset_query;
927 return( $q->having( @_ ) );
928 }
929  
930 # See DB::Object
931 # sub insert
932  
933 sub large_object
934 {
935 my $self = shift( @_ );
936 return( $self->error( "large_object() cannot be called as a class function." ) ) if( !ref( $self ) );
937 $self->_load_class( 'DB::Object::Postgres::Lo' ) || return( $self->pass_error );
938 # Parameter is a bitmask mode
939 return( DB::Object::Postgres::Lo->new( $self->{dbh} ) );
940 }
941  
942 # Must be superseded, or better yet, the one in DB::Object should probably be changed to ours
943 sub last_insert_id
944 {
945 my $self = shift( @_ );
946 my $table = shift( @_ ) || $self->{ 'table' };
947 return( $self->{ 'dbh' }->last_insert_id( undef, undef, $table, undef ) );
948 }
949  
950 # http://www.postgresql.org/docs/9.3/interactive/queries-limit.html
951 # See DB::Object::Postgres::Query
952 # sub limit
953  
954 # sub local
955  
956 # http://www.postgresql.org/docs/current/static/sql-lock.html
957 sub lock
958 {
959 my $self = shift( @_ );
960 my $table = shift( @_ ) || return( $self->error( "You must provide a table name to lock onto." ) );
961 # ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE |
962 # SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVE
963 my $mode = shift( @_ ) || undef();
964 my $nowait= shift( @_ );
965 my $query = "LOCK TABLE $table";
966 $query .= " IN $mode MODE" if( defined( $mode ) );
967 $query .= " NOWAIT" if( $nowait );
968 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
969 my $sth = $dbh->prepare( $query ) ||
970 return( $self->error( "Error while preparing query to get lock on table '$table': ", $dbh->errstr() ) );
971 $sth->execute() ||
972 return( $self->error( "Error while executing query to get lock on table '$table': ", $sth->errstr() ) );
973 my $res = $sth->fetchrow;
974 $sth->finish();
975 # We do not really need to track that information.
976 # $self->{ '_locks' } ||= [];
977 # push( @{ $self->{ '_locks' } }, $table ) if( $res && $res ne 'NULL' );
978 return( $res eq 'NULL' ? ( wantarray() ? () : undef() ) : $res );
979 }
980  
981 sub make_schema
982 {
983 my $self = shift( @_ );
984 my $db = shift( @_ ) || $self->{ 'database' };
985 my $dbh;
986 if( $self->{ 'dbh' } )
987 {
988 $dbh = $self;
989 }
990 else
991 {
992 $dbh = $self->connect( { 'login' => 'postgres', 'database' => $db } ) || return( $self->error( "Cannot connect to Postgres database $db: " . $self->error ) );
993 }
994 my $tables = $dbh->tables;
995 return( $self->error( "There is no table in database $db." ) ) if( !@$tables );
996 my @schema_tables = ();
997 my $max_field_size = <<SQL;
998 SELECT MAX(LENGTH(a.attname)) AS "max_length"
999 FROM pg_class c, pg_attribute a, pg_authid o
1000 WHERE c.relkind IN ('r', 'v', 'm', 'f') AND a.attrelid=c.oid AND c.relowner=o.oid AND o.rolname != 'postgres'
1001 SQL
1002 my $inherited_fields = <<SQL;
1003 SELECT c.relname AS table, a.attname AS field
1004 FROM pg_class c
1005 JOIN pg_inherits i ON c.oid = i.inhrelid
1006 JOIN pg_attribute a ON i.inhparent = a.attrelid
1007 WHERE attnum > 0
1008 SQL
1009 my $table_info = <<SQL;
1010 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
1011 LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)
1012 WHERE c.relname ~ '^(%s)\$'
1013 SQL
1014 my $field_info = <<SQL;
1015 SELECT a.attname,
1016 pg_catalog.format_type(a.atttypid, a.atttypmod),
1017 (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
1018 FROM pg_catalog.pg_attrdef d
1019 WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),
1020 a.attnotnull, a.attnum,
1021 (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t
1022 WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation,
1023 NULL AS indexdef,
1024 NULL AS attfdwoptions
1025 FROM pg_catalog.pg_attribute a
1026 WHERE a.attrelid = ? AND a.attnum > 0 AND NOT a.attisdropped
1027 ORDER BY a.attnum
1028 SQL
1029 my $get_constraints = <<SQL;
1030 SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),
1031 pg_catalog.pg_get_constraintdef(con.oid, true), contype, condeferrable, condeferred, c2.reltablespace
1032 FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
1033 LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))
1034 WHERE c.oid = ? AND c.oid = i.indrelid AND i.indexrelid = c2.oid
1035 ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname
1036 SQL
1037 my $get_check_constraint = <<SQL;
1038 SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true)
1039 FROM pg_catalog.pg_constraint r
1040 WHERE r.conrelid = ? AND r.contype = 'c'
1041 ORDER BY 1
1042 SQL
1043 my $get_fkey_constraint = <<SQL;
1044 SELECT conname,
1045 pg_catalog.pg_get_constraintdef(r.oid, true) as condef
1046 FROM pg_catalog.pg_constraint r
1047 WHERE r.conrelid = ? AND r.contype = 'f' ORDER BY 1
1048 SQL
1049 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";
1050 my $get_tbl_comment = "SELECT description FROM pg_description WHERE (SELECT relname FROM pg_class WHERE oid=objoid) = ? and objsubid = 0";
1051 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";
1052  
1053 # Get the max size of the fields to properly format the schema
1054 my $sth = $dbh->{dbh}->prepare_cached( $max_field_size ) || return( $self->error( $dbh->{dbh}->errstr ) );
1055 $sth->execute() || return( $self->error( $sth->errstr ) );
1056 my $fsize = $sth->fetchrow;
1057 $sth->finish;
1058  
1059 # Get the list of all inherited fields per table, so we can exclude them in the schema we produce.
1060 $sth = $dbh->{dbh}->prepare_cached( $inherited_fields ) || return( $self->error( $dbh->{dbh}->errstr ) );
1061 $sth->execute() || return( $self->error( $sth->errstr ) );
1062 my $all = $sth->fetchall_arrayref( {} );
1063 my $inherited = {};
1064 foreach my $h ( @$all )
1065 {
1066 $inherited->{ $h->{ 'table' } } = [] if( !exists( $inherited->{ $h->{ 'table' } } ) );
1067 push( @{$inherited->{ $h->{ 'table' } }}, $h->{ 'field' } );
1068 }
1069 $sth->finish;
1070  
1071 foreach my $t ( @$tables )
1072 {
1073 my @table_def = ( "CREATE TABLE $t (" );
1074 # Get table overall information
1075 $dbh->bind( 0 );
1076 $sth = $dbh->{dbh}->prepare_cached( sprintf( $table_info, $t ) ) || return( $self->error( $dbh->{dbh}->errstr ) );
1077 $sth->execute() || return( $self->error( $sth->errstr ) );
1078 my $tbl_info = $sth->fetchrow_hashref();
1079 $sth->finish;
1080 $dbh->bind( 1 );
1081  
1082 # Get field info.
1083 $sth = $dbh->{Dbh}->prepare_cached( $field_info ) || return( $self->error( $dbh->{dbh}->errstr ) );
1084 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1085 my $rows = $sth->fetchall_arrayref( {} );
1086 foreach my $r ( @$rows )
1087 {
1088 next if( exists( $inherited->{ $t } ) && grep( /^$r->{ 'attname' }$/, @{$inherited->{ $t }} ) );
1089 my @col_def = ( sprintf( "\t%-${fsize}s %s", $r->{ 'attname' }, uc( $r->{ 'format_type' } ) ) );
1090 push( @col_def, 'NOT NULL' ) if( $r->{ 'attnotnull' } );
1091 if( $r->{ 'format_type' } =~ /^(integer|int|boolean|decimal)$/i )
1092 {
1093 push( @col_def, sprintf( 'DEFAULT %s', $r->{ 'substring' } ) ) if( $r->{ 'substring' } );
1094 }
1095 else
1096 {
1097 push( @col_def, sprintf( "DEFAULT '%s'", $r->{ 'substring' } ) ) if( $r->{ 'substring' } );
1098 }
1099 push( @table_def, join( " ", @col_def ) );
1100 }
1101 $sth->finish;
1102 my @constraints = ();
1103 my @index = ();
1104 # Get primary key and unique index constraints
1105 $sth = $dbh->{dbh}->prepare_cached( $get_constraints ) || return( $self->error( $dbh->{dbh}->errstr ) );
1106 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1107 $rows = $sth->fetchall_arrayref( {} );
1108 foreach my $r ( @$rows )
1109 {
1110 if( $r->{ 'indisprimary' } || $r->{ 'indisunique' } )
1111 {
1112 push( @constraints, sprintf( "\tCONSTRAINT %s %s", @$r{ qw( relname pg_get_constraintdef ) } ) );
1113 }
1114 else
1115 {
1116 push( @index, sprintf( 'CREATE INDEX %s;', $r->{ 'pg_get_indexdef' } ) );
1117 }
1118 }
1119 $sth->finish;
1120 # Get CHECK constraints
1121 $sth = $dbh->{dbh}->prepare_cached( $get_check_constraint ) || return( $self->error( $dbh->{dbh}->errstr ) );
1122 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1123 $rows = $sth->fetchall_arrayref( {} );
1124 foreach my $r ( @$rows )
1125 {
1126 push( @constraints, sprintf( "\tCONSTRAINT %s %s", @$r{ qw( conname pg_get_constraintdef ) } ) );
1127 }
1128 $sth->finish;
1129 # Get foreign key constraints
1130 $sth = $dbh->{dbh}->prepare_cached( $get_fkey_constraint ) || return( $self->error( $dbh->{dbh}->errstr ) );
1131 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1132 $rows = $sth->fetchall_arrayref( {} );
1133 foreach my $r ( @$rows )
1134 {
1135 push( @constraints, sprintf( "\tCONSTRAINT %s %s", @$r{ qw( conname condef ) } ) );
1136 }
1137 $sth->finish;
1138 push( @table_def, @constraints );
1139  
1140 # Get table inheritance
1141 $sth = $dbh->{dbh}->prepare_cached( $inheritance ) || return( $self->error( $dbh->{dbh}->errstr ) );
1142 $sth->execute( $tbl_info->{ 'oid' } ) || return( $self->error( $sth->errstr ) );
1143 $rows = $sth->fetchall_arrayref( {} );
1144 my @inherit = map{ $_->{ 'oid' } } @$rows;
1145 $sth->finish;
1146  
1147 # Add a comma at the end of each line now we know how many there are.
1148 for( my $i = 0; $i < $#table_def; $i++ )
1149 {
1150 $table_def[ $i ] .= ",";
1151 }
1152  
1153 if( @inherit )
1154 {
1155 push( @table_def, sprintf( ') INHERITS (%s);', join( ", ", @inherit ) ) );
1156 }
1157 else
1158 {
1159 push( @table_def, ');' );
1160 }
1161  
1162 # Put here the table indexes
1163 push( @table_def, @index );
1164  
1165 # Get comments on the table itself, if any
1166 $sth = $dbh->{dbh}->prepare_cached( $get_tbl_comment ) || return( $self->error( $sth->{dbh}->errstr ) );
1167 $sth->execute( $t ) || return( $self->error( $sth->errstr ) );
1168 my $ref = $sth->fetchrow_hashref();
1169 $sth->finish;
1170 push( @table_def, sprintf( "COMMENT ON TABLE %s IS '%s';", $t, $ref->{ 'description' } ) ) if( $ref->{ 'description' } );
1171  
1172 # Get comments for each field
1173 $sth = $dbh->{dbh}->prepare_cached( $get_field_comment ) || return( $self->error( $sth->{dbh}->errstr ) );
1174 $sth->execute( $t ) || return( $self->error( $sth->errstr ) );
1175 $rows = $sth->fetchall_arrayref( {} );
1176 $sth->finish;
1177 foreach my $r ( @$rows )
1178 {
1179 push( @table_def, sprintf( "COMMENT ON COLUMN %s.%s IS '%s';", $t, @$r{ qw( attname description ) } ) );
1180 }
1181 push( @schema_tables, join( "\n", @table_def ) );
1182 }
1183 return( wantarray() ? @schema_tables : join( "\n\n", @schema_tables ) );
1184 }
1185  
1186 # sub no_bind
1187  
1188 # sub no_cache
1189  
1190 # sub order
1191  
1192 # See DB::Object
1193 # sub param
1194  
1195 sub pg_notifies
1196 {
1197 my $self = shift( @_ );
1198 my $dbh;
1199 if( $self->{dbh} )
1200 {
1201 $dbh = $self->{dbh};
1202 }
1203 elsif( $self->can( 'database_object' ) )
1204 {
1205 $dbh = $self->database_object ||
1206 return( $self->error( "No database object is set on this table object." ) );
1207 $dbh = $dbh->{dbh} || return( $self->error( "No database handler is set on our database object." ) );
1208 }
1209 else
1210 {
1211 return( $self->error( "The object of class ", ( ref( $self ) || $self ), " has no property 'dbh'." ) );
1212 }
1213  
1214 # try-catch
1215 local $@;
1216 my $ref = eval
1217 {
1218 $dbh->pg_notifies;
1219 };
1220 if( $@ )
1221 {
1222 return( $self->error( "Error calling PostgreSQL function pg_notifies: $@" ) );
1223 }
1224 return( $ref );
1225 }
1226  
1227 sub pg_ping(@)
1228 {
1229 return( shift->{dbh}->pg_ping );
1230 }
1231  
1232 # See DB::Object
1233 # sub ping(@)
1234  
1235 # See DB::Object
1236 # sub prepare($;$)
1237  
1238 # See DB::Object
1239 # sub prepare_cached
1240  
1241 # sub query($$)
1242  
1243 sub query_object { return( shift->_set_get_object( 'query_object', 'DB::Object::Postgres::Query', @_ ) ); }
1244  
1245 # sub quote will be automatically loaded via AUTOLOADER
1246  
1247 sub quote
1248 {
1249 my $self = shift( @_ );
1250 my( $str, $type ) = @_;
1251 # my $dbh = $self->{dbh} || return( $self->error( "No database handler was set." ) );
1252 my $dbh;
1253 unless( $dbh = $self->{dbh} )
1254 {
1255 return( $self->SUPER::quote( $str ) );
1256 }
1257 $type = { pg_type => $type } if( $type && ref( $type ) ne 'HASH' );
1258 return( $dbh->quote( $str, $type ) );
1259 }
1260  
1261 sub release
1262 {
1263 return( shift->{dbh}->pg_release( @_ ) );
1264 }
1265  
1266 sub replace
1267 {
1268 return( shift->error( "Replace queries are not supported in PostgreSQL" ) );
1269 }
1270  
1271 # sub reset
1272  
1273 # sub reverse
1274  
1275 # sub rollback will be automatically loaded via AUTOLOADER
1276  
1277 # Specific to Postgres
1278 sub returning
1279 {
1280 my $self = shift( @_ );
1281 my $q = $self->_reset_query;
1282 return( $q->returning( @_ ) );
1283 }
1284  
1285 sub rollback
1286 {
1287 return( shift->{dbh}->rollback() );
1288 }
1289  
1290 sub rollback_to(@)
1291 {
1292 return( shift->{dbh}->pg_rollback_to( @_ ) );
1293 }
1294  
1295 sub savepoint(@)
1296 {
1297 return( shift->{dbh}->pg_savepoint( @_ ) );
1298 }
1299  
1300 sub schema { return( shift->_set_get_scalar( 'schema', @_ ) ); }
1301  
1302 sub search_path
1303 {
1304 my $self = shift( @_ );
1305 if( @_ )
1306 {
1307 my $val = @_ == 1
1308 ? $self->_is_array( $_[0] )
1309 ? shift( @_ )
1310 : [ @_ ]
1311 : [ @_ ];
1312 my $arg = sprintf( '"%s"', join( '", "', @$val ) );
1313 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1314 my $sth = $dbh->prepare_cached( "SET search_path = $arg" ) || return( $self->error( "Unable to prepare sql query to set search path: ", $dbh->errstr() ) );
1315 my $rc = $sth->execute() || return( $self->error( "Unable to execute sql query to set search path: ", $self->errstr() ) );
1316 $sth->finish;
1317 return( $rc );
1318 }
1319 else
1320 {
1321 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1322 my $sth = $dbh->prepare_cached( "SHOW search_path" ) || return( $self->error( "Unable to prepare sql query to get search path: ", $dbh->errstr() ) );
1323 my $rc = $sth->execute() || return( $self->error( "Unable to execute sql query to set search path: ", $self->errstr() ) );
1324 my $val = $sth->fetchrow;
1325 $sth->finish;
1326 my $arr = $self->new_array( [ split( /\,[[:blank:]]*/, $val ) ] );
1327 # Removing surrounding quotes
1328 for( my $i = 0; $i < scalar( @$arr ); $i++ )
1329 {
1330 $arr->[$i] =~ s/^\"|\"$//g;
1331 }
1332 return( $arr );
1333 }
1334 }
1335  
1336 # See DB::Object; _query_component is superseded and this makes the select customised to Posgres needs
1337 # sub select
1338  
1339 # See DB::Object
1340 # sub set
1341  
1342 # See DB::Object
1343 # sub sort
1344  
1345 # Was previously getfd()
1346 sub socket
1347 {
1348 return( shift->{dbh}->{pg_socket} );
1349 }
1350  
1351 # See DB::Object
1352 # sub stat
1353  
1354 # See DB::Object
1355 # sub state(@)
1356  
1357 # See DB::Object
1358 # sub table
1359  
1360 # See DB::Object
1361 sub table_exists
1362 {
1363 my $self = shift( @_ );
1364 my $table = shift( @_ ) ||
1365 return( $self->error( "You must provide a table name to access the table methods." ) );
1366 my $opts = $self->_get_args_as_hash( @_ );
1367 my $schema = $self->schema || $opts->{schema} || '';
1368 my $cache_tables = $self->cache_tables;
1369 my $tables_in_cache = $cache_tables->get({
1370 host => $self->host,
1371 driver => $self->driver,
1372 port => $self->port,
1373 database => $self->database,
1374 });
1375 foreach my $this ( @$tables_in_cache )
1376 {
1377 if( $this->{name} eq $table &&
1378 (
1379 ( $schema && $this->{schema} eq $schema ) ||
1380 ( !$schema || $opts->{anywhere} )
1381 ) )
1382 {
1383 return(1);
1384 }
1385 }
1386 # We did not find it, so let's try by checking directly the database
1387 my $def = $self->table_info( $table ) || return;
1388 return(1) if( scalar( @$def ) );
1389 return(0);
1390 }
1391  
1392 sub table_info
1393 {
1394 my $self = shift( @_ );
1395 my $table = shift( @_ ) ||
1396 return( $self->error( "You must provide a table name to access the table methods." ) );
1397 my $opts = $self->_get_args_as_hash( @_ );
1398 my $schema = $self->schema || $opts->{schema} || '';
1399 my $sql = <<'EOT';
1400 SELECT
1401 n.nspname AS "schema"
1402 ,c.relname AS "name"
1403 ,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"
1404 ,pg_catalog.pg_get_userbyid(c.relowner) AS "owner"
1405 FROM pg_catalog.pg_class c
1406 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1407 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 = ?
1408 EOT
1409 my $dbh = $self->{dbh} || return( $self->error( "Could not find database handler." ) );
1410 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 ) );
1411 $sth->execute( $table ) || return( $self->error( "An error occured while executing query to check if table \"$table\" exists in our database: ", $sth->errstr ) );
1412 my $all = $sth->fetchall_arrayref( {} );
1413 $sth->finish;
1414 return( [] ) if( !scalar( @$all ) );
1415 return( $all ) if( !$schema || $opts->{anywhere} );
1416 foreach my $ref ( @$all )
1417 {
1418 return( $ref ) if( $ref->{schema} eq $schema );
1419 }
1420 return( [] );
1421 }
1422  
1423 # See DB::Object
1424 # sub table_push
1425  
1426 # See DB::Object
1427 # sub tables
1428  
1429 sub tables_info
1430 {
1431 my $self = shift( @_ );
1432 my $db = shift( @_ ) || $self->{database};
1433 my @tables = ();
1434 # Parameters are: ?, schema, table, and type
1435 # my $sth = $self->{ 'dbh' }->table_info( undef, undef, $table, "TABLE,VIEW" );
1436 # The original query was fetched by connecting to Postgres with psql -E and executing the command \z
1437 # This revised query will fetch only tables, views, materialised view and foreign tables, but will avoid the mysterious view called sequence_setvals
1438 # my $query = <<SQL;
1439 # SELECT n.nspname as "schema",
1440 # c.relname as "name"
1441 # FROM pg_catalog.pg_class c
1442 # LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1443 # WHERE c.relkind IN ('r', 'v', 'm', 'f')
1444 # AND n.nspname !~ '^pg_' AND pg_catalog.pg_table_is_visible(c.oid) AND c.relname != 'sequence_setvals'
1445 # ORDER BY c.oid
1446 # SQL
1447 # AND n.nspname OPERATOR(pg_catalog.~) '^((auth|public))$'
1448 my $query = <<'EOT';
1449 SELECT
1450 n.nspname as "schema"
1451 ,c.relname as "name"
1452 ,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"
1453 ,pg_catalog.pg_get_userbyid(c.relowner) as "owner"
1454 FROM pg_catalog.pg_class c
1455 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1456 WHERE c.relkind IN ('r','p','s','v','m','f','')
1457 AND n.nspname !~ '^(pg_|information_schema$)'
1458 AND c.relname != 'sequence_setvals'
1459 ORDER BY 1,2
1460 EOT
1461 my $sth = $self->{dbh}->prepare_cached( $query ) || return( $self->error( sprintf( "Error while preparing query $query: %s", $self->{dbh}->errstr ) ) );
1462 $sth->execute() || return( $self->error( sprintf( "Error while executing query $query: %s", $sth->errstr ) ) );
1463 my $all = $sth->fetchall_arrayref( {} );
1464 return( $all );
1465 }
1466  
1467 # See DB::Object
1468 # sub tables_refresh
1469  
1470 # See DB::Object
1471 # sub tie
1472  
1473 sub trace($;@)
1474 {
1475 my $self = shift( @_ );
1476 # Value is a numeric level; see parse_trace_flag.
1477 return( $self->error( "Trace can only be used on active connection. Use connect first." ) ) if( !$self->{dbh} );
1478 if( @_ )
1479 {
1480 # my( $opt, $filename ) = @_;
1481 $self->{dbh}->trace( @_ );
1482 }
1483 return( $self->{dbh}->trace );
1484 }
1485  
1486 sub trace_msg(@)
1487 {
1488 my $self = shift( @_ );
1489 return( $self->error( "Trace can only be used on active connection. Use connect first." ) ) if( !$self->{dbh} );
1490 # $dbh->trace_msg( $message_text, $min_level );
1491 return( $self->{dbh}->trace_msg( @_ ) );
1492 }
1493  
1494 # sub unix_timestamp
1495  
1496 sub unlock
1497 {
1498 shift->error( "unlock() does not work with Postgres." );
1499 }
1500  
1501 # See DB::Object
1502 # sub update
1503  
1504 # See DB::Object
1505 # sub use
1506  
1507 # See DB::Object
1508 # sub use_cache
1509  
1510 # See DB::Object
1511 # sub use_bind
1512  
1513 sub variables
1514 {
1515 return( shift->error( "variables is currently unsupported in Postgres" ) );
1516 }
1517  
1518 # See DB::Object
1519 # sub where
1520  
1521 # https://www.postgresql.org/docs/10/sql-show.html
1522 # show something exists since at lease from 7.1
1523 sub version
1524 {
1525 my $self = shift( @_ );
1526 # If we already have the information, let's use our cache instead of making a query
1527 return( $self->{_db_version} ) if( length( $self->{_db_version} ) );
1528 # e.g. 10.4
1529 my $sql = 'SHOW server_version';
1530 my $sth = $self->do( $sql ) || return( $self->error( "Unable to issue the sql statement '$sql' to get the server version: ", $self->errstr ) );
1531 my $ver = $sth->fetchrow;
1532 $sth->finish;
1533 # e.g.:
1534 # 12.1 (Ubuntu 12.1-1.pgdg16.04+1)
1535 # 10.4
1536 $ver =~ s/^(\d+(?:\.\S+)?).*?$/$1/;
1537 # We cache it
1538 $self->{_db_version} = version->parse( $ver );
1539 return( $ver );
1540 }
1541  
1542 sub _check_connect_param
1543 {
1544 my $self = shift( @_ );
1545 my $param = $self->SUPER::_check_connect_param( @_ ) || return( $self->pass_error );
1546 # This is also what the psql command line tool does
1547 $param->{login} = ( getpwuid( $> ) )[0] if( !$param->{login} );
1548 $param->{database} = 'postgres' if( !$param->{database} );
1549 # By default
1550 $param->{port} = 5432 if( !CORE::exists( $param->{port} ) );
1551 return( $param );
1552 }
1553  
1554 # Called from connect once all check was done to see if there are default to set
1555 sub _check_default_option
1556 {
1557 my $self = shift( @_ );
1558 my $opts = $self->_get_args_as_hash( @_ );
1559 return( $self->error( "Provided option is not a hash reference." ) ) if( !$self->_is_hash( $opts => 'strict' ) );
1560 $opts->{client_encoding} = 'utf8' if( !CORE::exists( $opts->{client_encoding} ) );
1561 # Enabled but with auto-guess
1562 $opts->{pg_enable_utf8} = -1 if( !CORE::exists( $opts->{pg_enable_utf8} ) && ( $opts->{client_encoding} eq 'utf8' || $opts->{client_encoding} eq 'utf-8' ) );
1563 return( $opts );
1564 }
1565  
1566 # Called by _check_connect_param
1567 sub _connection_options
1568 {
1569 my $self = shift( @_ );
1570 my $param = shift( @_ );
1571 my @pg_params = grep( /^pg_/, keys( %$param ) );
1572 my $opt = $self->SUPER::_connection_options( $param ) || return( $self->pass_error );
1573 @$opt{ @pg_params } = @$param{ @pg_params };
1574 return( $opt );
1575 }
1576  
1577 # NOTE: sub _connection_params2hash_driver is not necessary here. We use our parent's one.
1578  
1579 # Called by _check_connect_param
1580 sub _connection_parameters
1581 {
1582 my $self = shift( @_ );
1583 my $param = shift( @_ );
1584 my $core = [qw(
1585 db login passwd host port driver database schema server opt uri debug
1586 cache_connections cache_dir cache_query cache_table connect_via unknown_field
1587 use_cache
1588 )];
1589 my @pg_params = grep( /^pg_/, keys( %$param ) );
1590 # See DBD::mysql for the list of valid parameters
1591 # E.g.: mysql_client_found_rows, mysql_compression mysql_connect_timeout mysql_write_timeout mysql_read_timeout mysql_init_command mysql_skip_secure_auth mysql_read_default_file mysql_read_default_group mysql_socket mysql_ssl mysql_ssl_client_key mysql_ssl_client_cert mysql_ssl_ca_file mysql_ssl_ca_path mysql_ssl_cipher mysql_local_infile mysql_multi_statements mysql_server_prepare mysql_server_prepare_disable_fallback mysql_embedded_options mysql_embedded_groups mysql_conn_attrs
1592 push( @$core, @pg_params );
1593 return( $core );
1594 }
1595  
1596 sub _dsn
1597 {
1598 my $self = shift( @_ );
1599 my @params = ();
1600 # See pg_service.conf
1601 if( $self->{service} )
1602 {
1603 @params = ( sprintf( 'dbi:%s:%s', @$self{ qw( driver service ) } ) );
1604 }
1605 else
1606 {
1607 # It ends with ':'
1608 @params = ( sprintf( 'dbi:%s:', $self->{driver} ) );
1609 }
1610 push( @params, sprintf( 'dbname=%s', $self->{database} ) ) if( $self->{database} );
1611 push( @params, sprintf( 'host=%s', $self->{host} ) ) if( $self->{host} );
1612 push( @params, sprintf( 'port=%d', $self->{port} ) ) if( $self->{port} );
1613 # push( @params, "options=$options" ) if( length( $options ) );
1614 return( join( ';', @params ) );
1615 }
1616  
1617 # NOTE: _cache_this -> See DB::Object
1618 # sub _cache_this
1619  
1620 # NOTE _clean_statement -> DB::Object
1621 # sub _clean_statement
1622  
1623 # NOTE _cleanup -> DB::Object
1624 # sub _cleanup
1625  
1626 # NOTE _dbi_connect -> DB::Object
1627 # sub _dbi_connect
1628  
1629 # NOTE _make_sth -> DB::Object
1630 # sub _make_sth
1631  
1632 sub _placeholder_regexp { return( $PLACEHOLDER_REGEXP ) }
1633  
1634 # Moved to DB::Object::Postgres::Query
1635 # sub _query_components
1636  
1637 # See DB::Object. The meat of it is really in DB::Object::Query
1638 # sub _reset_query
1639  
1640 # See DB::Object
1641 # sub _save_bind
1642  
1643 # See DB::Object
1644 # sub _value2bind
1645  
1646 # AUTOLOAD is inherited
1647 # AUTOLOAD
1648  
1649 # NOTE: DESTROY
1650 DESTROY
1651 {
1652 # <https://perldoc.perl.org/perlobj#Destructors>
1653 CORE::local( $., $@, $!, $^E, $? );
1654 CORE::return if( ${^GLOBAL_PHASE} eq 'DESTRUCT' );
1655 my $self = CORE::shift( @_ );
1656 CORE::return if( !CORE::defined( $self ) );
1657 my $class = ref( $self ) || $self;
1658 if( $self->{sth} )
1659 {
1660 # print( STDERR "DESTROY(): Terminating sth '$self' for query:\n$self->{ 'query' }\n" ) if( $DEBUG );
1661 $self->{sth}->finish();
1662 }
1663 elsif( $self->{dbh} && $class =~ /^AI\:\:DB\:\:Postgres$/ )
1664 {
1665 local( $SIG{__WARN__} ) = sub { };
1666 # $self->{ 'dbh' }->disconnect();
1667 if( $DEBUG )
1668 {
1669 my( $pack, $file, $line, $sub ) = ( caller( 0 ) )[ 0, 1, 2, 3 ];
1670 my( $pack2, $file2, $line2, $sub2 ) = ( caller( 1 ) ) [ 0, 1, 2, 3 ];
1671 print( STDERR "DESTROY database handle ($self) [$self->{query}]\ncalled within sub '$sub' ($sub2) from package '$pack' ($pack2) in file '$file' ($file2) at line '$line' ($line2).\n" );
1672 }
1673 $self->disconnect();
1674 }
1675 my $locks = $self->{_locks};
1676 if( $locks && $self->_is_array( $locks ) )
1677 {
1678 foreach my $name ( @$locks )
1679 {
1680 $self->unlock( $name );
1681 }
1682 }
1683 }
1684  
1685 1;
1686 # NOTE: POD
1687 __END__
1688  
1689 =encoding utf8
1690  
1691 =head1 NAME
1692  
1693 DB::Object::Postgres - SQL API
1694  
1695 =head1 SYNOPSIS
1696  
1697 use DB::Object::Postgres;
1698  
1699 my $dbh = DB::Object::Postgres->connect({
1700 driver => 'Pg',
1701 conf_file => 'db-settings.json',
1702 database => 'webstore',
1703 host => 'localhost',
1704 login => 'store-admin',
1705 schema => 'auth',
1706 debug => 3,
1707 }) || bailout( "Unable to connect to sql server on host localhost: ", DB::Object->error );
1708  
1709 # Legacy regular query
1710 my $sth = $dbh->prepare( "SELECT login,name FROM login WHERE login='jack'" ) ||
1711 die( $dbh->errstr() );
1712 $sth->execute() || die( $sth->errstr() );
1713 my $ref = $sth->fetchrow_hashref();
1714 $sth->finish();
1715  
1716 # Get a list of databases;
1717 my @databases = $dbh->databases;
1718 # Doesn't exist? Create it:
1719 my $dbh2 = $dbh->create_db( 'webstore' );
1720 # Load some sql into it
1721 my $rv = $dbh2->do( $sql ) || die( $dbh->error );
1722  
1723 # Check a table exists
1724 $dbh->table_exists( 'customers' ) || die( "Cannot find the customers table!\n" );
1725  
1726 # Get list of tables, as array reference:
1727 my $tables = $dbh->tables;
1728  
1729 my $cust = $dbh->customers || die( "Cannot get customers object." );
1730 $cust->where( email => 'john@example.org' );
1731 my $str = $cust->delete->as_string;
1732 # Becomes: DELETE FROM customers WHERE email='john\@example.org'
1733  
1734 # Do some insert with transaction
1735 $dbh->begin_work;
1736 # Making some other inserts and updates here...
1737 my $cust_sth_ins = $cust->insert(
1738 first_name => 'Paul',
1739 last_name => 'Goldman',
1740 email => 'paul@example.org',
1741 active => 0,
1742 ) || do
1743 {
1744 # Rollback everything since the begin_work
1745 $dbh->rollback;
1746 die( "Error while create query to add data to table customers: " . $cust->error );
1747 };
1748 $result = $cust_sth_ins->as_string;
1749 # INSERT INTO customers (first_name, last_name, email, active) VALUES('Paul', 'Goldman', 'paul\@example.org', '0')
1750 $dbh->commit;
1751  
1752 # and more elaborate:
1753 # Ref: https://www.postgresql.org/docs/10/sql-insert.html#SQL-ON-CONFLICT
1754 $login->on_conflict({
1755 # mandatory, can be a constraint name or a field name or array of fields
1756 target => 'on constraint idx_prefs_unique',
1757 action => 'update',
1758 # where => '',
1759 # which fields to update. It can also be more specific by providing a hash ref like fields => { val => 'plop' }
1760 fields => [qw( val )],
1761 });
1762 # would become:
1763 insert into login (..) values(...) on conflict on constraint idx_prefs_unique do update set val = EXCLUDED.val;
1764  
1765 # Get the last used insert id
1766 my $id = $dbh->last_insert_id();
1767  
1768 $cust->where( email => 'john@example.org' );
1769 $cust->order( 'last_name' );
1770 $cust->having( email => qr/\@example/ );
1771 $cust->limit( 10 );
1772 my $cust_sth_sel = $cust->select || die( "An error occurred while creating a query to select data frm table customers: " . $cust->error );
1773 # Becomes:
1774 # SELECT id, first_name, last_name, email, created, modified, active, created::ABSTIME::INTEGER AS created_unixtime, modified::ABSTIME::INTEGER AS modified_unixtime, CONCAT(first_name, ' ', last_name) AS name FROM customers WHERE email='john\@example.org' HAVING email ~ '\@example' ORDER BY last_name LIMIT 10
1775  
1776 $cust->reset;
1777 $cust->where( email => 'john@example.org' );
1778 my $cust_sth_upd = $cust->update( active => 0 )
1779 # Would become:
1780 # UPDATE ONLY customers SET active='0' WHERE email='john\@example.org'
1781  
1782 # Lets' dump the result of our query
1783 # First to STDERR
1784 $login->where( "login='jack'" );
1785 $login->select->dump();
1786 # Now dump the result to a file
1787 $login->select->dump( "my_file.txt" );
1788  
1789 =head1 VERSION
1790  
1791 v1.5.1
1792  
1793 =head1 DESCRIPTION
1794  
1795 This package inherits from L<DB::Object>, so any method not here, but there you can use.
1796  
1797 L<DB::Object::Postgres> is a SQL API much alike L<DBD::Pg>.
1798 So why use a private module instead of using that great L<DBD::Pg> package?
1799  
1800 At first, I started to inherit from C<DBI> to conform to C<perlmod> perl
1801 manual page and to general perl coding guidlines. It became very quickly a
1802 real hassle. Barely impossible to inherit, difficulty to handle error, too
1803 much dependent from an API that change its behaviour with new versions.
1804 In short, I wanted a better, more accurate control over the SQL connection.
1805  
1806 So, L<DB::Object::Postgres> acts as a convenient, modifiable wrapper that provide the
1807 programmer with an intuitive, user-friendly and hassle free interface.
1808  
1809 =head1 CONSTRUCTOR
1810  
1811 =head2 new
1812  
1813 Create a new instance of L<DB::Object::Postgres>. Nothing much to say.
1814  
1815 =head2 connect
1816  
1817 Provided with a database, login, password, server, driver, and this will attempt a database connection.
1818  
1819 Create a new instance of L<DB::Object::Postgres>, but also attempts a connection to SQL server.
1820  
1821 You can specify the following parameters:
1822  
1823 =over 4
1824  
1825 =item * C<cache_connections>
1826  
1827 See L<DB::Object/connect> for more information
1828  
1829 =item * C<database>
1830  
1831 The database name you wish to connect to
1832  
1833 =item * C<login>
1834  
1835 The login used to access that database
1836  
1837 =item * C<password>
1838  
1839 The password that goes along
1840  
1841 =item * C<server>
1842  
1843 The server, that is hostname of the machine serving a SQL server.
1844  
1845 =item * C<driver>
1846  
1847 The driver you want to use. It needs to be of the same type than the server you want to connect to. If you are connecting to a MySQL server, you would use C<mysql>, if you would connecto to an Oracle server, you would use C<oracle>.
1848  
1849 You need to make sure that those driver are properly installed in the system before attempting to connect.
1850  
1851 To install the required driver, you could start with the command line:
1852  
1853 perl -MCPAN -e shell
1854  
1855 which will provide you a special shell to install modules in a convenient way.
1856  
1857 =back
1858  
1859 =head1 METHODS
1860  
1861 =head2 attribute
1862  
1863 Sets or gets one more pg attributes.
1864  
1865 Valid attributes are:
1866  
1867 =over 4
1868  
1869 =item * C<ActiveKids>
1870  
1871 Is read-only.
1872  
1873 =item * C<AutoCommit>
1874  
1875 Can be changed.
1876  
1877 =item * C<AutoInactiveDestroy>
1878  
1879 Can be changed.
1880  
1881 =item * C<CachedKids>
1882  
1883 Is read-only.
1884  
1885 =item * C<ChildHandles>
1886  
1887 Is read-only.
1888  
1889 =item * C<ChopBlanks>
1890  
1891 Can be changed.
1892  
1893 =item * C<CursorName>
1894  
1895 Is read-only.
1896  
1897 =item * C<Driver>
1898  
1899 Is read-only.
1900  
1901 =item * C<ErrCount>
1902  
1903 Can be changed.
1904  
1905 =item * C<Executed>
1906  
1907 Is read-only.
1908  
1909 =item * C<FetchHashKeyName>
1910  
1911 Can be changed.
1912  
1913 =item * C<HandleError>
1914  
1915 Can be changed.
1916  
1917 =item * C<HandleSetErr>
1918  
1919 Can be changed.
1920  
1921 =item * C<InactiveDestroy>
1922  
1923 Can be changed.
1924  
1925 =item * C<Kids>
1926  
1927 Is read-only.
1928  
1929 =item * C<NAME>
1930  
1931 Is read-only.
1932  
1933 =item * C<NULLABLE>
1934  
1935 Is read-only.
1936  
1937 =item * C<NUM_OF_FIELDS>
1938  
1939 Is read-only.
1940  
1941 =item * C<NUM_OF_PARAMS>
1942  
1943 Is read-only.
1944  
1945 =item * C<Name>
1946  
1947 Is read-only.
1948  
1949 =item * C<PRECISION>
1950  
1951 Is read-only.
1952  
1953 =item * C<PrintError>
1954  
1955 Can be changed.
1956  
1957 =item * C<PrintWarn>
1958  
1959 Can be changed.
1960  
1961 =item * C<Profile>
1962  
1963 Can be changed.
1964  
1965 =item * C<RaiseError>
1966  
1967 Can be changed.
1968  
1969 =item * C<ReadOnly>
1970  
1971 Can be changed.
1972  
1973 Specifies if the current database connection should be in read-only mode or not.
1974  
1975 =item * C<RowCacheSize>
1976  
1977 Is read-only.
1978  
1979 =item * C<RowsInCache>
1980  
1981 Is read-only.
1982  
1983 =item * C<SCALE>
1984  
1985 Is read-only.
1986  
1987 =item * C<ShowErrorStatement>
1988  
1989 Can be changed.
1990  
1991 =item * C<Statement>
1992  
1993 Is read-only.
1994  
1995 =item * C<TYPE>
1996  
1997 Is read-only.
1998  
1999 =item * C<Taint>
2000  
2001 Can be changed.
2002  
2003 =item * C<TaintIn>
2004  
2005 Can be changed.
2006  
2007 =item * C<TaintOut>
2008  
2009 Can be changed.
2010  
2011 =item * C<TraceLevel>
2012  
2013 Can be changed.
2014  
2015 =item * C<Type>
2016  
2017 Can be changed.
2018  
2019 =item * C<Username>
2020  
2021 Is read-only.
2022  
2023 =item * C<Warn>
2024  
2025 Can be changed.
2026  
2027 =item * C<pg_INV_READ>
2028  
2029 Is read-only.
2030  
2031 =item * C<pg_INV_WRITE>
2032  
2033 Is read-only.
2034  
2035 =item * C<pg_async_status>
2036  
2037 Is read-only.
2038  
2039 =item * C<pg_bool_tf>
2040  
2041 Can be changed.
2042  
2043 If true, boolean values will be returned as the characters 't' and 'f' instead of '1' and '0'.
2044  
2045 =item * C<pg_db>
2046  
2047 Is read-only.
2048  
2049 =item * C<pg_default_port>
2050  
2051 Is read-only.
2052  
2053 =item * C<pg_enable_utf8>
2054  
2055 Can be changed.
2056  
2057 =item * C<pg_errorlevel>
2058  
2059 Can be changed.
2060  
2061 Valid entries are 0, 1 and 2
2062  
2063 =item * C<pg_expand_array>
2064  
2065 Can be changed.
2066  
2067 =item * C<pg_host>
2068  
2069 Is read-only.
2070  
2071 =item * C<pg_lib_version>
2072  
2073 Is read-only.
2074  
2075 =item * C<pg_options>
2076  
2077 Is read-only.
2078  
2079 =item * C<pg_pass>
2080  
2081 Is read-only.
2082  
2083 =item * C<pg_pid>
2084  
2085 Is read-only.
2086  
2087 =item * C<pg_placeholder_dollaronly>
2088  
2089 Can be changed.
2090  
2091 When true, question marks inside of statements are not treated as placeholders, e.g. geometric operators
2092  
2093 =item * C<pg_placeholder_nocolons>
2094  
2095 Can be changed.
2096  
2097 When true, colons inside of statements are not treated as placeholders
2098  
2099 =item * C<pg_port>
2100  
2101 Is read-only.
2102  
2103 =item * C<pg_prepare_now>
2104  
2105 Can be changed.
2106  
2107 =item * C<pg_protocol>
2108  
2109 Is read-only.
2110  
2111 =item * C<pg_server_prepare>
2112  
2113 Can be changed.
2114  
2115 Indicates if L<DBD::Pg> should attempt to use server-side prepared statements. On by default
2116  
2117 =item * C<pg_server_version>
2118  
2119 Is read-only.
2120  
2121 =item * C<pg_socket>
2122  
2123 Is read-only.
2124  
2125 =item * C<pg_standard_conforming_strings>
2126  
2127 Is read-only.
2128  
2129 =item * C<pg_switch_prepared>
2130  
2131 Can be changed.
2132  
2133 =item * C<pg_user>
2134  
2135 Is read-only.
2136  
2137 =back
2138  
2139 =head2 begin_work
2140  
2141 Mark the beginning of a transaction.
2142  
2143 Any arguments provided are passed along to L<DBD::Pg/begin_work>
2144  
2145 =head2 commit
2146  
2147 Make any change to the database irreversible.
2148  
2149 This must be used only after having called L</begin_work>
2150  
2151 Any arguments provided are passed along to L<DBD::Pg/commit>
2152  
2153 =head2 connect
2154  
2155 Same as L<DB::Object/connect>, only specific to PostgreSQL.
2156  
2157 See L</_connection_params2hash>
2158  
2159 =head2 create_db
2160  
2161 Provided with a database name and some optional parameters and this will prepare and execute the query to create the database.
2162  
2163 Upon failure, this will return an error, and upon success, this will connect to the newly created database and return the database handler.
2164  
2165 Possible options are:
2166  
2167 =over 4
2168  
2169 =item * C<allowcon>
2170  
2171 Sets the C<ALLOW_CONNECTIONS> attribute
2172  
2173 "If false then no one can connect to this database. The default is true, allowing connections."
2174  
2175 =item * C<connlimit>
2176  
2177 Sets the C<CONNECTION LIMIT> attribute
2178  
2179 "How many concurrent connections can be made to this database. -1 (the default) means no limit."
2180  
2181 =item * C<encoding>
2182  
2183 Sets the C<ENCODING> attribute
2184  
2185 "Character set encoding to use in the new database."
2186  
2187 =item * C<lc_collate>
2188  
2189 Sets the C<LC_COLLATE> attribute
2190  
2191 "Collation order (LC_COLLATE) to use in the new database."
2192  
2193 =item * C<lc_ctype>
2194  
2195 Sets the C<LC_CTYPE> attribute
2196  
2197 "Character classification (LC_CTYPE) to use in the new database."
2198  
2199 =item * C<istemplate>
2200  
2201 Sets the C<IS_TEMPLATE> attribute
2202  
2203 "If true, then this database can be cloned by any user with CREATEDB privileges; if false (the default), then only superusers or the owner of the database can clone it."
2204  
2205 =item * C<owner>
2206  
2207 Sets the C<OWNER> attribute
2208  
2209 "The role name of the user who will own the new database"
2210  
2211 =item * C<tablespace>
2212  
2213 Sets the C<TABLESPACE> attribute
2214  
2215 "The name of the tablespace that will be associated with the new database"
2216  
2217 =item * C<template>
2218  
2219 Sets the C<TEMPLATE> attribute
2220  
2221 "The name of the template from which to create the new database"
2222  
2223 =back
2224  
2225 See L<PostgreSQL documentation for more information|https://www.postgresql.org/docs/9.5/sql-createdatabase.html>
2226  
2227 =head2 create_table
2228  
2229 Provided with a table name and some options as hash reference and this will create a new table.
2230  
2231 A mandatory parameter is I<sql> which must contain the sql script to be used.
2232  
2233 The sql script is executed using L<DB::Object/do> and the returned value is returned.
2234  
2235 =head2 databases
2236  
2237 Returns a list of all available databases.
2238  
2239 =head2 datatype_dict
2240  
2241 Returns an hash reference of each data type with their equivalent C<constant>, regular expression (C<re>), constant C<name> and C<type> name.
2242  
2243 Each data type is an hash with the following properties for each type: C<constant>, C<name>, C<re>, C<type>
2244  
2245 =head2 datatypes
2246  
2247 my $types = $dbh->datatypes;
2248  
2249 Returns an hash reference of data types to their respective values.
2250  
2251 It will return the PostgreSQL's constants.
2252  
2253 =head2 func
2254  
2255 Provided with a table name and a function name and this will call L<DBD::Pg/func> and returns the result.
2256  
2257 =head2 get_sql_type
2258  
2259 my $const $dbh->get_sql_type( 'bytea' );
2260 # returns 17
2261 my $const $dbh->get_sql_type( 'json' );
2262 # returns 114
2263 my $const $dbh->get_sql_type( 'jsonb' );
2264 # returns 3802
2265  
2266 Provided with a sql type, irrespective of the character case, and this will return the equivalent constant value.
2267  
2268 =head2 having
2269  
2270 A convenient wrapper to L<DB::Object::Postgres::Query/having>
2271  
2272 =head2 large_object
2273  
2274 Instantiate a new L<DB::Object::Postgres::Lo> and returns it.
2275  
2276 =head2 last_insert_id
2277  
2278 Get the id of the primary key from the last insert.
2279  
2280 =head2 lock
2281  
2282 Takes a table name, a lock mode and an optional C<nowait> and this will lock the given table by issuing the relevant query.
2283  
2284 Supported lock types are: C<SHARE>, C<SHARE ROW EXCLUSIVE>, C<EXCLUSIVE>, C<ACCESS EXCLUSIVE>
2285  
2286 If the lock failed (NULL), it returns undef(), otherwise, it returns the return value.
2287  
2288 =head2 make_schema
2289  
2290 Provided with a database name and this will create its schema.
2291  
2292 In list context, it returns an array of schema lines, and in scalar context, it returns the schema as a string.
2293  
2294 =head2 on_conflict
2295  
2296 See L<DB::Object::Postgres::Tables/on_conflict>
2297  
2298 =for Pod::Coverage pg_notifies
2299  
2300 =head2 pg_ping
2301  
2302 Calls L<DBD::Pg/pg_ping>
2303  
2304 =head2 query_object
2305  
2306 Set or gets the PostgreSQL query object (L<DB::Object::Postgres::Query>) used to process and format queries.
2307  
2308 =head2 quote
2309  
2310 Provided with a data and some data type, and this will possibly put surrounding single quotes and return the result.
2311  
2312 =head2 release
2313  
2314 $dbh->release( 'mysavepoint' );
2315  
2316 Calls L<DBD::pg_release> passing it through whatever arguments were provided.
2317  
2318 See also L<savepoint|/savepoint> and L<rollback_to|/rollback_to>
2319  
2320 =head2 replace
2321  
2322 Replace queries are not supported in PostgreSQL
2323  
2324 =head2 returning
2325  
2326 A convenient wrapper to L<DB::Object::Postgres::Query/returning>
2327  
2328 =head2 rollback
2329  
2330 Will roll back any changes made to the database since the last transaction point marked with L</begin_work>
2331  
2332 =head2 rollback_to
2333  
2334 $dbh->rollback_to( 'mysavepoint' );
2335  
2336 To be used inside a transaction. This will rollback any change up to the specified savepoint.
2337  
2338 Will call L<DBD::Pg/pg_rollback_to> and passing it through whatever arguments were provided.
2339  
2340 See also L<release|/release> and L<savepoint|/savepoint>
2341  
2342 =head2 savepoint
2343  
2344 $dbh->savepoint( 'mysavepoint' );
2345  
2346 To be used inside a transaction. This creates a savepoint, which you can L<rollback to|/rollback_to> or L<release/release>
2347  
2348 Will call L<DBD::Pg/pg_savepoint> and passing it through whatever arguments were provided.
2349  
2350 See also L<rollback_to|/rollback_to> and L<release|/release>
2351  
2352 =head2 schema
2353  
2354 Sets or gets the database schema.
2355  
2356 It returns the value as a L<Module:Generic::Scalar> object
2357  
2358 =head2 search_path
2359  
2360 If a search path is provided, this will issue the query to set it using C<SET search_path = $search_path> whatever C<$search_path> is. It returns the returned value from L<DBD::Pg/execute>
2361  
2362 If no arguments is provided, this will issue the query C<SHOW search_path> to retrieve the current search path.
2363  
2364 It returns an array object (L<Module::Generic::Array>) containing the search paths found.
2365  
2366 =head2 set
2367  
2368 This is inherited from L<DB::Object>
2369  
2370 Please see L<PostgreSQL documentation for the variables that can be set|https://www.postgresql.org/docs/10/runtime-config-client.html>.
2371  
2372 =head2 socket
2373  
2374 This returns the database handler property C<pg_socket>
2375  
2376 =head2 table_exists
2377  
2378 Provided with a table name and this will check if the table exists.
2379  
2380 It accepts the following options:
2381  
2382 =over 4
2383  
2384 =item * C<anywhere>
2385  
2386 If true, this will search anywhere.
2387  
2388 =item * C<schema>
2389  
2390 A database schema.
2391  
2392 =back
2393  
2394 =head2 table_info
2395  
2396 Provided with a table name and some optional parameters and this will retrieve the table information.
2397  
2398 It returns an array reference of tables information found if no schema was provided or if C<anywhere> is true.
2399  
2400 If a schema was provided, and the table found it returns an hash reference for that table.
2401  
2402 Otherwise, if nothing can be found, it returns an empty array reference.
2403  
2404 Optional parameters are:
2405  
2406 =over 4
2407  
2408 =item * C<anywhere>
2409  
2410 If true, it will search anywhere.
2411  
2412 =item * C<schema>
2413  
2414 A database schema.
2415  
2416 =back
2417  
2418 Information retrieved are:
2419  
2420 =over 4
2421  
2422 =item * C<name>
2423  
2424 The table name
2425  
2426 =item * C<schema>
2427  
2428 Database schema, if any.
2429  
2430 =item * C<type>
2431  
2432 The object type, which may be one of: C<table>, C<view>, C<materialized view>, C<special>, C<foreign table>
2433  
2434 =back
2435  
2436 =head2 tables_info
2437  
2438 Provided with a database name and this returns all the tables information.
2439  
2440 Information retrieved from the PostgreSQL system tables for every table found in the given database are:
2441  
2442 =over 4
2443  
2444 =item * C<name>
2445  
2446 The object name
2447  
2448 =item * C<owner>
2449  
2450 The object owner (role)
2451  
2452 =item * C<schema>
2453  
2454 Database schema, if any.
2455  
2456 =item * C<type>
2457  
2458 The object type, which may be one of: C<table>, C<view>, C<materialized view>, C<special>, C<foreign table>
2459  
2460 =back
2461  
2462 =head2 trace
2463  
2464 Calls L<DBD::Pg/trace> passing through whatever arguments were provided.
2465  
2466 =head2 trace_msg
2467  
2468 Calls L<DBD::Pg/trace_msg> and pass it whatever arguments were provided.
2469  
2470  
2471 =head2 unlock
2472  
2473 Unlock does not work with PostgreSQL
2474  
2475 =head2 table_info
2476  
2477 It returns an array reference of hash reference containing information about each table column.
2478  
2479 =head2 variables
2480  
2481 Variables are currently unsupported in Postgres
2482  
2483 =head2 version
2484  
2485 Returns the PostgreSQL database server version.
2486  
2487 This information is cached per object for efficiency.
2488  
2489 =head2 _check_connect_param
2490  
2491 Given some parameters hash and this will return a proper hash reference of parameters suitable for connection parameters.
2492  
2493 This will call L</_connection_parameters> to get the valid parameters and L</_connection_options> to get valid connection options based on the arguments provided.
2494  
2495 It returns the hash reference of connection parameters.
2496  
2497 =head2 _check_default_option
2498  
2499 Based on optional arguments and this will enable default options for the parameters provided.
2500  
2501 Currently this only check C<client_encoding> and set the default to C<utf8>
2502  
2503 It returns an hash reference of those parameters.
2504  
2505 =head2 _connection_options
2506  
2507 Based on an hash reference of parameters and this will call L<DB::Object/_connection_options> and return a new hash reference of keys starting with C<pg_>
2508  
2509 =head2 _connection_parameters
2510  
2511 Based on an hash reference of parameters, this will return an array reference of core properties plus additional PostgreSQL specific properties that start with C<pg_>
2512  
2513 The core properties are: C<db>, C<login>, C<passwd>, C<host>, C<port>, C<driver>, C<database>, C<schema>, C<server>, C<opt>, C<uri>, C<debug>
2514  
2515 =head2 _convert_datetime2object
2516  
2517 Based on an hash reference of parameters and this will transcode any datetime column into a L<DateTime> object.
2518  
2519 It returns the I<data> hash reference
2520  
2521 Possible parameters are:
2522  
2523 =over 4
2524  
2525 =item * C<data>
2526  
2527 An hash reference of data typically returned from a L<DBD::Pg/fetchrow_hashref>
2528  
2529 =item * C<statement>
2530  
2531 This is the statement from which to check for columns
2532  
2533 =back
2534  
2535 =head2 _convert_json2hash
2536  
2537 Based on an hash reference of parameters, and this will check for the I<data> for any json column and if found, it will transcode the json to hash reference.
2538  
2539 It returns the I<data> hash reference
2540  
2541 Possible parameters are:
2542  
2543 =over 4
2544  
2545 =item * C<data>
2546  
2547 An hash reference of data typically returned from a L<DBD::Pg/fetchrow_hashref>
2548  
2549 =item * C<statement>
2550  
2551 This is the statement from which to check for columns
2552  
2553 =back
2554  
2555 =head2 _dsn
2556  
2557 This returns a properly formatted C<dsn> as a string.
2558  
2559 =head1 SEE ALSO
2560  
2561 L<DBI>, L<Apache::DBI>
2562  
2563 =head1 AUTHOR
2564  
2565 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
2566  
2567 =head1 COPYRIGHT & LICENSE
2568  
2569 Copyright (c) 2019-2021 DEGUEST Pte. Ltd.
2570  
2571 You can use, copy, modify and redistribute this package and associated
2572 files under the same terms as Perl itself.
2573  
2574 =cut
« blib/lib/DB/Object/Fields/Overloaded.pm ↑ Summary lib/DB/Object/Fields/Overloaded.pm »