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

filter: Statementstmt 0.0% 0 / 255 Branchbran 0.0% 0 / 136 Conditioncond 0.0% 0 / 137 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 576 CC 69 SCAR 54.5
CC
69
Cov
0%
structure
702.0
create
210.0
create_info
42.0
CRAP 233.7
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Postgres/Tables.pm
4 ## Version v1.1.0
5 ## Copyright(c) 2024 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2026/03/22
9 ## All rights reserved
10 ##
11 ##
12 ## This program is free software; you can redistribute it and/or modify it
13 ## under the same terms as Perl itself.
14 ##----------------------------------------------------------------------------
15 ## This package's purpose is to separate the object of the tables from the main
16 ## DB::Object package so that when they get DESTROY'ed, it does not interrupt
17 ## the SQL connection
18 ##----------------------------------------------------------------------------
19 package DB::Object::Postgres::Tables;
20 BEGIN
21 {
22 use strict;
23 use warnings;
24 use parent qw( DB::Object::Tables DB::Object::Postgres );
25 use vars qw( $VERSION $DEBUG $EXCEPTION_CLASS );
26 our $DEBUG = 0;
27 our $EXCEPTION_CLASS = $DB::Object::EXCEPTION_CLASS;
28 our $VERSION = 'v1.1.0';
29 };
30  
31 use strict;
32 use warnings;
33  
34 sub init
35 {
36 # return( shift->DB::Object::Tables::init( @_ ) );
37 my $self = shift( @_ );
38 $self->{_init_params_order} = [qw( dbo query_object )];
39 $self->{_init_strict_use_sub} = 1;
40 $self->{_exception_class} = $EXCEPTION_CLASS;
41 $self->DB::Object::Tables::init( @_ ) || return( $self->pass_error );
42 return( $self );
43 }
44  
45 # Inherited from DB::Object::Tables
46 # sub alter
47  
48 sub create
49 {
50 my $self = shift( @_ );
51 # $tbl->create( [ 'ROW 1', 'ROW 2'... ], { 'temporary' => 1, 'TYPE' => ISAM }, $obj );
52 my $data = shift( @_ ) || [];
53 my $opt = shift( @_ ) || {};
54 my $sth = shift( @_ );
55 my $table = $self->{table};
56 # Set temporary in the object, so we can use it to recreate the table creation info as string:
57 # $table->create( [ ... ], { ... }, $obj )->as_string();
58 my $temp = $self->{temporary} = delete( $opt->{temporary} );
59 # Check possible options
60 my $allowed =
61 {
62 'inherits' => qr/^\w+$/i,
63 'with oids' => qr//,
64 'without oids' => qr//,
65 'on commit' => qr/^(PRESERVE ROWS|DELETE ROWS|DROP)$/,
66 'comment' => qr//,
67 'tablespace' => qr/^\w+$/,
68 };
69 my @options = ();
70 my @errors = ();
71 # Avoid working for nothing, make this condition
72 if( %$opt )
73 {
74 my %lc_opt = map{ lc( $_ ) => $opt->{ $_ } } keys( %$opt );
75 $opt = \%lc_opt;
76 foreach my $key ( keys( %$opt ) )
77 {
78 next if( $opt->{ $key } =~ /^\s*$/ || !exists( $allowed->{ $key } ) || $key eq "inherits" );
79 if( $opt->{ $key } !~ /$allowed->{ $key }/ )
80 {
81 push( @errors, $key );
82 }
83 else
84 {
85 push( @options, $key );
86 }
87 }
88 $opt->{ 'comment' } = "'" . quotemeta( $opt->{ 'comment' } ) . "'" if( exists( $opt->{ 'comment' } ) );
89 }
90 if( @errors )
91 {
92 warn( "The options '", join( ', ', @errors ), "' were either not recognized or malformed and thus were ignored.\n" );
93 }
94 # Check statement
95 my $select = '';
96 if( $sth && ref( $sth ) && ( $sth->isa( "DB::Object::Postgres::Statement" ) || $sth->can( 'as_string' ) ) )
97 {
98 $select = $sth->as_string();
99 if( $select !~ /^\s*(?:IGNORE|REPLACE)*\s*\bSELECT\s+/ )
100 {
101 return( $self->error( "SELECT statement to use to create table is invalid:\n$select" ) );
102 }
103 }
104 if( $self->exists() == 0 )
105 {
106 my $query = 'CREATE ' . ( $temp ? 'TEMPORARY ' : '' ) . "TABLE $table ";
107 # Structure of table if any -
108 # structure may very well be provided using a select statement, such as:
109 # CREATE TEMPORARY TABLE ploppy TYPE=HEAP COMMENT='this is kewl' MAX_ROWS=10 SELECT * FROM some_table LIMIT 0,0
110 my $def = "(\n" . CORE::join( ",\n", @$data ) . "\n)" if( $data && ref( $data ) && @$data );
111 $def .= " INHERITS (" . $opt->{ 'inherits' } . ")" if( $opt->{ 'inherits' } );
112 my $tdef = CORE::join( ' ', map{ "\U$_\E = $opt->{ $_ }" } @options );
113 if( !$def && !$select )
114 {
115 return( $self->error( "Lacking table '$table' structure information to create it." ) );
116 }
117 $query .= join( ' ', $def, $tdef, $select );
118 my $new = $self->database_object->prepare( $query ) ||
119 return( $self->error( "Error while preparing query to create table '$table':\n$query", $self->database_object->errstr() ) );
120 # Trick so other method may follow, such as as_string(), fetchrow(), rows()
121 if( !defined( wantarray() ) )
122 {
123 # print( STDERR "create(): wantarrays in void context.\n" );
124 $new->execute() ||
125 return( $self->error( "Error while executing query to create table '$table':\n$query", $new->errstr() ) );
126 }
127 $self->reset_structure;
128 $self->database_object->table_push( $table );
129 return( $new );
130 }
131 else
132 {
133 return( $self->error( "Table '$table' already exists." ) );
134 }
135 }
136  
137 sub create_info
138 {
139 my $self = shift( @_ );
140 my $table = $self->{table};
141 $self->structure || return( $self->pass_error );
142 my $struct = $self->{structure};
143 my $fields = $self->{fields};
144 my $default = $self->{default};
145 my $primary = $self->{primary};
146 my @output = ();
147 foreach my $field ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) )
148 {
149 push( @output, "$field $struct->{ $field }" );
150 }
151 push( @output, "PRIMARY KEY(" . CORE::join( ',', @$primary ) . ")" ) if( $primary && @$primary );
152 my $info = $self->stat( $table );
153 my @opt = ();
154 my $addons = $info->{create_options};
155 if( $addons )
156 {
157 $addons =~ s/(\A|\s+)([\w\_]+)\s*=\s*/$1\U$2\E=/g;
158 push( @opt, $addons );
159 }
160 push( @opt, "COMMENT='" . quotemeta( $info->{ 'comment' } ) . "'" ) if( $info->{comment} );
161 my $str = "CREATE TABLE $table (\n\t" . CORE::join( ",\n\t", @output ) . "\n)";
162 $str .= ' ' . CORE::join( ' ', @opt ) if( @opt );
163 $str .= ';';
164 return( @output ? $str : undef() );
165 }
166  
167 # NOTE: sub default is inherited from DB::Object::Tables
168 # sub default
169  
170 # <https://www.postgresql.org/docs/10/sql-altertable.html>
171 sub disable_trigger
172 {
173 my $self = shift( @_ );
174 my $table = $self->{table} ||
175 return( $self->error( "No table was provided to disable trigger." ) );
176 my $opts = $self->_get_args_as_hash( @_ );
177 $opts->{all} //= 0;
178 # This feature exists only since version 8.1
179 unless( $self->database_object->version >= version->declare( '8.1' ) )
180 {
181 return( $self->error( "Disabling trigger on a table requires PostgreSQL version 8.1 or higher." ) );
182 }
183 my $query = 'ALTER TABLE ' . $table . ' DISABLE TRIGGER ';
184 if( defined( $opts->{name} ) && length( $opts->{name} ) )
185 {
186 $query .= $opts->{name};
187 }
188 else
189 {
190 $query .= $opts->{all} ? 'ALL' : 'USER';
191 }
192 my $sth = $self->database_object->prepare( $query ) ||
193 return( $self->error( "Error while preparing query to disable trigger for table '$table':\n$query", $self->database_object->errstr() ) );
194 if( !defined( wantarray() ) )
195 {
196 $sth->execute() ||
197 return( $self->error( "Error while executing query to disable trigger for table '$table':\n$query", $sth->errstr() ) );
198 }
199 return( $sth );
200 }
201  
202 sub drop
203 {
204 my $self = shift( @_ );
205 my $table = $self->{table} ||
206 return( $self->error( "No table was provided to drop." ) );
207 my $opts = $self->_get_args_as_hash( @_ );
208 my $query = 'DROP TABLE';
209 $query .= ' IF EXISTS' if( $opts->{ 'if-exists' } || $opts->{if_exists} );
210 $query .= " $table";
211 if( $opts->{cascade} )
212 {
213 $query .= ' CASCADE';
214 }
215 ## Default Postgres behavior
216 elsif( $opts->{restrict} )
217 {
218 $query .= ' RESTRICT';
219 }
220 my $sth = $self->database_object->prepare( $query ) ||
221 return( $self->error( "Error while preparing query to drop table '$table':\n$query", $self->database_object->errstr() ) );
222 if( !defined( wantarray() ) )
223 {
224 $sth->execute() ||
225 return( $self->error( "Error while executing query to drop table '$table':\n$query", $sth->errstr() ) );
226 }
227 $self->reset_structure;
228 return( $sth );
229 }
230  
231 # <https://www.postgresql.org/docs/10/sql-altertable.html>
232 sub enable_trigger
233 {
234 my $self = shift( @_ );
235 my $table = $self->{table} ||
236 return( $self->error( "No table was provided to enable trigger." ) );
237 my $opts = $self->_get_args_as_hash( @_ );
238 $opts->{all} //= 0;
239 # This feature exists only since version 8.1
240 unless( $self->database_object->version >= version->declare( '8.1' ) )
241 {
242 return( $self->error( "Enabling trigger on a table requires PostgreSQL version 8.1 or higher." ) );
243 }
244 my $query = 'ALTER TABLE ' . $table . ' ENABLE TRIGGER ';
245 if( defined( $opts->{name} ) && length( $opts->{name} ) )
246 {
247 $query .= $opts->{name};
248 }
249 else
250 {
251 $query .= $opts->{all} ? 'ALL' : 'USER';
252 }
253 my $sth = $self->database_object->prepare( $query ) ||
254 return( $self->error( "Error while preparing query to disable trigger for table '$table':\n$query", $self->database_object->errstr() ) );
255 if( !defined( wantarray() ) )
256 {
257 $sth->execute() ||
258 return( $self->error( "Error while executing query to disable trigger for table '$table':\n$query", $sth->errstr() ) );
259 }
260 return( $sth );
261 }
262  
263 sub exists
264 {
265 my $self = shift( @_ );
266 return( $self->table_exists( @_ ? shift( @_ ) : $self->name ) );
267 }
268  
269 # NOTE: sub fields is inherited from DB::Object::Tables
270 # sub fields
271  
272 sub lock
273 {
274 my $self = shift( @_ );
275 my $table = $self->{table};
276 my $opt = shift( @_ ) || 'SHARE';
277 my $nowait = shift( @_ ) || undef();
278 if( $opt !~ /^(ACCESS SHARE|ROW SHARE|ROW EXCLUSIVE|SHARE UPDATE EXCLUSIVE|SHARE|SHARE ROW EXCLUSIVE|EXCLUSIVE|ACCESS EXCLUSIVE)$/i )
279 {
280 return( $self->error( "Bad table '$table' locking option '$opt'." ) );
281 }
282 my $query = sprintf( 'LOCK TABLE %s IN %s MODE', $table, $opt );
283 $query .= " NOWAIT" if( $nowait );
284 my $sth = $self->database_object->prepare( $query ) ||
285 return( $self->error( "Error while preparing query to do tables locking:\n$query", $self->database_object->errstr() ) );
286 if( !defined( wantarray() ) )
287 {
288 $sth->execute() ||
289 return( $self->error( "Error while executing query to do tables locking:\n$query", $sth->errstr() ) );
290 }
291 return( $sth );
292 }
293  
294 # NOTE: sub name is inherited from DB::Object::Tables
295 # sub name
296  
297 # NOTE: sub null is inherited from DB::Object::Tables
298 # sub null
299  
300 # NOTE: sub primary is inherited from DB::Object::Tables
301 # sub primary
302  
303 sub on_conflict
304 {
305 my $self = shift( @_ );
306 my $q = $self->_reset_query;
307 # Void
308 return( $q->on_conflict( @_ ) ) if( !defined( wantarray() ) );
309 if( wantarray() )
310 {
311 my( @val ) = $q->on_conflict( @_ ) || return( $self->pass_error( $q->error ) );
312 return( @val );
313 }
314 else
315 {
316 my $val = $q->on_conflict( @_ );
317 return( $self->pass_error( $q->error ) ) if( !defined( $val ) );
318 return( $val );
319 }
320 }
321  
322 sub optimize { return( shift->error( "optimize() is not implemented PostgreSQL." ) ); }
323  
324 sub parent { return( shift->_set_get_scalar( 'parent', @_ ) ); }
325  
326 sub qualified_name
327 {
328 my $self = shift( @_ );
329 my @val = ();
330 CORE::push( @val, $self->database_object->database ) if( $self->{prefixed} > 2 );
331 CORE::push( @val, $self->schema ) if( $self->{prefixed} > 1 && $self->schema );
332 CORE::push( @val, $self->name );
333 return( CORE::join( '.', @val ) );
334 }
335  
336 sub rename
337 {
338 my $self = shift( @_ );
339 my $table = $self->{table} ||
340 return( $self->error( 'No table was provided to rename' ) );
341 my $new = shift( @_ ) ||
342 return( $self->error( "No new table name was provided to rename table '$table'." ) );
343 if( $new !~ /^[\w\_]+$/ )
344 {
345 return( $self->error( "Bad new table name '$new'." ) );
346 }
347 my $query = "ALTER TABLE $table RENAME TO $new";
348 my $sth = $self->database_object->prepare( $query ) ||
349 return( $self->error( "Error while preparing query to rename table '$table' into '$new':\n$query", $self->database_object->errstr() ) );
350 if( !defined( wantarray() ) )
351 {
352 $sth->execute() ||
353 return( $self->error( "Error while executing query to rename table '$table' into '$new':\n$query", $sth->errstr() ) );
354 }
355 $self->reset_structure;
356 return( $sth );
357 }
358  
359 sub repair { return( shift->error( "repair() is not implemented PostgreSQL." ) ); }
360  
361 sub reset { return( shift->DB::Object::Tables::reset( @_ ) ); }
362  
363 sub stat { return( shift->error( "stat() is not implemented PostgreSQL." ) ); }
364  
365 sub structure
366 {
367 my $self = shift( @_ );
368 return( $self->_clone( $self->{_cache_structure} ) ) if( $self->{_cache_structure} && !CORE::length( $self->{_reset_structure} // '' ) );
369 my $table = $self->{table} ||
370 return( $self->error( "No table provided to get its structure." ) );
371 my $struct = $self->{structure} // {};
372 my $fields = $self->{fields} // {};
373 my $types_dict = $self->database_object->datatype_dict;
374 $self->_load_class( 'DB::Object::Fields::Field' ) || return( $self->pass_error );
375 my $q = $self->_reset_query;
376 # <https://stackoverflow.com/questions/6777456/list-all-index-names-column-names-and-its-table-name-of-a-postgresql-database>
377  
378 # If we have a cache, use it instead of reprocessing it.
379 # <https://stackoverflow.com/questions/52376045/why-does-atttypmod-differ-from-character-maximum-length>
380 # my $query = <<EOT;
381 # SELECT
382 # a.table_schema AS "schema_name"
383 # ,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 "table_type"
384 # ,a.column_name AS "field"
385 # ,a.ordinal_position AS "field_num"
386 # ,a.column_default AS "default"
387 # ,a.*
388 # FROM information_schema.columns a
389 # LEFT JOIN pg_catalog.pg_class c ON c.relname = a.table_name
390 # WHERE a.table_name = ?
391 # ORDER BY a.ordinal_position
392 # EOT
393 # <https://www.postgresql.org/docs/14/catalog-pg-attrdef.html>
394 # We could use:
395 # generate_subscripts(i.indkey, 1)
396 # instead of:
397 # generate_series(1,array_upper(string_to_array(i.indkey::text, ' ' )::int2[],1))
398 # but this is not supported by PostgreSQL v8.0; only from v8.4 onward
399 my $query = <<EOT;
400 SELECT
401 n.nspname AS "schema_name"
402 ,c.relname AS "table_name"
403 ,CASE c.relkind
404 WHEN 'r' THEN 'table'
405 WHEN 'v' THEN 'view'
406 WHEN 'm' THEN 'materialized view'
407 WHEN 's' THEN 'special'
408 WHEN 'f' THEN 'foreign table'
409 WHEN 'p' THEN 'table'
410 END as "table_type"
411 ,a.attname AS "field"
412 ,a.attnum AS "field_num"
413 ,CASE
414 WHEN a.atttypmod = -1 THEN null
415 WHEN t.oid IN (1042, 1043) THEN a.atttypmod - 4
416 WHEN t.oid IN (1560, 1562) THEN a.atttypmod
417 ELSE NULL
418 END AS "character_maximum_length"
419 ,CASE SUBSTRING(t.typname,1,1)
420 WHEN '_' THEN SUBSTRING(t.typname,2)
421 ELSE t.typname
422 END AS "data_type"
423 ,pg_catalog.format_type(a.atttypid,a.atttypmod) AS "format_type"
424 ,a.attndims > 0 AS "is_array"
425 ,CASE a.attnotnull
426 WHEN FALSE THEN TRUE
427 ELSE FALSE
428 END AS "is_nullable"
429 ,COALESCE(i.indisprimary,false) AS "is_primary"
430 ,COALESCE(i.indisunique,false) AS "is_unique"
431 ,r.oid IS NOT NULL AS "is_foreign"
432 ,r2.oid IS NOT NULL AS "is_check"
433 ,(SELECT pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) FROM pg_attrdef
434 WHERE pg_attrdef.adrelid = c.oid
435 AND pg_attrdef.adnum = a.attnum) AS "default"
436 ,(SELECT pg_description.description FROM pg_description
437 WHERE pg_description.objoid = c.oid AND pg_description.objsubid = a.attnum) AS "comment"
438 ,(SELECT c2.relname FROM pg_inherits LEFT JOIN pg_class c2 ON c2.oid = pg_inherits.inhparent
439 WHERE pg_inherits.inhrelid = c.oid) AS "table_parent"
440 ,c2.relname AS "index_name"
441 ,i.indnatts AS "index_n_columns"
442 ,i.indkey AS "index_columns"
443 ,ARRAY(
444 SELECT pg_get_indexdef(i.indexrelid, k, TRUE)
445 FROM generate_series(1,array_upper(string_to_array(i.indkey::text, ' ' )::int2[],1)) AS s(k)
446 ORDER BY k
447 ) AS "index_keys"
448 ,r.conname AS "foreign_name"
449 ,CASE
450 WHEN r.conindid > 0 THEN (SELECT c3.relname FROM pg_catalog.pg_class c3 WHERE c3.oid = r.conindid)
451 ELSE NULL
452 END AS "foreign_index_name"
453 ,CASE
454 WHEN r.confrelid > 0 THEN (SELECT c4.relname FROM pg_catalog.pg_class c4 WHERE c4.oid = r.confrelid)
455 ELSE NULL
456 END AS "foreign_table"
457 ,CASE r.confupdtype
458 WHEN 'a' THEN 'nothing'
459 WHEN 'r' THEN 'restrict'
460 WHEN 'c' THEN 'cascade'
461 WHEN 'n' THEN 'null'
462 WHEN 'd' THEN 'default'
463 ELSE NULL
464 END AS "foreign_update_action"
465 ,CASE r.confdeltype
466 WHEN 'a' THEN 'nothing'
467 WHEN 'r' THEN 'restrict'
468 WHEN 'c' THEN 'cascade'
469 WHEN 'n' THEN 'null'
470 WHEN 'd' THEN 'default'
471 ELSE NULL
472 END AS "foreign_delete_action"
473 ,CASE r.confmatchtype
474 WHEN 'f' THEN 'full'
475 WHEN 'p' THEN 'partial'
476 WHEN 's' THEN 'simple'
477 ELSE NULL
478 END AS "foreign_match"
479 ,r.conkey AS "foreign_columns"
480 ,ARRAY(
481 SELECT a2.attname
482 FROM generate_series(1,array_upper(r.conkey,1)) AS z(j), pg_catalog.pg_attribute a2
483 WHERE a2.attrelid = c.oid AND a2.attnum = r.conkey[j]
484 ) AS "foreign_keys"
485 ,CASE
486 WHEN r.oid IS NOT NULL THEN pg_get_constraintdef(r.oid,TRUE)
487 ELSE NULL
488 END AS "foreign_expression"
489 ,r2.conname AS "check_name"
490 ,CASE
491 WHEN r2.conindid > 0 THEN (SELECT c3.relname FROM pg_catalog.pg_class c3 WHERE c3.oid = r2.conindid)
492 ELSE NULL
493 END AS "check_index_name"
494 ,r2.conkey AS "check_columns"
495 ,ARRAY(
496 SELECT a2.attname
497 FROM generate_series(1,array_upper(r2.conkey,1)) AS z(j), pg_catalog.pg_attribute a2
498 WHERE a2.attrelid = c.oid AND a2.attnum = r2.conkey[j]
499 ) AS "check_keys"
500 ,CASE
501 WHEN r2.oid IS NOT NULL THEN pg_get_constraintdef(r2.oid,TRUE)
502 ELSE NULL
503 END AS "check_expression"
504 FROM pg_catalog.pg_class c
505 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
506 LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
507 LEFT JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
508 LEFT JOIN pg_catalog.pg_index i ON i.indrelid = c.oid AND a.attnum = ANY (i.indkey::int[])
509 LEFT JOIN pg_catalog.pg_class c2 ON c2.oid = i.indexrelid
510 LEFT JOIN pg_catalog.pg_constraint r ON r.conrelid = c.oid AND r.contype = 'f' AND a.attnum = ANY (r.conkey)
511 LEFT JOIN pg_catalog.pg_constraint r2 ON r2.conrelid = c.oid AND r2.contype = 'c' AND a.attnum = ANY (r2.conkey)
512 WHERE
513 c.relname = ? AND
514 a.attnum > 0 AND
515 NOT a.attisdropped
516 ORDER BY a.attnum
517 EOT
518 # http://www.postgresql.org/docs/9.3/interactive/infoschema-columns.html
519 # select * from information_schema.columns where table_name = 'address'
520 my $sth = $self->database_object->prepare_cached( $query ) ||
521 return( $self->error( "Error while preparing query to get table '$table' columns specification: ", $self->database_object->errstr ) );
522 $sth->execute( $table ) ||
523 return( $self->error( "Error while executing query to get table '$table' columns specification: ", $sth->errstr ) );
524 my $check = {};
525 my $foreign = {};
526 my $index = {};
527 my @primary = ();
528 my $ref = '';
529 my $c = 0;
530 # Mysql: field, type, null, key, default, extra
531 # Postgres: tablename, field, field_num, type, len, comment, is_nullable, key, foreign_key, default
532 while( $ref = $sth->fetchrow_hashref() )
533 {
534 my $def =
535 {
536 name => $ref->{field},
537 comment => $ref->{comment},
538 default => $ref->{default},
539 ( $ref->{check_name} ? ( check_name => $ref->{check_name} ) : () ),
540 ( $ref->{foreign_name} ? ( foreign_name => $ref->{foreign_name} ) : () ),
541 ( $ref->{index_name} ? ( index_name => $ref->{index_name} ) : () ),
542 is_array => ( $ref->{is_array} ? 1 : 0 ),
543 is_check => ( $ref->{is_check} ? 1 : 0 ),
544 is_foreign => ( $ref->{is_foreign} ? 1 : 0 ),
545 is_nullable => ( $ref->{is_nullable} ? 1 : 0 ),
546 is_primary => ( $ref->{is_primary} ? 1 : 0 ),
547 is_unique => ( $ref->{is_unique} ? 1 : 0 ),
548 pos => $ref->{field_num},
549 # query_object => $q,
550 size => $ref->{character_maximum_length},
551 # When the field is an array, the data type will start with an underscore
552 type => ( substr( $ref->{data_type}, 0, 1 ) eq '_' ? substr( $ref->{data_type}, 1 ) : $ref->{data_type} ),
553 # table_object => $self,
554 };
555 $self->{type} = $ref->{table_type} if( !$self->{type} );
556 $self->{schema} = $ref->{schema_name} if( !$self->{schema} );
557 $self->{parent} = $ref->{table_parent} if( !$self->{table_parent} );
558 if( $ref->{index_name} &&
559 !CORE::exists( $index->{ $ref->{index_name} } ) )
560 {
561 my $constraint = $self->new_index(
562 is_primary => $ref->{is_primary},
563 is_unique => $ref->{is_unique},
564 fields => $ref->{index_keys},
565 name => $ref->{index_name},
566 ) || return( $self->pass_error );
567 $index->{ $ref->{index_name} } = $constraint;
568 }
569 if( $ref->{check_name} &&
570 !CORE::exists( $check->{ $ref->{check_name} } ) )
571 {
572 my $constraint = $self->new_check(
573 expr => $ref->{check_expression},
574 fields => $ref->{check_keys},
575 name => $ref->{check_name},
576 ) || return( $self->pass_error );
577 $check->{ $ref->{check_name} } = $constraint;
578 }
579 if( $ref->{foreign_name} &&
580 !CORE::exists( $foreign->{ $ref->{foreign_name} } ) )
581 {
582 my $constraint = $self->new_foreign(
583 expr => $ref->{foreign_expression},
584 match => $ref->{foreign_match},
585 on_delete => $ref->{foreign_delete_action},
586 on_update => $ref->{foreign_update_action},
587 table => $ref->{foreign_table},
588 fields => $ref->{foreign_keys},
589 name => $ref->{foreign_name},
590 ) || return( $self->pass_error );
591 $foreign->{ $ref->{foreign_name} } = $constraint;
592 }
593  
594 my( $const_def, $dict );
595 if( $def->{is_array} &&
596 CORE::exists( $types_dict->{ "$def->{type}array" } ) )
597 {
598 $const_def = $types_dict->{ "$def->{type}array" };
599 }
600 elsif( CORE::exists( $types_dict->{ $def->{type} } ) )
601 {
602 $const_def = $types_dict->{ $def->{type} };
603 }
604 else
605 {
606 # Get the constant
607 DATA_TYPE_RE: foreach my $type ( keys( %$types_dict ) )
608 {
609 if( $def->{type} =~ /$types_dict->{ $type }->{re}/i )
610 {
611 $const_def = $types_dict->{ $type };
612 last DATA_TYPE_RE;
613 }
614 }
615 }
616 if( defined( $const_def ) )
617 {
618 my $const_keys = [keys( %$const_def )];
619 my $dict = {};
620 @$dict{ @$const_keys } = @$const_def{ @$const_keys };
621 $def->{datatype} = $dict;
622 # $def->{type} = $dict->{type};
623 }
624 $def->{query_object} = $q;
625 $def->{table_object} = $self;
626 my @define = ( $def->{type} );
627 push( @define, "DEFAULT '$def->{default}'" ) if( defined( $def->{default} ) && length( $def->{default} // '' ) );
628 push( @define, "NOT NULL" ) if( !$def->{is_nullable} );
629 push( @primary, $def->{name} ) if( $ref->{key} );
630 $struct->{ $def->{name} } = CORE::join( ' ', @define );
631 $def->{debug} = $self->debug;
632 my $field = DB::Object::Fields::Field->new( %$def ) ||
633 return( $self->pass_error( DB::Object::Fields::Field->error ) );
634 $fields->{ $def->{name} } = $field;
635 }
636 $sth->finish;
637 if( @primary )
638 {
639 $self->{primary} = \@primary;
640 }
641 $self->{check} = $check;
642 $self->{fields} = $fields;
643 $self->{foreign} = $foreign;
644 $self->{indexes} = $index;
645 $self->{_cache_structure} = $struct;
646 return( $self->_clone( $struct ) );
647 }
648  
649 sub table_info { return( shift->database_object->table_info( @_ ) ); }
650  
651 sub unlock
652 {
653 my $self = shift( @_ );
654 if( @_ )
655 {
656 return( $self->CORE::unlock( @_ ) );
657 }
658 my $query = 'UNLOCK TABLES';
659 my $sth = $self->database_object->prepare( $query ) ||
660 return( $self->error( "Error while preparing query to unlock tables:\n$query", $self->database_object->errstr() ) );
661 if( !defined( wantarray() ) )
662 {
663 $sth->execute() ||
664 return( $self->error( "Error while executing query to unlock tables:\n$query", $sth->errstr() ) );
665 }
666 return( $sth );
667 }
668  
669 # NOTE: DESTROY
670 DESTROY
671 {
672 # Do nothing
673 # DB::Object::Tables are never destroyed.
674 # They are just gateway to tables, and they are cached by DB::Object::Postgres::table()
675 # print( STDERR "DESTROY'ing table $self ($self->{ 'table' })\n" );
676 };
677  
678 1;
679 # NOTE: POD
680 __END__
681  
682 =encoding utf-8
683  
684 =head1 NAME
685  
686 DB::Object::Postgres::Tables - PostgreSQL Table Object
687  
688 =head1 SYNOPSIS
689  
690 use DB::Object::Postgres::Tables;
691 my $this = DB::Object::Postgres::Tables->new ||
692 die( DB::Object::Postgres::Tables->error, "\n" );
693  
694 =head1 VERSION
695  
696 v1.1.0
697  
698 =head1 DESCRIPTION
699  
700 This is a PostgreSQL table object class. It inherits from L<DB::Object::Tables>
701  
702 =head1 METHODS
703  
704 =head2 check
705  
706 Sets or gets an hash reference of check constraint name to an hash of properties for that constraint.
707  
708 See each driver for the value provided, but available properties typically are:
709  
710 =over 4
711  
712 =item * C<expr>
713  
714 The check constraint expression
715  
716 =item * C<fields>
717  
718 The L<array object|Module::Generic::Array> of table columns associated with this check constraint.
719  
720 =item * C<name>
721  
722 The check constraint name.
723  
724 =back
725  
726 =head2 create
727  
728 This creates a table.
729  
730 It takes some array reference data containing the columns definitions, some optional parameters and a statement handler.
731  
732 If a statement handler is provided, then no need to provide an array reference of columns definition. The columns definition will be taken from the statement handler. However, at least either one of them needs to be provided to set the columns definition.
733  
734 Possible parameters are:
735  
736 =over 4
737  
738 =item * C<comment>
739  
740 =item * C<inherits>
741  
742 Takes the name of another table to inherit from
743  
744 =item * C<on commit>
745  
746 =item * C<tablespace>
747  
748 =item * C<temporary>
749  
750 If provided, this will create a temporary table.
751  
752 =item * C<with oids>
753  
754 If true, this will enable table oid
755  
756 =item * C<without oids>
757  
758 If true, this will disable table oid
759  
760 =back
761  
762 This will return an error if the table already exists, so best to check beforehand with L</exists>.
763  
764 Upon success, it will return the new statement to create the table. However, if L</create> is called in void context, then the statement is executed right away and returned.
765  
766 =head2 create_info
767  
768 This returns the create info for the current table object as a string representing the sql script necessary to recreate the table.
769  
770 =head2 disable_trigger
771  
772 my $sth = $tbl->disable_trigger;
773 my $sth = $tbl->disable_trigger( all => 1 );
774 my $sth = $tbl->disable_trigger( name => 'my_trigger' );
775  
776 Provided with some optional parameters and this will return a statement handler to disable all triggers or a given trigger on the table.
777  
778 If it is called in void context, then the statement is executed immediately and returned, otherwise it is just returned.
779  
780 $tbl->disable_trigger;
781 # would issue immediately the following query:
782 ALTER TABLE my_table DISABLE TRIGGER USER
783  
784 It takes the following options:
785  
786 =over 4
787  
788 =item * C<all>
789  
790 If true, this will disable all trigger on the table. Please note that, as per the L<PostgreSQL documentation|https://www.postgresql.org/docs/10/sql-altertable.html> this requires super user privilege.
791  
792 If false, this will disable only the user triggers, i.e. not including the system ones.
793  
794 =item * C<name>
795  
796 If a trigger name is provided, it will be used to specifically disable this trigger.
797  
798 =back
799  
800 =head2 drop
801  
802 This will prepare a drop statement to drop the current table.
803  
804 If it is called in void context, then the statement is executed immediately and returned, otherwise it is just returned.
805  
806 It takes the following options:
807  
808 =over 4
809  
810 =item * C<cascade>
811  
812 If true, C<CASCADE> will be added to the C<DROP> query.
813  
814 =item * C<if_exists>
815  
816 If true, this will add a C<IF EXISTS> to the C<DROP> query.
817  
818 You can also use I<if-exists>
819  
820 =item * C<restrict>
821  
822 If true, C<RESTRICT> will be added to the C<DROP> query.
823  
824 =back
825  
826 See L<PostgreSQL documentation for more information|https://www.postgresql.org/docs/9.5/sql-droptable.html>
827  
828 =head2 enable_trigger
829  
830 my $sth = $tbl->enable_trigger;
831 my $sth = $tbl->enable_trigger( all => 1 );
832 my $sth = $tbl->enable_trigger( name => 'my_trigger' );
833  
834 Provided with some optional parameters and this will return a statement handler to enable all triggers or a given trigger on the table.
835  
836 If it is called in void context, then the statement is executed immediately and returned, otherwise it is just returned.
837  
838 $tbl->enable_trigger;
839 # would issue immediately the following query:
840 ALTER TABLE my_table ENABLE TRIGGER USER
841  
842 It takes the following options:
843  
844 =over 4
845  
846 =item * C<all>
847  
848 If true, this will enable all trigger on the table. Please note that, as per the L<PostgreSQL documentation|https://www.postgresql.org/docs/10/sql-altertable.html> this requires super user privilege.
849  
850 If false, this will enable only the user triggers, i.e. not including the system ones.
851  
852 =item * C<name>
853  
854 If a trigger name is provided, it will be used to specifically enable this trigger.
855  
856 =back
857  
858 =head2 exists
859  
860 Returns true if the current table exists, or false otherwise.
861  
862 =head2 foreign
863  
864 Sets or gets an hash reference of foreign key constraint name to an hash of properties for that constraint.
865  
866 Available properties are:
867  
868 =over 4
869  
870 =item * C<expr>
871  
872 The foreign key expression used when creating the table schema.
873  
874 =item * C<match>
875  
876 Typical value is C<full>, C<partial> and C<simple>
877  
878 =item * C<on_delete>
879  
880 The action the database is to take upon deletion. For example: C<nothing>, C<restrict>, C<cascade>, C<null> or C<default>
881  
882 =item * C<on_update>
883  
884 The action the database is to take upon update. For example: C<nothing>, C<restrict>, C<cascade>, C<null> or C<default>
885  
886 =item * C<table>
887  
888 The table name of the foreign key.
889  
890 =item * C<fields>
891  
892 The associated table column names for this foreign key constraint.
893  
894 =item * C<name>
895  
896 The foreign key constraint name.
897  
898 =back
899  
900 =head2 lock
901  
902 This will prepare a query to lock the table and return the statement handler. If it is called in void context, the statement handler returned is executed immediately.
903  
904 It takes an optional lock type and an optional C<NOWAIT> parameter.
905  
906 Supported lock types are:
907  
908 =over 4
909  
910 =item C<ACCESS SHARE>
911  
912 =item C<ROW SHARE>
913  
914 =item C<ROW EXCLUSIVE>
915  
916 =item C<SHARE UPDATE EXCLUSIVE>
917  
918 =item C<SHARE>
919  
920 =item C<SHARE ROW EXCLUSIVE>
921  
922 =item C<EXCLUSIVE>
923  
924 =item C<ACCESS EXCLUSIVE>
925  
926 =back
927  
928 See L<PostgreSQL documentation for more information|https://www.postgresql.org/docs/9.5/explicit-locking.html>
929  
930 =head2 on_conflict
931  
932 A convenient wrapper to L<DB::Object::Postgres::Query/on_conflict>
933  
934 =head2 optimize
935  
936 Not implemented in PostgreSQL.
937  
938 =head2 parent
939  
940 This will return the parent table if the current table inherits from another table.
941  
942 =head2 qualified_name
943  
944 This return a fully qualified name to be used as a prefix to columns in queries.
945  
946 If L<DB::Object::Tables/prefixed> is greater than 2, the database name will be added.
947  
948 If there is a schema defined and the L<DB::Object::Tables/prefixed> is greater than 1, the schema will be added.
949  
950 At minimum, the table name is added.
951  
952 $tbl->prefixed(2);
953 $tbl->qualified_name;
954 # Would return something like: mydb.my_schema.my_table
955  
956 $tbl->prefixed(1);
957 $tbl->qualified_name;
958 # Would return only: my_table
959  
960 =head2 rename
961  
962 Provided with a new table name, and this will prepare the necessary query to rename the table and return the statement handler.
963  
964 If it is called in void context, the statement handler is executed immediately.
965  
966 # Get the prefs table object
967 my $tbl = $dbh->pref;
968 $tbl->rename( 'prefs' );
969 # Would issue a statement handler for the query: ALTER TABLE pref RENAME TO prefs
970  
971 See L<PostgreSQL documentation for more information|https://www.postgresql.org/docs/9.5/sql-altertable.html>
972  
973 =head2 repair
974  
975 Not implemented in PostgreSQL.
976  
977 =head2 stat
978  
979 Not implemented in PostgreSQL.
980  
981 =head2 structure
982  
983 This returns, in list context, an hash and, in scalar context, an hash reference of the table structure.
984  
985 The hash, or hash reference returned contains the column name and its definition.
986  
987 The data returned is cached, so it fetches the information from PostgreSQL only once.
988  
989 This method will also set the following object properties:
990  
991 =over 4
992  
993 =item * L<DB::Object::Tables/type>
994  
995 The table type.
996  
997 =item * L<DB::Object::Tables/schema>
998  
999 The table schema.
1000  
1001 =item * C<default>
1002  
1003 A column name to default value hash reference
1004  
1005 =item * C<fields>
1006  
1007 A column name to field position (integer) hash reference
1008  
1009 =item * C<null>
1010  
1011 A column name to a boolean representing whether the column is nullable or not.
1012  
1013 =item * L<DB::Object::Tables/primary>
1014  
1015 An array reference of column names that are used as primary key for the table.
1016  
1017 =item * C<structure>
1018  
1019 A column name to its sql definition
1020  
1021 =item * C<types>
1022  
1023 A column name to column data type hash reference
1024  
1025 =back
1026  
1027 =head2 table_info
1028  
1029 This is an alias for L<DB::Object::Postgres/table_info>
1030  
1031 =head2 unlock
1032  
1033 This will unlock a previously locked table.
1034  
1035 If an argument is provided, this calls instead C<CORE::unlock> passing it whatever parameters provided.
1036  
1037 Otherwise, it will prepare a query C<UNLOCK TABLES> and returns the statement handler.
1038  
1039 If it is called in void context, this will execute the statement handler immediately.
1040  
1041 =head1 SEE ALSO
1042  
1043 L<perl>
1044  
1045 =head1 AUTHOR
1046  
1047 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
1048  
1049 =head1 COPYRIGHT & LICENSE
1050  
1051 Copyright (c) 2019-2021 DEGUEST Pte. Ltd.
1052  
1053 You can use, copy, modify and redistribute this package and associated
1054 files under the same terms as Perl itself.
1055  
1056 =cut