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

filter: Statementstmt 0.0% 0 / 298 Branchbran 0.0% 0 / 156 Conditioncond 0.0% 0 / 140 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 636 CC 79 SCAR 51.3
CC
79
Cov
0%
structure
462.0
create
210.0
lock
210.0
CRAP 169.1
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/Mysql/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 2025/03/09
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::Mysql::Tables;
20 BEGIN
21 {
22 use strict;
23 use warnings;
24 use parent qw( DB::Object::Mysql DB::Object::Tables );
25 use vars qw( $VERSION $DEBUG $TYPE_TO_CONSTANT );
26 # <https://dev.mysql.com/doc/refman/8.0/en/data-types.html>
27 # the 'constant' property in the dictionary hash is added in structure()
28 # See also: SELECT DISTINCT(data_type) FROM information_schema.columns ORDER by data_type
29 # but this does not provide a complete list of datatype
30 our $TYPE_TO_CONSTANT =
31 {
32 qr/^(bit)/ => { constant => '', name => 'SQL_BIT', type => 'bit' },
33 qr/^(tinyint)/ => { constant => '', name => 'SQL_TINYINT', type => 'tinyint' },
34 qr/^(smallint)/ => { constant => '', name => 'SQL_SMALLINT', type => 'smallint' },
35 qr/^(mediumint)/ => { constant => '', name => 'SQL_BIT', type => 'mediumint' },
36 qr/^(integer|int)/ => { constant => '', name => 'SQL_INTEGER', type => 'int' },
37 qr/^(bigint)/ => { constant => '', name => 'SQL_BIGINT', type => 'bigint' },
38 qr/^(dec|decimal)/ => { constant => '', name => 'SQL_DECIMAL', type => 'decimal' },
39 qr/^(float)/ => { constant => '', name => 'SQL_FLOAT', type => 'float' },
40 qr/^(double\s+precision|double)/ => { constant => '', name => 'SQL_DOUBLE', type => 'double' },
41 qr/^(date)\b/ => { constant => '', name => 'SQL_DATE', type => 'date' },
42 qr/^(datetime)/ => { constant => '', name => 'SQL_DATETIME', type => 'datetime' },
43 qr/^(timestamp)/ => { constant => '', name => 'SQL_TIMESTAMP', type => 'timestamp' },
44 qr/^(year)/ => { constant => '', name => 'SQL_INTERVAL_YEAR', type => 'year' },
45 qr/^(character|char)\b(?![[:blank:]]+varying)/ => { constant => '', name => 'SQL_VARCHAR', type => 'varchar' },
46 qr/^(character varying|varchar)/ => { constant => '', name => 'SQL_WVARCHAR', type => 'varchar' },
47 qr/^blob/ => { constant => '', name => 'SQL_BLOB', type => 'blob' },
48 qr/^text/ => { constant => '', name => 'SQL_LONGVARCHAR', type => 'text' },
49 qr/^binary/ => { constant => '', name => 'SQL_BINARY', type => 'binary' },
50 qr/^varbinary/ => { constant => '', name => 'SQL_VARBINARY', type => 'varbinary' },
51 qr/^(tinyblob)\b/ => { constant => '', name => 'SQL_BLOB', type => 'tinyblob' },
52 qr/^(mediumblob)\b/ => { constant => '', name => 'SQL_BLOB', type => 'mediumblob' },
53 qr/^(longlob)\b/ => { constant => '', name => 'SQL_BLOB', type => 'longlob' },
54 qr/^(tinytext)\b/ => { constant => '', name => 'SQL_LONGVARCHAR', type => 'tinytext' },
55 qr/^(mediumtext)\b/ => { constant => '', name => 'SQL_LONGVARCHAR', type => 'mediumtext' },
56 qr/^(longtext)\b/ => { constant => '', name => 'SQL_LONGVARCHAR', type => 'longtext' },
57 qr/^(enum)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'enum' },
58 qr/^(set)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'set' },
59 qr/^(geometry)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'geometry' },
60 qr/^(linestring)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'linestring' },
61 qr/^(point)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'point' },
62 qr/^(polygon)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'polygon' },
63 qr/^(curve)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'curve' },
64 qr/^(multipolygon)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'multipolygon' },
65 qr/^(multilinestring)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'multilinestring' },
66 qr/^(multipoint)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'multipoint' },
67 qr/^(geometrycollection)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'geometrycollection' },
68 qr/^(multicurve)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'multicurve' },
69 qr/^(json)\b/ => { constant => '', name => 'SQL_UNKNOWN_TYPE', type => 'json' },
70 };
71 our $DEBUG = 0;
72 our $VERSION = 'v1.1.0';
73 };
74  
75 use strict;
76 use warnings;
77  
78 sub init
79 {
80 return( shift->DB::Object::Tables::init( @_ ) );
81 }
82  
83 # NOTE] sub alter is inherited from DB::Object::Tables
84 # sub alter
85  
86 sub check
87 {
88 my $self = shift( @_ );
89 my $table = $self->{table} ||
90 return( $self->error( 'No table was provided to check' ) );
91 my $opt = shift( @_ ) if( @_ == 1 );
92 my %arg = ( @_ );
93 $opt = \%arg if( !$opt && %arg );
94 my $query = "CHECK TABLE $table";
95 $query .= " TYPE = QUICK" if( $opt->{ 'quick' } );
96 my $sth = $self->prepare( $query ) ||
97 return( $self->error( "Error while preparing query to check table '$table':\n$query\n", $self->errstr() ) );
98 if( !defined( wantarray() ) )
99 {
100 $sth->execute() ||
101 return( $self->error( "Error while executing query to check table '$table':\n$query\n", $sth->errstr() ) );
102 }
103 return( $sth );
104 }
105  
106 sub create
107 {
108 my $self = shift( @_ );
109 # $tbl->create( [ 'ROW 1', 'ROW 2'... ], { 'temporary' => 1, 'TYPE' => ISAM }, $obj );
110 my $data = shift( @_ ) || [];
111 my $opt = shift( @_ ) || {};
112 my $sth = shift( @_ );
113 my $table = $self->{table};
114 # Set temporary in the object, so we can use it to recreate the table creation info as string:
115 # $table->create( [ ... ], { ... }, $obj )->as_string();
116 my $temp = $self->{temporary} = delete( $opt->{temporary} );
117 # Check possible options
118 my $allowed =
119 {
120 type => qr/^(ISAM|MYISAM|HEAP)$/i,
121 auto_increment => qr/^(1|0)$/,
122 avg_row_length => qr/^\d+$/,
123 checksum => qr/^(1|0)$/,
124 comment => qr//,
125 max_rows => qr/^\d+$/,
126 min_rows => qr/^\d+$/,
127 pack_keys => qr/^(1|0)$/,
128 password => qr//,
129 delay_key_write => qr/^\d+$/,
130 row_format => qr/^(default|dynamic|static|compressed)$/i,
131 raid_type => qr/^(?:1|STRIPED|RAID0|RAID_CHUNKS\s*=\s*\d+|RAID_CHUNKSIZE\s*=\s*\d+)$/,
132 };
133 my @options = ();
134 my @errors = ();
135 # Avoid working for nothing, make this condition
136 if( %$opt )
137 {
138 my %lc_opt = map{ lc( $_ ) => $opt->{ $_ } } keys( %$opt );
139 $opt = \%lc_opt;
140 foreach my $key ( keys( %$opt ) )
141 {
142 next if( $opt->{ $key } =~ /^\s*$/ || !exists( $allowed->{ $key } ) );
143 if( $opt->{ $key } !~ /$allowed->{ $key }/ )
144 {
145 push( @errors, $key );
146 }
147 else
148 {
149 push( @options, $key );
150 }
151 }
152 $opt->{comment} = "'" . quotemeta( $opt->{comment} ) . "'" if( exists( $opt->{comment} ) );
153 $opt->{password} = "'" . $opt->{password} . "'" if( exists( $opt->{password} ) );
154 }
155 if( @errors )
156 {
157 warn( "The options '", join( ', ', @errors ), "' were either not recognized or malformed and thus were ignored.\n" );
158 }
159 # Check statement
160 my $select = '';
161 if( $sth && ref( $sth ) && ( $sth->isa( "DB::Object::Statement" ) || $sth->can( 'as_string' ) ) )
162 {
163 $select = $sth->as_string();
164 if( $select !~ /^\s*(?:IGNORE|REPLACE)*\s*\bSELECT\s+/ )
165 {
166 return( $self->error( "SELECT statement to use to create table is invalid:\n$select" ) );
167 }
168 }
169 if( $self->exists() == 0 )
170 {
171 my $query = 'CREATE ' . ( $temp ? 'TEMPORARY ' : '' ) . "TABLE $table ";
172 # Structure of table if any -
173 # structure may very well be provided using a select statement, such as:
174 # CREATE TEMPORARY TABLE ploppy TYPE=HEAP COMMENT='this is kewl' MAX_ROWS=10 SELECT * FROM some_table LIMIT 0,0
175 my $def = "(\n" . CORE::join( ",\n", @$data ) . "\n)" if( $data && ref( $data ) && @$data );
176 my $tdef = CORE::join( ' ', map{ "\U$_\E = $opt->{ $_ }" } @options );
177 if( !$def && !$select )
178 {
179 return( $self->error( "Lacking table '$table' structure information to create it." ) );
180 }
181 $query .= join( ' ', $def, $tdef, $select );
182 my $new = $self->prepare( $query ) ||
183 return( $self->error( "Error while preparing query to create table '$table':\n$query", $self->errstr() ) );
184 # Trick so other method may follow, such as as_string(), fetchrow(), rows()
185 if( !defined( wantarray() ) )
186 {
187 # print( STDERR "create(): wantarrays in void context.\n" );
188 $new->execute ||
189 return( $self->error( "Error while executing query to create table '$table':\n$query", $new->errstr() ) );
190 }
191 $self->reset_structure;
192 return( $new );
193 }
194 else
195 {
196 return( $self->error( "Table '$table' already exists." ) );
197 }
198 }
199  
200 sub create_info
201 {
202 my $self = shift( @_ );
203 my $table = $self->{table};
204 $self->structure || return( $self->pass_error );
205 my $struct = $self->{structure};
206 my $fields = $self->{fields};
207 my $default = $self->{default};
208 my $primary = $self->{primary};
209 my @output = ();
210 foreach my $field ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) )
211 {
212 push( @output, "$field $struct->{ $field }" );
213 }
214 push( @output, "PRIMARY KEY(" . CORE::join( ',', @$primary ) . ")" ) if( $primary && @$primary );
215 my $info = $self->stat( $table );
216 my @opt = ();
217 push( @opt, "TYPE = $info->{type}" ) if( $info->{type} );
218 my $addons = $info->{create_options};
219 if( $addons )
220 {
221 $addons =~ s/(\A|\s+)([\w\_]+)\s*=\s*/$1\U$2\E=/g;
222 push( @opt, $addons );
223 }
224 push( @opt, "COMMENT='" . quotemeta( $info->{ 'comment' } ) . "'" ) if( $info->{comment} );
225 my $str = "CREATE TABLE $table (\n\t" . CORE::join( ",\n\t", @output ) . "\n)";
226 $str .= ' ' . CORE::join( ' ', @opt ) if( @opt );
227 $str .= ';';
228 return( @output ? $str : undef() );
229 }
230  
231 # NOTE: sub default is inherited from DB::Object::Tables
232 # sub default
233  
234 sub drop
235 {
236 my $self = shift( @_ );
237 my $table = $self->{table} ||
238 return( $self->error( "No table was provided to drop." ) );
239 my $query = "DROP TABLE $table";
240 my $sth = $self->prepare( $query ) ||
241 return( $self->error( "Error while preparing query to drop table '$table':\n$query", $self->errstr() ) );
242 if( !defined( wantarray() ) )
243 {
244 $sth->execute ||
245 return( $self->error( "Error while executing query to drop table '$table':\n$query", $sth->errstr() ) );
246 }
247 $self->reset_structure;
248 return( $sth );
249 }
250  
251 sub exists
252 {
253 return( shift->table_exists( shift( @_ ) ) );
254 }
255  
256 sub lock
257 {
258 my $self = shift( @_ );
259 # There is two arguments, the first one does not look like an exiting table name and the second is a number...
260 # It pretty much looks like a statement lock
261 if( @_ == 2 && ( !$self->exists( $_[ 0 ] ) || $_[ 1 ] =~ /^\d+$/ ) )
262 {
263 return( $self->SUPER::lock( @_ ) );
264 }
265 my @tables = ();
266 my $chk_opt = sub
267 {
268 my $self = shift( @_ );
269 my $table = shift( @_ );
270 my $opt = shift( @_ );
271 my $alias = shift( @_ );
272 if( $opt !~ /^(READ|READ\s+LOCAL|(LOW_PRIORITY\s+)?WRITE)$/i )
273 {
274 return( $self->error( "Bad table '$table' locking option '$opt'." ) );
275 }
276 if( $alias )
277 {
278 if( $self->_simple_exist( $alias ) )
279 {
280 return( $self->error( "Alias '$alias' for table '$table' seems to match an already existing table." ) );
281 }
282 elsif( $alias !~ /^[\w\_]+$/ )
283 {
284 return( $self->error( "Illegal characters for table '$table' alias name '$alias'." ) );
285 }
286 }
287 return( 1 );
288 };
289 # No parameter, so we default to WRITE for read/write access, but with a low priority
290 if( !@_ )
291 {
292 push( @tables, "$self->{table} LOW_PRIORITY WRITE" );
293 }
294 elsif( @_ == 1 )
295 {
296 my $arg = shift( @_ );
297 my $alias = '';
298 my $opt = '';
299 # Array reference means 'table alias', 'access mode'
300 if( $self->_is_array( $arg ) )
301 {
302 ( $alias, $opt ) = @$arg;
303 }
304 # Otherwise just 'access mode'
305 else
306 {
307 $opt = $arg;
308 }
309 $opt ||= 'LOW_PRIORITY WRITE';
310 $chk_opt->( $self, $self->{table}, $opt, $alias ) || return;
311 my @lck = ( $self->{table} );
312 push( @lck, "AS $alias" ) if( $alias );
313 push( @lck, uc( $opt ) );
314 push( @tables, CORE::join( ' ', @lck ) );
315 }
316 else
317 {
318 my %arg = ( @_ );
319 my( $tbl, $value );
320 while( ( $tbl, $value ) = each( %arg ) )
321 {
322 my( $alias, $opt );
323 if( !$value )
324 {
325 $opt = 'LOW_PRIORITY WRITE';
326 }
327 elsif( ref( $value ) )
328 {
329 ( $alias, $opt ) = @$value;
330 }
331 else
332 {
333 $opt = $value;
334 }
335 $opt ||= 'LOW_PRIORITY WRITE';
336 $chk_opt->( $self, $tbl, $opt, $alias ) || return;
337 my @lck = ( $tbl );
338 push( @lck, "AS $alias" ) if( $alias );
339 push( @lck, uc( $opt ) );
340 push( @tables, CORE::join( ' ', @lck ) );
341 }
342 }
343 my $query = 'LOCK TABLES ' . CORE::join( ', ', @tables );
344 my $sth = $self->prepare( $query ) ||
345 return( $self->error( "Error while preparing query to do tables locking:\n$query", $self->errstr() ) );
346 if( !defined( wantarray() ) )
347 {
348 $sth->execute ||
349 return( $self->error( "Error while executing query to do tables locking:\n$query", $sth->errstr() ) );
350 }
351 return( $sth );
352 }
353  
354 # NOTE: sub name is inherited from DB::Object::Tables
355 # sub name
356  
357 # NOTE: sub null is inherited from DB::Object::Tables
358 # sub null
359  
360 sub on_conflict
361 {
362 my $self = shift( @_ );
363 my $q = $self->_reset_query;
364 # Void
365 return( $q->on_conflict( @_ ) ) if( !defined( wantarray() ) );
366 if( wantarray() )
367 {
368 my( @val ) = $q->on_conflict( @_ ) || return( $self->pass_error( $q->error ) );
369 return( @val );
370 }
371 else
372 {
373 my $val = $q->on_conflict( @_ );
374 return( $self->pass_error( $q->error ) ) if( !defined( $val ) );
375 return( $val );
376 }
377 }
378  
379 sub optimize
380 {
381 my $self = shift( @_ );
382 my $table = $self->{table} ||
383 return( $self->error( 'No table was provided to optmize' ) );
384 return( $self->error( "Table '$table' does not exist." ) ) if( !$self->exists( $table ) );
385 my $query = "OPTIMIZE TABLE $table";
386 my $sth = $self->prepare( $query ) ||
387 return( $self->error( "Error while preparing query to optimize table '$table':\n$query\n", $self->errstr() ) );
388 if( !defined( wantarray() ) )
389 {
390 $sth->execute() ||
391 return( $self->error( "Error while executing query to optimize table '$table':\n$query\n", $sth->errstr() ) );
392 }
393 return( $sth );
394 }
395  
396 # NOTE: sub primary is inherited from DB::Object::Tables
397 # sub primary
398  
399 sub qualified_name
400 {
401 my $self = shift( @_ );
402 my @val = ();
403 CORE::push( @val, $self->database_object->database ) if( $self->{prefixed} > 2 );
404 CORE::push( @val, $self->name );
405 return( CORE::join( '.', @val ) );
406 }
407  
408 sub rename
409 {
410 my $self = shift( @_ );
411 my $table = $self->{table} ||
412 return( $self->error( 'No table was provided to rename' ) );
413 my $new = shift( @_ ) ||
414 return( $self->error( "No new table name was provided to rename table '$table'." ) );
415 if( $new !~ /^[\w\_]+$/ )
416 {
417 return( $self->error( "Bad new table name '$new'." ) );
418 }
419 my $query = "ALTER TABLE $table RENAME TO $new";
420 my $sth = $self->prepare( $query ) ||
421 return( $self->error( "Error while preparing query to rename table '$table' into '$new':\n$query", $self->errstr() ) );
422 if( !defined( wantarray() ) )
423 {
424 $sth->execute() ||
425 return( $self->error( "Error while executing query to rename table '$table' into '$new':\n$query", $sth->errstr() ) );
426 }
427 $self->reset_structure;
428 return( $sth );
429 }
430  
431 sub repair
432 {
433 my $self = shift( @_ );
434 my $table = $self->{table} ||
435 return( $self->error( 'No table was provided to repair' ) );
436 return( $self->error( "Table '$table' does not exist." ) ) if( !$self->exists( $table ) );
437 my $opts = $self->_get_args_as_hash( @_ );
438 my $query = "REPAIR TABLE $table";
439 $query .= ' TYPE = QUICK' if( $opts->{quick} );
440 my $sth = $self->prepare( $query ) ||
441 return( $self->error( "Error while preparing query to repair table '$table':\n$query\n", $self->errstr() ) );
442 if( !defined( wantarray() ) )
443 {
444 $sth->execute() ||
445 return( $self->error( "Error while executing query to repair table '$table':\n$query\n", $sth->errstr() ) );
446 }
447 return( $sth );
448 }
449  
450 sub stat
451 {
452 my $self = shift( @_ );
453 # If no $table argument is provided, we will stat all tables
454 my $table = shift( @_ );
455 my $db = $self->{database};
456 my $query = $table ? "SHOW TABLE STATUS FROM $db LIKE '$table'" : "SHOW TABLE STATUS FROM $db";
457 my $sth = $self->prepare( $query ) ||
458 return( $self->error( "Error while preparing query to get the status of table", ( $table ? " '$table'" : 's' ), ":\n$query", $self->errstr() ) );
459 $sth->execute ||
460 return( $self->error( "Error while executing query to get the status of table", ( $table ? " '$table'" : 's' ), ":\n$query", $sth->errstr ) );
461 my $tables = {};
462 my $ref = '';
463 while( $ref = $sth->fetchrow_hashref() )
464 {
465 my %data = map{ lc( $_ ) => $ref->{ $_ } } keys( %$ref );
466 my $name = $data{name};
467 # map{ $tables->{ $name }->{ $_ } = $data{ $_ } } keys( %data );
468 $tables->{ $name } = \%data;
469 }
470 $sth->finish;
471 return( wantarray() ? () : undef() ) if( !%$tables );
472 return( wantarray() ? %{ $tables->{ $table } } : $tables->{ $table } ) if( $table && exists( $tables->{ $table } ) );
473 return( wantarray() ? %$tables : $tables );
474 }
475  
476 # TODO: Must implement a cache mechanism for DB::Object::Mysql::structure()
477 sub structure
478 {
479 my $self = shift( @_ );
480 return( $self->_clone( $self->{_cache_structure} ) ) if( $self->{_cache_structure} && !CORE::length( $self->{_reset_structure} // '' ) );
481 my $struct = $self->{structure};
482 my $fields = $self->{fields};
483 my $types_dict = $self->database_object->datatype_dict;
484 $self->_load_class( 'DB::Object::Fields::Field' ) || return( $self->pass_error );
485 my $q = $self->_reset_query;
486 my $table = $self->{table} ||
487 return( $self->error( "No table provided to get its structure." ) );
488 my $dbh = $self->database_object->{dbh};
489 my $sth1 = $dbh->prepare_cached( "SELECT * FROM information_schema.tables WHERE table_name = ?" ) ||
490 return( $self->error( "An error occured while preparing the sql query to get the details of table \"$table\": ", $dbh->errstr() ) );
491 $sth1->execute( $table ) ||
492 return( $self->error( "An error occured while executing the sql query to get the details of table \"$table\": ", $sth1->errstr() ) );
493 my $def = $sth1->fetchrow_hashref;
494 $sth1->finish;
495 if( scalar( keys( %$def ) ) )
496 {
497 # Ensure all fields are in lower case.
498 foreach my $k ( keys( %$def ) )
499 {
500 # For example: AUTO_INCREMENT -> auto_increment
501 $def->{ lc( $k ) } = CORE::delete( $def->{ $k } );
502 }
503 $self->{type} = lc( $def->{table_type} );
504 $self->{type} = 'table' if( $self->{type} eq 'base table' );
505 }
506 else
507 {
508 warn( "No information found for table ${table}\n" ) if( $self->_is_warnings_enabled( 'DB::Object' ) );
509 }
510 # <https://dev.mysql.com/doc/refman/8.0/en/information-schema-columns-table.html>
511 my $query = <<EOT;
512 SELECT
513 a.column_name AS "field"
514 ,a.ordinal_position AS "field_num"
515 ,a.column_default AS "default"
516 ,a.*
517 FROM information_schema.columns a
518 WHERE table_name = ?
519 ORDER BY a.ordinal_position
520 EOT
521 my $sth = $dbh->prepare_cached( $query ) ||
522 return( $self->error( "Error while preparing query to get table '$table' columns specification: ", $dbh->errstr() ) );
523 $sth->execute( $table ) ||
524 return( $self->error( "Error while executing query to get table '$table' columns specification: ", $sth->errstr() ) );
525  
526 my @primary = ();
527 my $ref = '';
528 my $c = 0;
529 while( $ref = $sth->fetchrow_hashref() )
530 {
531 # Ensure all fields are in lower case.
532 foreach my $k ( keys( %$ref ) )
533 {
534 # For example: ORDINAL_POSITION -> ordinal_position
535 $ref->{ lc( $k ) } = CORE::delete( $ref->{ $k } );
536 }
537 my $def =
538 {
539 name => $ref->{field},
540 ( CORE::length( $ref->{column_comment} // '' ) ? ( comment => $ref->{column_comment} ) : () ),
541 default => $ref->{column_default},
542 # Damn MySQL not using boolean
543 is_nullable => ( $ref->{is_nullable} eq 'YES' ? 1 : 0 ),
544 is_primary => ( ( $ref->{column_key} // '' ) eq 'PRI' ? 1 : 0 ),
545 is_unique => ( ( $ref->{column_key} // '' ) eq 'UNI' ? 1 : 0 ),
546 pos => $ref->{field_num},
547 # query_object => $q,
548 size => $ref->{character_maximum_length},
549 type => $ref->{data_type},
550 # table_object => $self,
551 };
552  
553 my( $const_def, $dict );
554 if( CORE::exists( $types_dict->{ $def->{type} } ) )
555 {
556 $const_def = $types_dict->{ $def->{type} };
557 }
558 else
559 {
560 # Get the constant
561 DATA_TYPE_RE: foreach my $type ( keys( %$types_dict ) )
562 {
563 if( $def->{type} =~ /$types_dict->{ $type }->{re}/i )
564 {
565 $const_def = $types_dict->{ $type };
566 last DATA_TYPE_RE;
567 }
568 }
569 }
570 if( defined( $const_def ) )
571 {
572 my $const_keys = [keys( %$const_def )];
573 my $dict = {};
574 @$dict{ @$const_keys } = @$const_def{ @$const_keys };
575 $def->{datatype} = $dict;
576 }
577 $def->{query_object} = $q;
578 $def->{table_object} = $self;
579 # The information schema field 'column_type' provides already what is needed, such as 'varchar(255)'
580 my @define = ( $ref->{column_type} );
581 push( @define, "NOT NULL" ) if( !$def->{is_nullable} );
582 # <https://stackoverflow.com/questions/68639745/how-to-get-a-default-column-value-from-mysql-5-7-information-schema-columns-with>
583 if( defined( $def->{default} ) )
584 {
585 my $value;
586 if( ( $ref->{data_type} eq 'datetime' || $ref->{data_type} eq 'timestamp' ) &&
587 $def->{default} eq 'CURRENT_TIMESTAMP' )
588 {
589 $value = 'CURRENT_TIMESTAMP';
590 }
591 elsif( !length( $def->{default} // '' ) )
592 {
593 $value = "''";
594 }
595 else
596 {
597 $value = $self->database_object->quote( $def->{default}, ( CORE::length( $def->{datatype}->{constant} // '' ) ? $def->{datatype}->{constant} : () ) );
598 }
599 push( @define, "DEFAULT ${value}" );
600 }
601 push( @define, 'AUTO_INCREMENT' ) if( lc( $ref->{extra} // '' ) eq 'auto_increment' );
602 if( defined( $ref->{extra} ) &&
603 $ref->{extra} =~ /^DEFAULT_GENERATED[[:blank:]]+(ON[[:blank:]]+UPDATE[[:blank:]]+.*)$/i )
604 {
605 push( @define, $1 );
606 }
607 push( @primary, $def->{name} ) if( $ref->{column_key} eq 'PRI' );
608 $struct->{ $def->{name} } = CORE::join( ' ', @define );
609 my $field = DB::Object::Fields::Field->new( %$def, debug => $self->debug ) ||
610 return( $self->pass_error( DB::Object::Fields::Field->error ) );
611 $fields->{ $def->{name} } = $field;
612 }
613 $sth->finish;
614 if( @primary )
615 {
616 $self->{primary} = \@primary;
617 }
618 $self->{fields} = $fields;
619 $self->{_cache_structure} = $struct;
620 return( $self->_clone( $struct ) );
621 }
622  
623 sub table_info { return( shift->database_object->table_info( @_ ) ); }
624  
625 sub unlock
626 {
627 my $self = shift( @_ );
628 if( @_ )
629 {
630 return( $self->CORE::unlock( @_ ) );
631 }
632 my $query = 'UNLOCK TABLES';
633 my $sth = $self->prepare( $query ) ||
634 return( $self->error( "Error while preparing query to unlock tables:\n$query", $self->errstr() ) );
635 if( !defined( wantarray() ) )
636 {
637 $sth->execute() ||
638 return( $self->error( "Error while executing query to unlock tables:\n$query", $sth->errstr() ) );
639 }
640 return( $sth );
641 }
642  
643 DESTROY
644 {
645 # Do nothing
646 # DB::Object::Tables are never destroyed.
647 # They are just gateway to tables, and they are cached by DB::Object::table()
648 # print( STDERR "DESTROY'ing table $self ($self->{ 'table' })\n" );
649 };
650  
651 1;
652  
653 # NOTE: POD
654  
655 __END__
656  
657 =encoding utf-8
658  
659 =head1 NAME
660  
661 DB::Object::Mysql::Tables - MySQL Table Object
662  
663 =head1 SYNOPSIS
664  
665 use DB::Object::Mysql::Tables;
666 my $this = DB::Object::Mysql::Tables->new || die( DB::Object::Mysql::Tables->error, "\n" );
667  
668 =head1 VERSION
669  
670 v1.1.0
671  
672 =head1 DESCRIPTION
673  
674 This is a MySQL table object class.
675  
676 =head1 METHODS
677  
678 =head2 check
679  
680 This will prepare the statement to C<check> the table.
681  
682 Checking table is a query specific to C<MySQL>
683  
684 If called in void context, the resulting statement handler will be executed immediately.
685  
686 It returns the newly created statement handler.
687  
688 =head2 create
689  
690 This creates a table.
691  
692 It takes some array reference data containing the columns definitions, some optional parameters and a statement handler.
693  
694 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.
695  
696 Possible parameters are:
697  
698 =over 4
699  
700 =item I<comment>
701  
702 =item I<inherits>
703  
704 Takes the name of another table to inherit from
705  
706 =item I<on commit>
707  
708 =item I<tablespace>
709  
710 =item I<temporary>
711  
712 If provided, this will create a temporary table.
713  
714 =item I<with oids>
715  
716 If true, this will enable table oid
717  
718 =item I<without oids>
719  
720 If true, this will disable table oid
721  
722 =back
723  
724 This will return an error if the table already exists, so best to check beforehand with L</exists>.
725  
726 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.
727  
728 =head2 create_info
729  
730 This returns the create info for the current table object as a string representing the sql script necessary to recreate the table.
731  
732 =head2 drop
733  
734 This will prepare a drop statement to drop the current table.
735  
736 If it is called in void context, then the statement is executed immediately and returned, otherwise it is just returned.
737  
738 It takes no option.
739  
740 See L<MySQL documentation for more information|https://dev.mysql.com/doc/refman/8.0/en/drop-table.html>
741  
742 =head2 exists
743  
744 Returns true if the current table exists, or false otherwise.
745  
746 =head2 lock
747  
748 If no parameter is provided, this will issue the following query C<LOCK t LOW_PRIORITY WRITE> where t is the table name.
749  
750 If one parameter is provided and is an array reference containing the table alias and some lock option, otherwise if the one parameter provided is the lock option. If no lock option is provided this will default to C<LOW_PRIORITY WRITE>.
751  
752 For example:
753  
754 $t->lock([ 'n', 'low_priority write' ]);
755  
756 This will issue the following query:
757  
758 LOCK TABLE t AS n LOW_PRIORITY WRITE
759  
760 $t->lock( 'low_priority write' );
761  
762 This will issue the following query:
763  
764 LOCK TABLE t LOW_PRIORITY WRITE
765  
766 If the parameters provided is an hash of table name-option pairs, such as:
767  
768 $t->lock(
769 t1 => ['n' => 'low_priority write'], # alias to n with option
770 t2 => 'low_priority write', # only option
771 );
772  
773 This will issue the following query:
774  
775 LOCK TABLES t1 AS n LOW_PRIORITY WRITE, t2 LOW_PRIORITY WRITE
776  
777 The option can only be:
778  
779 =over 4
780  
781 =item I<read>
782  
783 =item I<read local>
784  
785 =item I<write>
786  
787 =item I<low priority write>
788  
789 =back
790  
791 This will prepare the query to lock the table or tables and return the statement handler. If it is called in void context, the statement handler returned is executed immediately.
792  
793 See L<MyQL documentation for more information|https://dev.mysql.com/doc/refman/5.7/en/lock-tables.html>
794  
795 =head2 on_conflict
796  
797 A convenient wrapper to L<DB::Object::Mysql::Query/on_conflict>
798  
799 =head2 optimize
800  
801 my $sth = $t->optimize; # OPTIMIZE TABLE t
802  
803 This will prepare a query to C<optimize> the table. If it is called in void context, the statement handler returned is executed immediately.
804  
805 See L<MyQL documentation for more information|https://dev.mysql.com/doc/refman/5.7/en/optimize-table.html>
806  
807 =head2 qualified_name
808  
809 This return a fully qualified name to be used as a prefix to columns in queries.
810  
811 Note that in MySQL there is no meaning of schema like in other modern drivers like PostgreSQL. In MySQL a C<schema> is equivalent to a C<database>. See this L<StackOverflow discussion|https://stackoverflow.com/questions/11618277/difference-between-schema-database-in-mysql>
812  
813 If L<DB::Object::Tables/prefixed> is greater than 2, the database name will be added.
814  
815 At minimum, the table name is added.
816  
817 $tbl->prefixed(2);
818 $tbl->qualified_name;
819 # Would return something like: mydb.my_table
820  
821 $tbl->prefixed(1);
822 $tbl->qualified_name;
823 # Would return only: my_table
824  
825 See L<MyQL documentation for more information|https://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html>
826  
827 =head2 rename
828  
829 Provided with a new table name, and this will prepare the necessary query to rename the table and return the statement handler.
830  
831 If it is called in void context, the statement handler is executed immediately.
832  
833 # Get the prefs table object
834 my $tbl = $dbh->pref;
835 $tbl->rename( 'prefs' );
836 # Would issue a statement handler for the query: ALTER TABLE pref RENAME TO prefs
837  
838 It returns the statement handler created.
839  
840 See L<PostgreSQL documentation for more information|https://dev.mysql.com/doc/refman/5.7/en/alter-table.html>
841  
842 =head2 repair
843  
844 Provided with an optional hash or hash reference of parameter, and this will prepare a query to C<repair> the MySQL table.
845  
846 my $tbl = $dbh->my_table || die( $dbh->error );
847 my $sth = $tbl->repair || die( $tbl->error );
848 $sth->exec || die( $sth->error );
849  
850 If it is called in void context, the statement handler is executed immediately.
851  
852 It returns the statement handler created.
853  
854 See L<PostgreSQL documentation for more information|https://dev.mysql.com/doc/refman/5.7/en/repair-table.html>
855  
856 =head2 stat
857  
858 Provided with a table name and this will prepare a C<SHOW TABLE STATUS> MySQL query. If no table explicitly specified, then this will prepare a stat query for all tables in the database.
859  
860 $tbl->stat( 'my_table' );
861 # SHOW TABLE STATUS FROM my_database LIKE 'my_table'
862 $tbl->stat;
863 # SHOW TABLE STATUS FROM my_database
864  
865 The stat statement will be executed and an hash reference of property-value pairs in lower case will be retrieved for each table. Each table hash is stored in another hash reference of table name-properties hash reference pairs.
866  
867 If only one table was the subject of the stat, in list context, this returns an hash of those table stat properties, and in scalar context its hash reference.
868  
869 If the stat was done for the entire database, in list context, this returns an hash of all those tables to properties pairs, or an hash reference in scalar context.
870  
871 =head2 structure
872  
873 This returns in list context an hash and in scalar context an hash reference of the table structure.
874  
875 The hash, or hash reference returned contains the column name and its definition.
876  
877 This method will also set the following object properties:
878  
879 =over 4
880  
881 =item L<DB::Object::Tables/type>
882  
883 The table type.
884  
885 =item L<DB::Object::Tables/schema>
886  
887 No such thing in MySQL, so this is unavailable.
888  
889 =item I<default>
890  
891 A column name to default value hash reference
892  
893 =item I<fields>
894  
895 A column name to field position (integer) hash reference
896  
897 =item I<null>
898  
899 A column name to a boolean representing whether the column is nullable or not.
900  
901 =item L<DB::Object::Tables/primary>
902  
903 An array reference of column names that are used as primary key for the table.
904  
905 =item I<structure>
906  
907 A column name to its sql definition
908  
909 =item I<types>
910  
911 A column name to column data type hash reference
912  
913 =back
914  
915 =head2 table_info
916  
917 This is an alias for L<DB::Object::Mysql/table_info>
918  
919 =head2 unlock
920  
921 This will unlock a previously locked table.
922  
923 If an argument is provided, this calls instead C<CORE::unlock> passing it whatever parameters provided.
924  
925 Otherwise, it will prepare a query C<UNLOCK TABLES> and returns the statement handler.
926  
927 If it is called in void context, this will execute the statement handler immediately.
928  
929 See L<MyQL documentation for more information|https://dev.mysql.com/doc/refman/5.7/en/lock-tables.html>
930  
931 =head1 SEE ALSO
932  
933 L<perl>
934  
935 =head1 AUTHOR
936  
937 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
938  
939 =head1 COPYRIGHT & LICENSE
940  
941 Copyright (c) 2019-2021 DEGUEST Pte. Ltd.
942  
943 You can use, copy, modify and redistribute this package and associated
944 files under the same terms as Perl itself.
945  
946 =cut