| 1 | # -*- perl -*- | ||
| 2 | ##---------------------------------------------------------------------------- | ||
| 3 | ## Database Object Interface - ~/lib/DB/Object/SQLite/Tables.pm | ||
| 4 | ## Version v1.0.1 | ||
| 5 | ## Copyright(c) 2023 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::SQLite::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 $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.1'; | ||
| 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." ) if( $self->_is_warnings_enabled( 'DB::Object' ) ); | ||
| 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 | sub stat { return( shift->database_object->stat( @_ ) ); } | ||
| 237 | |||
| 238 | # TODO: Must implement a cache mechanism for DB::Object::SQLite::structure() | ||
| 239 | # <https://www.sqlite.org/pragma.html#pragma_table_info> | ||
| 240 | sub structure | ||
| 241 | { | ||
| 242 | my $self = shift( @_ ); | ||
| 243 | return( $self->_clone( $self->{_cache_structure} ) ) if( $self->{_cache_structure} && !CORE::length( $self->{_reset_structure} // '' ) ); | ||
| 244 | my $table = $self->{table} || | ||
| 245 | return( $self->error( "No table provided to get its structure." ) ); | ||
| 246 | my $sth1 = $self->prepare_cached( "SELECT * FROM sqlite_master WHERE name = ?" ) || | ||
| 247 | return( $self->error( "An error occured while preparing the sql query to get the details of table \"$table\": ", $self->errstr() ) ); | ||
| 248 | $sth1->execute( $table ) || | ||
| 249 | return( $self->error( "An error occured while executing the sql query to get the details of table \"$table\": ", $sth1->errstr ) ); | ||
| 250 | my $def = $sth1->fetchrow_hashref; | ||
| 251 | $sth1->finish; | ||
| 252 | # table or view | ||
| 253 | $self->{type} = $def->{type}; | ||
| 254 | my $struct = $self->{structure}; | ||
| 255 | my $fields = $self->{fields}; | ||
| 256 | my $types_dict = $self->database_object->datatype_dict; | ||
| 257 | $self->_load_class( 'DB::Object::Fields::Field' ) || return( $self->pass_error ); | ||
| 258 | my $q = $self->_reset_query; | ||
| 259 | # .header on | ||
| 260 | # PRAGMA table_info('dummy'); | ||
| 261 | # cid|name|type|notnull|dflt_value|pk | ||
| 262 | my $query = "PRAGMA table_info(${table})"; | ||
| 263 | # <https://www.sqlite.org/pragma.html> | ||
| 264 | my $sth = $self->database_object->prepare_cached( $query ) || | ||
| 265 | return( $self->error( "Error while preparing query to get table '$table' columns specification: ", $self->errstr() ) ); | ||
| 266 | $sth->execute || | ||
| 267 | return( $self->error( "Error while executing query to get table '$table' columns specification: ", $sth->errstr() ) ); | ||
| 268 | my @primary = (); | ||
| 269 | my $ref = ''; | ||
| 270 | my $c = 0; | ||
| 271 | # Mysql: field, type, null, key, default, extra | ||
| 272 | # Postgres: tablename, field, field_num, type, len, comment, is_nullable, key, foreign_key, default | ||
| 273 | # SQLite: cid, name, type, notnull, dflt_value, pk | ||
| 274 | while( $ref = $sth->fetchrow_hashref() ) | ||
| 275 | { | ||
| 276 | my $def = | ||
| 277 | { | ||
| 278 | name => $ref->{name}, | ||
| 279 | default => $ref->{dflt_value}, | ||
| 280 | is_nullable => ( $ref->{notnull} ? 0 : 1 ), | ||
| 281 | is_primary => ( $ref->{is_primary} ? 1 : 0 ), | ||
| 282 | pos => ++$c, | ||
| 283 | #query_object => $q, | ||
| 284 | size => undef, | ||
| 285 | type => $ref->{type}, | ||
| 286 | #table_object => $self, | ||
| 287 | }; | ||
| 288 | if( $def->{type} =~ /^([^\(]+)\(([^\)]+)\)$/ ) | ||
| 289 | { | ||
| 290 | @$def{qw( type size )} = ( $1, $2 ); | ||
| 291 | } | ||
| 292 | |||
| 293 | my( $const_def, $dict ); | ||
| 294 | if( CORE::exists( $types_dict->{ $def->{type} } ) ) | ||
| 295 | { | ||
| 296 | $const_def = $types_dict->{ $def->{type} }; | ||
| 297 | } | ||
| 298 | else | ||
| 299 | { | ||
| 300 | # Get the constant | ||
| 301 | DATA_TYPE_RE: foreach my $type ( keys( %$types_dict ) ) | ||
| 302 | { | ||
| 303 | if( $def->{type} =~ /$types_dict->{ $type }->{re}/i ) | ||
| 304 | { | ||
| 305 | $const_def = $types_dict->{ $type }; | ||
| 306 | last DATA_TYPE_RE; | ||
| 307 | } | ||
| 308 | } | ||
| 309 | } | ||
| 310 | if( defined( $const_def ) ) | ||
| 311 | { | ||
| 312 | my $const_keys = [keys( %$const_def )]; | ||
| 313 | my $dict = {}; | ||
| 314 | @$dict{ @$const_keys } = @$const_def{ @$const_keys }; | ||
| 315 | $def->{datatype} = $dict; | ||
| 316 | } | ||
| 317 | $def->{query_object} = $q; | ||
| 318 | $def->{table_object} = $self; | ||
| 319 | my @define = ( $def->{type} ); | ||
| 320 | push( @define, "DEFAULT '$def->{default}'" ) if( defined( $def->{default} ) && length( $def->{default} // '' ) ); | ||
| 321 | push( @define, "NOT NULL" ) if( $ref->{notnull} ); | ||
| 322 | push( @primary, $def->{name} ) if( $ref->{pk} ); | ||
| 323 | $struct->{ $def->{name} } = CORE::join( ' ', @define ); | ||
| 324 | my $field = DB::Object::Fields::Field->new( %$def, debug => $self->debug ) || | ||
| 325 | return( $self->pass_error( DB::Object::Fields::Field->error ) ); | ||
| 326 | $fields->{ $def->{name} } = $field; | ||
| 327 | } | ||
| 328 | $sth->finish; | ||
| 329 | if( @primary ) | ||
| 330 | { | ||
| 331 | $self->{primary} = \@primary; | ||
| 332 | } | ||
| 333 | $self->{fields} = $fields; | ||
| 334 | $self->{_cache_structure} = $struct; | ||
| 335 | return( $self->_clone( $struct ) ); | ||
| 336 | } | ||
| 337 | |||
| 338 | sub table_info { return( shift->database_object->tables_info( @_ ) ); } | ||
| 339 | |||
| 340 | sub unlock { return( shift->error( "Locking and unlocking of tables is unsupportde in SQLite." ) ); } | ||
| 341 | |||
| 342 | # NOTE: sub _simple_exist is inherited from DB::Object | ||
| 343 | # sub _simple_exist | ||
| 344 | |||
| 345 | # NOTE: DESTROY | ||
| 346 | DESTROY | ||
| 347 | { | ||
| 348 | # Do nothing | ||
| 349 | # DB::Object::Tables are never destroyed. | ||
| 350 | # They are just gateway to tables, and they are cached by DB::Object::table() | ||
| 351 | # print( STDERR "DESTROY'ing table $self ($self->{table})\n" ); | ||
| 352 | }; | ||
| 353 | |||
| 354 | 1; | ||
| 355 | |||
| 356 | # NOTE: POD | ||
| 357 | __END__ |