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

filter: Statementstmt 0.0% 0 / 163 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 70 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 331 CC 35 SCAR 46.2
CC
35
Cov
0%
create
210.0
structure
156.0
create_info
56.0
CRAP 102.0
1 # -*- perl -*-
2 ##----------------------------------------------------------------------------
3 ## Database Object Interface - ~/lib/DB/Object/SQLite/Tables.pm
4 ## Version v1.0.0
5 ## Copyright(c) 2023 DEGUEST Pte. Ltd.
6 ## Author: Jacques Deguest <jack@deguest.jp>
7 ## Created 2017/07/19
8 ## Modified 2023/11/17
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::SQLite::Tables;
20 BEGIN
21 {
22 use strict;
23 use warnings;
24 use parent qw( DB::Object::SQLite DB::Object::Tables );
25 use vars qw( $VERSION $DEBUG $TYPE_TO_CONSTANT );
26 # <https://metacpan.org/pod/DBD::SQLite::Constants>
27 # <https://www.sqlite.org/datatype3.html>
28 # <https://metacpan.org/pod/DBD::SQLite::Constants#datatypes-(fundamental_datatypes)>
29 # NULL, INTEGER, REAL, TEXT, BLOB
30 our $TYPE_TO_CONSTANT =
31 {
32 qr/^(INT|INTEGER|TINYINT|SMALLINT|MEDIUMINT|BIGINT|UNSIGNED\s+BIG\s+INT|INT2|INT8)/ => { constant => '', name => 'SQLITE_INTEGER', type => 'integer' },
33 qr/^(CHARACTER\(\d+\)|VARCHAR\(\d+\)|VARYING\s+CHARACTER\(\d+\)|NCHAR\(\d+\)|NATIVE\s+CHARACTER\(\d+\)|NVARCHAR\(\d+\)|TEXT|CLOB)/ => { constant => '', name => 'SQLITE_TEXT', type => 'text' },
34 qr/^BLOB/ => { constant => '', name => 'SQLITE_BLOB', type => 'blob' },
35 qr/^(REAL|DOUBLE\s+DOUBLE\s+PRECISION|FLOAT)/ => { constant => '', name => 'SQLITE_FLOAT', type => 'float' },
36 qr/^(NUMERIC|DECIMAL\(\d+,\d+\)|BOOLEAN|DATETIME|DATE)/ => { constant => '', name => 'SQLITE_NULL', type => 'bool' },
37 };
38 our $DEBUG = 0;
39 our $VERSION = 'v1.0.0';
40 };
41  
42 use strict;
43 use warnings;
44  
45 sub init
46 {
47 return( shift->DB::Object::Tables::init( @_ ) );
48 }
49  
50 # Inherited from DB::Object::Tables
51 # sub alter
52  
53 sub create
54 {
55 my $self = shift( @_ );
56 # $tbl->create( [ 'ROW 1', 'ROW 2'... ], { 'temporary' => 1, 'TYPE' => ISAM }, $obj );
57 my $data = shift( @_ ) || [];
58 my $opt = shift( @_ ) || {};
59 my $sth = shift( @_ );
60 my $table = $self->{table};
61 # Set temporary in the object, so we can use it to recreate the table creation info as string:
62 # $table->create( [ ... ], { ... }, $obj )->as_string();
63 my $temp = $self->{temporary} = delete( $opt->{temporary} );
64 # Check possible options
65 my $allowed =
66 {
67 type => qr/^(ISAM|MYISAM|HEAP)$/i,
68 auto_increment => qr/^(1|0)$/,
69 avg_row_length => qr/^\d+$/,
70 checksum => qr/^(1|0)$/,
71 comment => qr//,
72 max_rows => qr/^\d+$/,
73 min_rows => qr/^\d+$/,
74 pack_keys => qr/^(1|0)$/,
75 password => qr//,
76 delay_key_write => qr/^\d+$/,
77 row_format => qr/^(default|dynamic|static|compressed)$/i,
78 raid_type => qr/^(?:1|STRIPED|RAID0|RAID_CHUNKS\s*=\s*\d+|RAID_CHUNKSIZE\s*=\s*\d+)$/,
79 };
80 my @options = ();
81 my @errors = ();
82 # Avoid working for nothing, make this condition
83 if( %$opt )
84 {
85 my %lc_opt = map{ lc( $_ ) => $opt->{ $_ } } keys( %$opt );
86 $opt = \%lc_opt;
87 foreach my $key ( keys( %$opt ) )
88 {
89 next if( $opt->{ $key } =~ /^\s*$/ || !exists( $allowed->{ $key } ) );
90 if( $opt->{ $key } !~ /$allowed->{ $key }/ )
91 {
92 push( @errors, $key );
93 }
94 else
95 {
96 push( @options, $key );
97 }
98 }
99 $opt->{comment} = "'" . quotemeta( $opt->{comment} ) . "'" if( exists( $opt->{comment} ) );
100 $opt->{password} = "'" . $opt->{password} . "'" if( exists( $opt->{password} ) );
101 }
102 if( @errors )
103 {
104 warn( "The options '", join( ', ', @errors ), "' were either not recognized or malformed and thus were ignored.\n" );
105 }
106 # Check statement
107 my $select = '';
108 if( $sth && ref( $sth ) && ( $sth->isa( 'DB::Object::Statement' ) || $sth->can( 'as_string' ) ) )
109 {
110 $select = $sth->as_string();
111 if( $select !~ /^\s*(?:IGNORE|REPLACE)*\s*\bSELECT\s+/ )
112 {
113 return( $self->error( "SELECT statement to use to create table is invalid:\n$select" ) );
114 }
115 }
116 if( $self->exists() == 0 )
117 {
118 my $query = 'CREATE ' . ( $temp ? 'TEMPORARY ' : '' ) . "TABLE $table ";
119 # Structure of table if any -
120 # structure may very well be provided using a select statement, such as:
121 # CREATE TEMPORARY TABLE ploppy TYPE=HEAP COMMENT='this is kewl' MAX_ROWS=10 SELECT * FROM some_table LIMIT 0,0
122 my $def = "(\n" . CORE::join( ",\n", @$data ) . "\n)" if( $data && ref( $data ) && @$data );
123 my $tdef = CORE::join( ' ', map{ "\U$_\E = $opt->{ $_ }" } @options );
124 if( !$def && !$select )
125 {
126 return( $self->error( "Lacking table '$table' structure information to create it." ) );
127 }
128 $query .= join( ' ', $def, $tdef, $select );
129 my $new = $self->prepare( $query ) ||
130 return( $self->error( "Error while preparing query to create table '$table':\n$query", $self->errstr() ) );
131 # Trick so other method may follow, such as as_string(), fetchrow(), rows()
132 if( !defined( wantarray() ) )
133 {
134 $new->execute ||
135 return( $self->error( "Error while executing query to create table '$table':\n$query", $new->errstr() ) );
136 }
137 $self->reset_structure;
138 return( $new );
139 }
140 else
141 {
142 return( $self->error( "Table '$table' already exists." ) );
143 }
144 }
145  
146 sub create_info
147 {
148 my $self = shift( @_ );
149 my $table = $self->{table};
150 $self->structure || return( $self->pass_error );
151 my $struct = $self->{structure};
152 my $fields = $self->{fields};
153 my $default = $self->{default};
154 my $primary = $self->{primary};
155 my @output = ();
156 foreach my $field ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) )
157 {
158 push( @output, "$field $struct->{ $field }" );
159 }
160 push( @output, "PRIMARY KEY(" . CORE::join( ',', @$primary ) . ")" ) if( $primary && @$primary );
161 my $info = $self->stat( $table );
162 my @opt = ();
163 push( @opt, "TYPE = $info->{type}" ) if( $info->{type} );
164 my $addons = $info->{create_options};
165 if( $addons )
166 {
167 $addons =~ s/(\A|\s+)([\w\_]+)\s*=\s*/$1\U$2\E=/g;
168 push( @opt, $addons );
169 }
170 push( @opt, "COMMENT='" . quotemeta( $info->{comment} ) . "'" ) if( $info->{comment} );
171 my $str = "CREATE TABLE $table (\n\t" . CORE::join( ",\n\t", @output ) . "\n)";
172 $str .= ' ' . CORE::join( ' ', @opt ) if( @opt );
173 $str .= ';';
174 return( @output ? $str : undef() );
175 }
176  
177 # NOTE: sub default is inherited from DB::Object::Tables
178 # sub default
179  
180 # NOTE: sub drop is inherited from DB::Object::Tables
181 # sub drop
182  
183 sub exists { return( shift->table_exists( shift( @_ ) ) ); }
184  
185 sub lock { return( shift->error( "There is no table locking in SQLite." ) ); }
186  
187 # NOTE: sub name is inherited from DB::Object::Tables
188 # sub name
189  
190 # NOTE: sub null is inherited from DB::Object::Tables
191 # sub null
192  
193 # NOTE: sub primary is inherited from DB::Object::Tables
194 # sub primary
195  
196 sub on_conflict
197 {
198 my $self = shift( @_ );
199 my $q = $self->_reset_query;
200 return( $q->on_conflict( @_ ) ) if( !defined( wantarray() ) );
201 if( wantarray() )
202 {
203 my( @val ) = $q->on_conflict( @_ ) || return( $self->pass_error( $q->error ) );
204 return( @val );
205 }
206 else
207 {
208 my $val = $q->on_conflict( @_ ) || return( $self->pass_error( $q->error ) );
209 return( $val );
210 }
211 }
212  
213 sub rename
214 {
215 my $self = shift( @_ );
216 my $table = $self->{table} ||
217 return( $self->error( 'No table was provided to rename' ) );
218 my $new = shift( @_ ) ||
219 return( $self->error( "No new table name was provided to rename table '$table'." ) );
220 if( $new !~ /^[a-zA-Z][\w\_]+$/ )
221 {
222 return( $self->error( "Bad new table name '$new'." ) );
223 }
224 my $query = "ALTER TABLE $table RENAME TO $new";
225 my $sth = $self->prepare( $query ) ||
226 return( $self->error( "Error while preparing query to rename table '$table' into '$new':\n$query", $self->errstr() ) );
227 if( !defined( wantarray() ) )
228 {
229 $sth->execute ||
230 return( $self->error( "Error while executing query to rename table '$table' into '$new':\n$query", $sth->errstr() ) );
231 }
232 $self->reset_structure;
233 return( $sth );
234 }
235  
236 # TODO: Must implement a cache mechanism for DB::Object::SQLite::structure()
237 # <https://www.sqlite.org/pragma.html#pragma_table_info>
238 sub structure
239 {
240 my $self = shift( @_ );
241 return( $self->_clone( $self->{_cache_structure} ) ) if( $self->{_cache_structure} && !CORE::length( $self->{_reset_structure} // '' ) );
242 my $table = $self->{table} ||
243 return( $self->error( "No table provided to get its structure." ) );
244 my $sth1 = $self->prepare_cached( "SELECT * FROM sqlite_master WHERE name = ?" ) ||
245 return( $self->error( "An error occured while preparing the sql query to get the details of table \"$table\": ", $self->errstr() ) );
246 $sth1->execute( $table ) ||
247 return( $self->error( "An error occured while executing the sql query to get the details of table \"$table\": ", $sth1->errstr ) );
248 my $def = $sth1->fetchrow_hashref;
249 $sth1->finish;
250 # table or view
251 $self->{type} = $def->{type};
252 my $struct = $self->{structure};
253 my $fields = $self->{fields};
254 my $types_dict = $self->database_object->datatype_dict;
255 $self->_load_class( 'DB::Object::Fields::Field' ) || return( $self->pass_error );
256 my $q = $self->_reset_query;
257 # .header on
258 # PRAGMA table_info('dummy');
259 # cid|name|type|notnull|dflt_value|pk
260 my $query = "PRAGMA table_info(${table})";
261 # <https://www.sqlite.org/pragma.html>
262 my $sth = $self->database_object->prepare_cached( $query ) ||
263 return( $self->error( "Error while preparing query to get table '$table' columns specification: ", $self->errstr() ) );
264 $sth->execute ||
265 return( $self->error( "Error while executing query to get table '$table' columns specification: ", $sth->errstr() ) );
266 my @primary = ();
267 my $ref = '';
268 my $c = 0;
269 # Mysql: field, type, null, key, default, extra
270 # Postgres: tablename, field, field_num, type, len, comment, is_nullable, key, foreign_key, default
271 # SQLite: cid, name, type, notnull, dflt_value, pk
272 while( $ref = $sth->fetchrow_hashref() )
273 {
274 my $def =
275 {
276 name => $ref->{name},
277 default => $ref->{dflt_value},
278 is_nullable => ( $ref->{notnull} ? 0 : 1 ),
279 is_primary => ( $ref->{is_primary} ? 1 : 0 ),
280 pos => ++$c,
281 #query_object => $q,
282 size => undef,
283 type => $ref->{type},
284 #table_object => $self,
285 };
286 if( $def->{type} =~ /^([^\(]+)\(([^\)]+)\)$/ )
287 {
288 @$def{qw( type size )} = ( $1, $2 );
289 }
290  
291 my( $const_def, $dict );
292 if( CORE::exists( $types_dict->{ $def->{type} } ) )
293 {
294 $const_def = $types_dict->{ $def->{type} };
295 }
296 else
297 {
298 # Get the constant
299 DATA_TYPE_RE: foreach my $type ( keys( %$types_dict ) )
300 {
301 if( $def->{type} =~ /$types_dict->{ $type }->{re}/i )
302 {
303 $const_def = $types_dict->{ $type };
304 last DATA_TYPE_RE;
305 }
306 }
307 }
308 if( defined( $const_def ) )
309 {
310 my $const_keys = [keys( %$const_def )];
311 my $dict = {};
312 @$dict{ @$const_keys } = @$const_def{ @$const_keys };
313 $def->{datatype} = $dict;
314 }
315 $def->{query_object} = $q;
316 $def->{table_object} = $self;
317 my @define = ( $def->{type} );
318 push( @define, "DEFAULT '$def->{default}'" ) if( defined( $def->{default} ) && length( $def->{default} // '' ) );
319 push( @define, "NOT NULL" ) if( $ref->{notnull} );
320 push( @primary, $def->{name} ) if( $ref->{pk} );
321 $struct->{ $def->{name} } = CORE::join( ' ', @define );
322 my $field = DB::Object::Fields::Field->new( %$def, debug => $self->debug ) ||
323 return( $self->pass_error( DB::Object::Fields::Field->error ) );
324 $fields->{ $def->{name} } = $field;
325 }
326 $sth->finish;
327 if( @primary )
328 {
329 $self->{primary} = \@primary;
330 }
331 $self->{fields} = $fields;
332 $self->{_cache_structure} = $struct;
333 return( $self->_clone( $struct ) );
334 }
335  
336 sub table_info { return( shift->database_object->tables_info( @_ ) ); }
337  
338 sub unlock { return( shift->error( "Locking and unlocking of tables is unsupportde in SQLite." ) ); }
339  
340 # NOTE: sub _simple_exist is inherited from DB::Object
341 # sub _simple_exist
342  
343 # NOTE: DESTROY
344 DESTROY
345 {
346 # Do nothing
347 # DB::Object::Tables are never destroyed.
348 # They are just gateway to tables, and they are cached by DB::Object::table()
349 # print( STDERR "DESTROY'ing table $self ($self->{table})\n" );
350 };
351  
352 1;
353  
354 # NOTE: POD
355 __END__
356  
357 =encoding utf-8
358  
359 =head1 NAME
360  
361 DB::Object::SQLite::Tables - SQLite Table Object
362  
363 =head1 SYNOPSIS
364  
365 use DB::Object::SQLite::Tables;
366 my $this = DB::Object::SQLite::Tables->new || die( DB::Object::SQLite::Tables->error, "\n" );
367  
368 =head1 VERSION
369  
370 v1.0.0
371  
372 =head1 DESCRIPTION
373  
374 This is a SQLite table object class.
375  
376 =head1 METHODS
377  
378 =head2 create
379  
380 This creates a table.
381  
382 It takes some array reference data containing the columns definitions, some optional parameters and a statement handler.
383  
384 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.
385  
386 Possible parameters are:
387  
388 =over 4
389  
390 =item * C<comment>
391  
392 =item * C<password>
393  
394 =item * C<temporary>
395  
396 If provided, this will create a temporary table.
397  
398 =back
399  
400 This will return an error if the table already exists, so best to check beforehand with L</exists>.
401  
402 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.
403  
404 =head2 create_info
405  
406 This returns the create info for the current table object as a string representing the sql script necessary to recreate the table.
407  
408 =head2 exists
409  
410 Returns true if the current table exists, or false otherwise.
411  
412 =head2 lock
413  
414 Table lock is unsupported in SQLite and this will return an error.
415  
416 =head2 on_conflict
417  
418 A convenient wrapper to L<DB::Object::Postgres::Query/on_conflict>
419  
420 This feature is available in SQLite since version 3.35.0 released on 2021-03-12. If your version of SQLite is anterior, this will return an error.
421  
422 =head2 rename
423  
424 Provided with a new table name, and this will prepare the necessary query to rename the table and return the statement handler.
425  
426 If it is called in void context, the statement handler is executed immediately.
427  
428 # Get the prefs table object
429 my $tbl = $dbh->pref;
430 $tbl->rename( 'prefs' );
431 # Would issue a statement handler for the query: ALTER TABLE pref RENAME TO prefs
432  
433 See L<SQLite documentation for more information|https://www.sqlite.org/lang_altertable.html>
434  
435 =head2 structure
436  
437 This returns in list context an hash and in scalar context an hash reference of the table structure.
438  
439 The hash, or hash reference returned contains the column name and its definition.
440  
441 This method will also set the following object properties:
442  
443 =over 4
444  
445 =item * L<DB::Object::Tables/type>
446  
447 The table type.
448  
449 =item * C<default>
450  
451 A column name to default value hash reference
452  
453 =item * C<fields>
454  
455 A column name to field position (integer) hash reference
456  
457 =item * C<null>
458  
459 A column name to a boolean representing whether the column is nullable or not.
460  
461 =item * L<DB::Object::Tables/primary>
462  
463 An array reference of column names that are used as primary key for the table.
464  
465 =item * C<structure>
466  
467 A column name to its sql definition
468  
469 =item * C<types>
470  
471 A column name to column data type hash reference
472  
473 =back
474  
475 =head2 table_info
476  
477 This is an alias for L<DB::Object::SQLite/table_info>
478  
479 =head2 unlock
480  
481 This returns an error as C<unlock> is unsupported in SQLite
482  
483 =head1 SEE ALSO
484  
485 L<perl>
486  
487 =head1 AUTHOR
488  
489 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
490  
491 =head1 COPYRIGHT & LICENSE
492  
493 Copyright (c) 2019-2021 DEGUEST Pte. Ltd.
494  
495 You can use, copy, modify and redistribute this package and associated
496 files under the same terms as Perl itself.
497  
498 =cut