| 1 | # -*- perl -*- | ||
| 2 | ##---------------------------------------------------------------------------- | ||
| 3 | ## Database Object Interface - ~/lib/DB/Object/Postgres/Tables.pm | ||
| 4 | ## Version v1.1.1 | ||
| 5 | ## Copyright(c) 2026 DEGUEST Pte. Ltd. | ||
| 6 | ## Author: Jacques Deguest <jack@deguest.jp> | ||
| 7 | ## Created 2017/07/19 | ||
| 8 | ## Modified 2026/08/05 | ||
| 9 | ## All rights reserved | ||
| 10 | ## | ||
| 11 | ## This program is free software; you can redistribute it and/or modify it | ||
| 12 | ## under the same terms as Perl itself.## | ||
| 13 | ##----------------------------------------------------------------------------## | ||
| 14 | ## This package's purpose is to separate the object of the tables from the main | ||
| 15 | ## DB::Object package so that when they get DESTROY'ed, it does not interrupt | ||
| 16 | ## the SQL connection | ||
| 17 | ##---------------------------------------------------------------------------- | ||
| 18 | package DB::Object::Postgres::Tables; | ||
| 19 | BEGIN | ||
| 20 | { | ||
| 21 | use strict; | ||
| 22 | use warnings; | ||
| 23 | warnings::register_categories( 'DB::Object' ); | ||
| 24 | use parent qw( DB::Object::Tables ); | ||
| 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.1'; | ||
| 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 this is a SELECT ... FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHAR, we redirect to the query builder | ||
| 279 | if( $opt =~ /^(?:For[[:blank:]\h]+)?(update|no[[:blank:]\h]+key[[:blank:]\h]+update|share|key[[:blank:]\h]+share)/i ) | ||
| 280 | { | ||
| 281 | return( $self->lock_select( $opt ) ); | ||
| 282 | } | ||
| 283 | elsif( $opt !~ /^(ACCESS SHARE|ROW SHARE|ROW EXCLUSIVE|SHARE UPDATE EXCLUSIVE|SHARE|SHARE ROW EXCLUSIVE|EXCLUSIVE|ACCESS EXCLUSIVE)$/i ) | ||
| 284 | { | ||
| 285 | return( $self->error( "Bad table '$table' locking option '$opt'." ) ); | ||
| 286 | } | ||
| 287 | my $query = sprintf( 'LOCK TABLE %s IN %s MODE', $table, $opt ); | ||
| 288 | $query .= " NOWAIT" if( $nowait ); | ||
| 289 | my $sth = $self->database_object->prepare( $query ) || | ||
| 290 | return( $self->error( "Error while preparing query to do tables locking:\n$query", $self->database_object->errstr() ) ); | ||
| 291 | if( !defined( wantarray() ) ) | ||
| 292 | { | ||
| 293 | $sth->execute() || | ||
| 294 | return( $self->error( "Error while executing query to do tables locking:\n$query", $sth->errstr() ) ); | ||
| 295 | } | ||
| 296 | return( $sth ); | ||
| 297 | } | ||
| 298 | |||
| 299 | sub lock_select | ||
| 300 | { | ||
| 301 | my $self = shift( @_ ); | ||
| 302 | my $q = $self->_reset_query; | ||
| 303 | # Void | ||
| 304 | return( $q->lock( @_ ) ) if( !defined( wantarray() ) ); | ||
| 305 | if( wantarray() ) | ||
| 306 | { | ||
| 307 | my( @val ) = $q->lock( @_ ) || return( $self->pass_error( $q->error ) ); | ||
| 308 | return( @val ); | ||
| 309 | } | ||
| 310 | else | ||
| 311 | { | ||
| 312 | my $val = $q->lock( @_ ); | ||
| 313 | return( $self->pass_error( $q->error ) ) if( !defined( $val ) ); | ||
| 314 | return( $val ); | ||
| 315 | } | ||
| 316 | } | ||
| 317 | |||
| 318 | # NOTE: sub name is inherited from DB::Object::Tables | ||
| 319 | # sub name | ||
| 320 | |||
| 321 | # NOTE: sub null is inherited from DB::Object::Tables | ||
| 322 | # sub null | ||
| 323 | |||
| 324 | # NOTE: sub primary is inherited from DB::Object::Tables | ||
| 325 | # sub primary | ||
| 326 | |||
| 327 | sub on_conflict | ||
| 328 | { | ||
| 329 | my $self = shift( @_ ); | ||
| 330 | my $q = $self->_reset_query; | ||
| 331 | # Void | ||
| 332 | return( $q->on_conflict( @_ ) ) if( !defined( wantarray() ) ); | ||
| 333 | if( wantarray() ) | ||
| 334 | { | ||
| 335 | my( @val ) = $q->on_conflict( @_ ) || return( $self->pass_error( $q->error ) ); | ||
| 336 | return( @val ); | ||
| 337 | } | ||
| 338 | else | ||
| 339 | { | ||
| 340 | my $val = $q->on_conflict( @_ ); | ||
| 341 | return( $self->pass_error( $q->error ) ) if( !defined( $val ) ); | ||
| 342 | return( $val ); | ||
| 343 | } | ||
| 344 | } | ||
| 345 | |||
| 346 | sub optimize { return( shift->error( "optimize() is not implemented PostgreSQL." ) ); } | ||
| 347 | |||
| 348 | sub parent { return( shift->_set_get_scalar( 'parent', @_ ) ); } | ||
| 349 | |||
| 350 | sub qualified_name | ||
| 351 | { | ||
| 352 | my $self = shift( @_ ); | ||
| 353 | my @val = (); | ||
| 354 | CORE::push( @val, $self->database_object->database ) if( $self->{prefixed} > 2 ); | ||
| 355 | CORE::push( @val, $self->schema ) if( $self->{prefixed} > 1 && $self->schema ); | ||
| 356 | CORE::push( @val, $self->name ); | ||
| 357 | return( CORE::join( '.', @val ) ); | ||
| 358 | } | ||
| 359 | |||
| 360 | sub rename | ||
| 361 | { | ||
| 362 | my $self = shift( @_ ); | ||
| 363 | my $table = $self->{table} || | ||
| 364 | return( $self->error( 'No table was provided to rename' ) ); | ||
| 365 | my $new = shift( @_ ) || | ||
| 366 | return( $self->error( "No new table name was provided to rename table '$table'." ) ); | ||
| 367 | if( $new !~ /^[\w\_]+$/ ) | ||
| 368 | { | ||
| 369 | return( $self->error( "Bad new table name '$new'." ) ); | ||
| 370 | } | ||
| 371 | my $query = "ALTER TABLE $table RENAME TO $new"; | ||
| 372 | my $sth = $self->database_object->prepare( $query ) || | ||
| 373 | return( $self->error( "Error while preparing query to rename table '$table' into '$new':\n$query", $self->database_object->errstr() ) ); | ||
| 374 | if( !defined( wantarray() ) ) | ||
| 375 | { | ||
| 376 | $sth->execute() || | ||
| 377 | return( $self->error( "Error while executing query to rename table '$table' into '$new':\n$query", $sth->errstr() ) ); | ||
| 378 | } | ||
| 379 | $self->reset_structure; | ||
| 380 | return( $sth ); | ||
| 381 | } | ||
| 382 | |||
| 383 | sub repair { return( shift->error( "repair() is not implemented PostgreSQL." ) ); } | ||
| 384 | |||
| 385 | sub reset { return( shift->DB::Object::Tables::reset( @_ ) ); } | ||
| 386 | |||
| 387 | sub stat { return( shift->error( "stat() is not implemented PostgreSQL." ) ); } | ||
| 388 | |||
| 389 | sub structure | ||
| 390 | { | ||
| 391 | my $self = shift( @_ ); | ||
| 392 | return( $self->_clone( $self->{_cache_structure} ) ) if( $self->{_cache_structure} && !CORE::length( $self->{_reset_structure} // '' ) ); | ||
| 393 | my $table = $self->{table} || | ||
| 394 | return( $self->error( "No table provided to get its structure." ) ); | ||
| 395 | my $struct = $self->{structure} // {}; | ||
| 396 | my $fields = $self->{fields} // {}; | ||
| 397 | my $types_dict = $self->database_object->datatype_dict; | ||
| 398 | $self->_load_class( 'DB::Object::Fields::Field' ) || return( $self->pass_error ); | ||
| 399 | my $q = $self->_reset_query; | ||
| 400 | # <https://stackoverflow.com/questions/6777456/list-all-index-names-column-names-and-its-table-name-of-a-postgresql-database> | ||
| 401 | |||
| 402 | # If we have a cache, use it instead of reprocessing it. | ||
| 403 | # <https://stackoverflow.com/questions/52376045/why-does-atttypmod-differ-from-character-maximum-length> | ||
| 404 | # my $query = <<EOT; | ||
| 405 | # SELECT | ||
| 406 | # a.table_schema AS "schema_name" | ||
| 407 | # ,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" | ||
| 408 | # ,a.column_name AS "field" | ||
| 409 | # ,a.ordinal_position AS "field_num" | ||
| 410 | # ,a.column_default AS "default" | ||
| 411 | # ,a.* | ||
| 412 | # FROM information_schema.columns a | ||
| 413 | # LEFT JOIN pg_catalog.pg_class c ON c.relname = a.table_name | ||
| 414 | # WHERE a.table_name = ? | ||
| 415 | # ORDER BY a.ordinal_position | ||
| 416 | # EOT | ||
| 417 | # <https://www.postgresql.org/docs/14/catalog-pg-attrdef.html> | ||
| 418 | # We could use: | ||
| 419 | # generate_subscripts(i.indkey, 1) | ||
| 420 | # instead of: | ||
| 421 | # generate_series(1,array_upper(string_to_array(i.indkey::text, ' ' )::int2[],1)) | ||
| 422 | # but this is not supported by PostgreSQL v8.0; only from v8.4 onward | ||
| 423 | my $query = <<EOT; | ||
| 424 | SELECT | ||
| 425 | n.nspname AS "schema_name" | ||
| 426 | ,c.relname AS "table_name" | ||
| 427 | ,CASE c.relkind | ||
| 428 | WHEN 'r' THEN 'table' | ||
| 429 | WHEN 'v' THEN 'view' | ||
| 430 | WHEN 'm' THEN 'materialized view' | ||
| 431 | WHEN 's' THEN 'special' | ||
| 432 | WHEN 'f' THEN 'foreign table' | ||
| 433 | WHEN 'p' THEN 'table' | ||
| 434 | END as "table_type" | ||
| 435 | ,a.attname AS "field" | ||
| 436 | ,a.attnum AS "field_num" | ||
| 437 | ,CASE | ||
| 438 | WHEN a.atttypmod = -1 THEN null | ||
| 439 | WHEN t.oid IN (1042, 1043) THEN a.atttypmod - 4 | ||
| 440 | WHEN t.oid IN (1560, 1562) THEN a.atttypmod | ||
| 441 | ELSE NULL | ||
| 442 | END AS "character_maximum_length" | ||
| 443 | ,CASE SUBSTRING(t.typname,1,1) | ||
| 444 | WHEN '_' THEN SUBSTRING(t.typname,2) | ||
| 445 | ELSE t.typname | ||
| 446 | END AS "data_type" | ||
| 447 | ,pg_catalog.format_type(a.atttypid,a.atttypmod) AS "format_type" | ||
| 448 | ,(a.attndims > 0 OR pg_catalog.format_type(a.atttypid,a.atttypmod) LIKE '%[]') AS "is_array" | ||
| 449 | ,CASE a.attnotnull | ||
| 450 | WHEN FALSE THEN TRUE | ||
| 451 | ELSE FALSE | ||
| 452 | END AS "is_nullable" | ||
| 453 | ,COALESCE(i.indisprimary,false) AS "is_primary" | ||
| 454 | ,COALESCE(i.indisunique,false) AS "is_unique" | ||
| 455 | ,r.oid IS NOT NULL AS "is_foreign" | ||
| 456 | ,r2.oid IS NOT NULL AS "is_check" | ||
| 457 | ,(SELECT pg_get_expr(pg_attrdef.adbin, pg_attrdef.adrelid) FROM pg_attrdef | ||
| 458 | WHERE pg_attrdef.adrelid = c.oid | ||
| 459 | AND pg_attrdef.adnum = a.attnum) AS "default" | ||
| 460 | ,(SELECT pg_description.description FROM pg_description | ||
| 461 | WHERE pg_description.objoid = c.oid AND pg_description.objsubid = a.attnum) AS "comment" | ||
| 462 | ,(SELECT c2.relname FROM pg_inherits LEFT JOIN pg_class c2 ON c2.oid = pg_inherits.inhparent | ||
| 463 | WHERE pg_inherits.inhrelid = c.oid) AS "table_parent" | ||
| 464 | ,c2.relname AS "index_name" | ||
| 465 | ,i.indnatts AS "index_n_columns" | ||
| 466 | ,i.indkey AS "index_columns" | ||
| 467 | ,ARRAY( | ||
| 468 | SELECT pg_get_indexdef(i.indexrelid, k, TRUE) | ||
| 469 | FROM generate_series(1,array_upper(string_to_array(i.indkey::text, ' ' )::int2[],1)) AS s(k) | ||
| 470 | ORDER BY k | ||
| 471 | ) AS "index_keys" | ||
| 472 | ,r.conname AS "foreign_name" | ||
| 473 | ,CASE | ||
| 474 | WHEN r.conindid > 0 THEN (SELECT c3.relname FROM pg_catalog.pg_class c3 WHERE c3.oid = r.conindid) | ||
| 475 | ELSE NULL | ||
| 476 | END AS "foreign_index_name" | ||
| 477 | ,CASE | ||
| 478 | WHEN r.confrelid > 0 THEN (SELECT c4.relname FROM pg_catalog.pg_class c4 WHERE c4.oid = r.confrelid) | ||
| 479 | ELSE NULL | ||
| 480 | END AS "foreign_table" | ||
| 481 | ,CASE r.confupdtype | ||
| 482 | WHEN 'a' THEN 'nothing' | ||
| 483 | WHEN 'r' THEN 'restrict' | ||
| 484 | WHEN 'c' THEN 'cascade' | ||
| 485 | WHEN 'n' THEN 'null' | ||
| 486 | WHEN 'd' THEN 'default' | ||
| 487 | ELSE NULL | ||
| 488 | END AS "foreign_update_action" | ||
| 489 | ,CASE r.confdeltype | ||
| 490 | WHEN 'a' THEN 'nothing' | ||
| 491 | WHEN 'r' THEN 'restrict' | ||
| 492 | WHEN 'c' THEN 'cascade' | ||
| 493 | WHEN 'n' THEN 'null' | ||
| 494 | WHEN 'd' THEN 'default' | ||
| 495 | ELSE NULL | ||
| 496 | END AS "foreign_delete_action" | ||
| 497 | ,CASE r.confmatchtype | ||
| 498 | WHEN 'f' THEN 'full' | ||
| 499 | WHEN 'p' THEN 'partial' | ||
| 500 | WHEN 's' THEN 'simple' | ||
| 501 | ELSE NULL | ||
| 502 | END AS "foreign_match" | ||
| 503 | ,r.conkey AS "foreign_columns" | ||
| 504 | ,ARRAY( | ||
| 505 | SELECT a2.attname | ||
| 506 | FROM generate_series(1,array_upper(r.conkey,1)) AS z(j), pg_catalog.pg_attribute a2 | ||
| 507 | WHERE a2.attrelid = c.oid AND a2.attnum = r.conkey[j] | ||
| 508 | ) AS "foreign_keys" | ||
| 509 | ,CASE | ||
| 510 | WHEN r.oid IS NOT NULL THEN pg_get_constraintdef(r.oid,TRUE) | ||
| 511 | ELSE NULL | ||
| 512 | END AS "foreign_expression" | ||
| 513 | ,r2.conname AS "check_name" | ||
| 514 | ,CASE | ||
| 515 | WHEN r2.conindid > 0 THEN (SELECT c3.relname FROM pg_catalog.pg_class c3 WHERE c3.oid = r2.conindid) | ||
| 516 | ELSE NULL | ||
| 517 | END AS "check_index_name" | ||
| 518 | ,r2.conkey AS "check_columns" | ||
| 519 | ,ARRAY( | ||
| 520 | SELECT a2.attname | ||
| 521 | FROM generate_series(1,array_upper(r2.conkey,1)) AS z(j), pg_catalog.pg_attribute a2 | ||
| 522 | WHERE a2.attrelid = c.oid AND a2.attnum = r2.conkey[j] | ||
| 523 | ) AS "check_keys" | ||
| 524 | ,CASE | ||
| 525 | WHEN r2.oid IS NOT NULL THEN pg_get_constraintdef(r2.oid,TRUE) | ||
| 526 | ELSE NULL | ||
| 527 | END AS "check_expression" | ||
| 528 | FROM pg_catalog.pg_class c | ||
| 529 | LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace | ||
| 530 | LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid | ||
| 531 | LEFT JOIN pg_catalog.pg_type t ON t.oid = a.atttypid | ||
| 532 | LEFT JOIN pg_catalog.pg_index i ON i.indrelid = c.oid AND a.attnum = ANY (i.indkey::int[]) | ||
| 533 | LEFT JOIN pg_catalog.pg_class c2 ON c2.oid = i.indexrelid | ||
| 534 | LEFT JOIN pg_catalog.pg_constraint r ON r.conrelid = c.oid AND r.contype = 'f' AND a.attnum = ANY (r.conkey) | ||
| 535 | LEFT JOIN pg_catalog.pg_constraint r2 ON r2.conrelid = c.oid AND r2.contype = 'c' AND a.attnum = ANY (r2.conkey) | ||
| 536 | WHERE | ||
| 537 | c.relname = ? AND | ||
| 538 | a.attnum > 0 AND | ||
| 539 | NOT a.attisdropped | ||
| 540 | ORDER BY a.attnum | ||
| 541 | EOT | ||
| 542 | # http://www.postgresql.org/docs/9.3/interactive/infoschema-columns.html | ||
| 543 | # select * from information_schema.columns where table_name = 'address' | ||
| 544 | my $sth = $self->database_object->prepare_cached( $query ) || | ||
| 545 | return( $self->error( "Error while preparing query to get table '$table' columns specification: ", $self->database_object->errstr ) ); | ||
| 546 | $sth->execute( $table ) || | ||
| 547 | return( $self->error( "Error while executing query to get table '$table' columns specification: ", $sth->errstr ) ); | ||
| 548 | my $check = {}; | ||
| 549 | my $foreign = {}; | ||
| 550 | my $index = {}; | ||
| 551 | my @primary = (); | ||
| 552 | my $ref = ''; | ||
| 553 | my $c = 0; | ||
| 554 | # Mysql: field, type, null, key, default, extra | ||
| 555 | # Postgres: tablename, field, field_num, type, len, comment, is_nullable, key, foreign_key, default | ||
| 556 | while( $ref = $sth->fetchrow_hashref() ) | ||
| 557 | { | ||
| 558 | my $def = | ||
| 559 | { | ||
| 560 | name => $ref->{field}, | ||
| 561 | comment => $ref->{comment}, | ||
| 562 | default => $ref->{default}, | ||
| 563 | ( $ref->{check_name} ? ( check_name => $ref->{check_name} ) : () ), | ||
| 564 | ( $ref->{foreign_name} ? ( foreign_name => $ref->{foreign_name} ) : () ), | ||
| 565 | ( $ref->{index_name} ? ( index_name => $ref->{index_name} ) : () ), | ||
| 566 | is_array => ( $ref->{is_array} ? 1 : 0 ), | ||
| 567 | is_check => ( $ref->{is_check} ? 1 : 0 ), | ||
| 568 | is_foreign => ( $ref->{is_foreign} ? 1 : 0 ), | ||
| 569 | is_nullable => ( $ref->{is_nullable} ? 1 : 0 ), | ||
| 570 | is_primary => ( $ref->{is_primary} ? 1 : 0 ), | ||
| 571 | is_unique => ( $ref->{is_unique} ? 1 : 0 ), | ||
| 572 | pos => $ref->{field_num}, | ||
| 573 | # query_object => $q, | ||
| 574 | size => $ref->{character_maximum_length}, | ||
| 575 | # When the field is an array, the data type will start with an underscore | ||
| 576 | type => ( substr( $ref->{data_type}, 0, 1 ) eq '_' ? substr( $ref->{data_type}, 1 ) : $ref->{data_type} ), | ||
| 577 | # table_object => $self, | ||
| 578 | }; | ||
| 579 | $self->{type} = $ref->{table_type} if( !$self->{type} ); | ||
| 580 | $self->{schema} = $ref->{schema_name} if( !$self->{schema} ); | ||
| 581 | $self->{parent} = $ref->{table_parent} if( !$self->{table_parent} ); | ||
| 582 | if( $ref->{index_name} && | ||
| 583 | !CORE::exists( $index->{ $ref->{index_name} } ) ) | ||
| 584 | { | ||
| 585 | my $constraint = $self->new_index( | ||
| 586 | is_primary => $ref->{is_primary}, | ||
| 587 | is_unique => $ref->{is_unique}, | ||
| 588 | fields => $ref->{index_keys}, | ||
| 589 | name => $ref->{index_name}, | ||
| 590 | ) || return( $self->pass_error ); | ||
| 591 | $index->{ $ref->{index_name} } = $constraint; | ||
| 592 | } | ||
| 593 | if( $ref->{check_name} && | ||
| 594 | !CORE::exists( $check->{ $ref->{check_name} } ) ) | ||
| 595 | { | ||
| 596 | my $constraint = $self->new_check( | ||
| 597 | expr => $ref->{check_expression}, | ||
| 598 | fields => $ref->{check_keys}, | ||
| 599 | name => $ref->{check_name}, | ||
| 600 | ) || return( $self->pass_error ); | ||
| 601 | $check->{ $ref->{check_name} } = $constraint; | ||
| 602 | } | ||
| 603 | if( $ref->{foreign_name} && | ||
| 604 | !CORE::exists( $foreign->{ $ref->{foreign_name} } ) ) | ||
| 605 | { | ||
| 606 | my $constraint = $self->new_foreign( | ||
| 607 | expr => $ref->{foreign_expression}, | ||
| 608 | match => $ref->{foreign_match}, | ||
| 609 | on_delete => $ref->{foreign_delete_action}, | ||
| 610 | on_update => $ref->{foreign_update_action}, | ||
| 611 | table => $ref->{foreign_table}, | ||
| 612 | fields => $ref->{foreign_keys}, | ||
| 613 | name => $ref->{foreign_name}, | ||
| 614 | ) || return( $self->pass_error ); | ||
| 615 | $foreign->{ $ref->{foreign_name} } = $constraint; | ||
| 616 | } | ||
| 617 | |||
| 618 | my( $const_def, $dict ); | ||
| 619 | if( $def->{is_array} && | ||
| 620 | CORE::exists( $types_dict->{ "$def->{type}array" } ) ) | ||
| 621 | { | ||
| 622 | $const_def = $types_dict->{ "$def->{type}array" }; | ||
| 623 | } | ||
| 624 | elsif( CORE::exists( $types_dict->{ $def->{type} } ) ) | ||
| 625 | { | ||
| 626 | $const_def = $types_dict->{ $def->{type} }; | ||
| 627 | } | ||
| 628 | else | ||
| 629 | { | ||
| 630 | # Get the constant | ||
| 631 | DATA_TYPE_RE: foreach my $type ( keys( %$types_dict ) ) | ||
| 632 | { | ||
| 633 | if( $def->{type} =~ /$types_dict->{ $type }->{re}/i ) | ||
| 634 | { | ||
| 635 | $const_def = $types_dict->{ $type }; | ||
| 636 | last DATA_TYPE_RE; | ||
| 637 | } | ||
| 638 | } | ||
| 639 | } | ||
| 640 | if( defined( $const_def ) ) | ||
| 641 | { | ||
| 642 | my $const_keys = [keys( %$const_def )]; | ||
| 643 | my $dict = {}; | ||
| 644 | @$dict{ @$const_keys } = @$const_def{ @$const_keys }; | ||
| 645 | $def->{datatype} = $dict; | ||
| 646 | # $def->{type} = $dict->{type}; | ||
| 647 | } | ||
| 648 | $def->{query_object} = $q; | ||
| 649 | $def->{table_object} = $self; | ||
| 650 | my @define = ( $def->{type} ); | ||
| 651 | push( @define, "DEFAULT '$def->{default}'" ) if( defined( $def->{default} ) && length( $def->{default} // '' ) ); | ||
| 652 | push( @define, "NOT NULL" ) if( !$def->{is_nullable} ); | ||
| 653 | push( @primary, $def->{name} ) if( $ref->{key} ); | ||
| 654 | $struct->{ $def->{name} } = CORE::join( ' ', @define ); | ||
| 655 | $def->{debug} = $self->debug; | ||
| 656 | my $field = DB::Object::Fields::Field->new( %$def ) || | ||
| 657 | return( $self->pass_error( DB::Object::Fields::Field->error ) ); | ||
| 658 | $fields->{ $def->{name} } = $field; | ||
| 659 | } | ||
| 660 | $sth->finish; | ||
| 661 | if( @primary ) | ||
| 662 | { | ||
| 663 | $self->{primary} = \@primary; | ||
| 664 | } | ||
| 665 | $self->{check} = $check; | ||
| 666 | $self->{fields} = $fields; | ||
| 667 | $self->{foreign} = $foreign; | ||
| 668 | $self->{indexes} = $index; | ||
| 669 | $self->{_cache_structure} = $struct; | ||
| 670 | return( $self->_clone( $struct ) ); | ||
| 671 | } | ||
| 672 | |||
| 673 | sub table_info { return( shift->database_object->table_info( @_ ) ); } | ||
| 674 | |||
| 675 | sub unlock | ||
| 676 | { | ||
| 677 | my $self = shift( @_ ); | ||
| 678 | if( @_ ) | ||
| 679 | { | ||
| 680 | return( $self->CORE::unlock( @_ ) ); | ||
| 681 | } | ||
| 682 | my $query = 'UNLOCK TABLES'; | ||
| 683 | my $sth = $self->database_object->prepare( $query ) || | ||
| 684 | return( $self->error( "Error while preparing query to unlock tables:\n$query", $self->database_object->errstr() ) ); | ||
| 685 | if( !defined( wantarray() ) ) | ||
| 686 | { | ||
| 687 | $sth->execute() || | ||
| 688 | return( $self->error( "Error while executing query to unlock tables:\n$query", $sth->errstr() ) ); | ||
| 689 | } | ||
| 690 | return( $sth ); | ||
| 691 | } | ||
| 692 | |||
| 693 | # NOTE: DESTROY | ||
| 694 | DESTROY | ||
| 695 | { | ||
| 696 | # Do nothing | ||
| 697 | # DB::Object::Tables are never destroyed. | ||
| 698 | # They are just gateway to tables, and they are cached by DB::Object::Postgres::table() | ||
| 699 | # print( STDERR "DESTROY'ing table $self ($self->{ 'table' })\n" ); | ||
| 700 | }; | ||
| 701 | |||
| 702 | 1; | ||
| 703 | # NOTE: POD | ||
| 704 | __END__ |