lib/DB/Object/SQLite/Tables.pm

filter: Statementstmt 44.7% 72 / 161 Branchbran 30.4% 25 / 82 Conditioncond 17.2% 10 / 58 MC/DCmcdc 6.9% 2 / 29 Subroutinesub 50.0% 9 / 18 Podpod 100% 10 / 10 totaltotal 35.7% 128 / 358 CC 69 SCAR 54.8
CC
69
Cov
36%
create
702.0
create_info
110.0
rename
56.0
CRAP 239.3
« blib/lib/DB/Object/SQLite/Query.pm ↑ Summary lib/DB/Object/SQLite/Query.pm »
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 2 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 2 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 2 ▶ use parent qw( DB::Object::SQLite DB::Object::Tables );
Subroutine BEGIN: called CC=1 SCAR=0.0
25 2 ▶ use vars qw( $VERSION $DEBUG $TYPE_TO_CONSTANT );
Subroutine BEGIN: called CC=1 SCAR=0.0
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 2 ▶ our $TYPE_TO_CONSTANT =
Subroutine BEGIN: called CC=1 SCAR=0.0
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 2 our $DEBUG = 0;
39 2 our $VERSION = 'v1.0.0';
40 };
41  
42 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
44  
45 sub init
46 {
47 2 ▶ return( shift->DB::Object::Tables::init( @_ ) );
Subroutine init: called CC=1 SCAR=0.0
Pod documented
48 }
49  
50 # Inherited from DB::Object::Tables
51 # sub alter
52  
53 sub create
54 {
55 0 ▶ my $self = shift( @_ );
Subroutine create: not called CC=26 SCAR=65.5
Pod documented
56 # $tbl->create( [ 'ROW 1', 'ROW 2'... ], { 'temporary' => 1, 'TYPE' => ISAM }, $obj );
57 0 ▶ my $data = shift( @_ ) || [];
Condition0%0/2
shift @_ || []
l!l
00
MC/DC0%0/1
shift @_ || []
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
58 0 ▶ my $opt = shift( @_ ) || {};
Condition0%0/2
shift @_ || {}
l!l
00
MC/DC0%0/1
shift @_ || {}
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
59 0 my $sth = shift( @_ );
60 0 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 0 my $temp = $self->{temporary} = delete( $opt->{temporary} );
64 # Check possible options
65 0 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 0 my @options = ();
81 0 my @errors = ();
82 # Avoid working for nothing, make this condition
83 0 ▶ if( %$opt )
Branch: 1 branch
BranchTrueFalseTotal
if (%$opt) 0 0 0
84 {
85 0 my %lc_opt = map{ lc( $_ ) => $opt->{ $_ } } keys( %$opt );
86 0 $opt = \%lc_opt;
87 0 foreach my $key ( keys( %$opt ) )
88 {
89 0 ▶ next if( $opt->{ $key } =~ /^\s*$/ || !exists( $allowed->{ $key } ) );
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{$key} =~ /^\s*$/ or not exists $allowed->{$key} 0 0 0
Condition0%0/3
$opt->{$key} =~ /^\s*$/ or not exists $allowed->{$key}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt->{$key} =~ /^\s*$/ or not exists $allowed->{$key}
$opt->{$key} =~ /^\s*$/ not exists $allowed->{$key}
Truth table0%0/3
A or not(B)
A= $opt->{$key} =~ /^\s*$/B= not exists $allowed->{$key}
ABresult
1X1
011
000
90 0 ▶ if( $opt->{ $key } !~ /$allowed->{ $key }/ )
Branch: 1 branch
BranchTrueFalseTotal
if (not $opt->{$key} =~ /$allowed->{$key}/) { } 0 0 0
91 {
92 0 push( @errors, $key );
93 }
94 else
95 {
96 0 push( @options, $key );
97 }
98 }
99 0 ▶ $opt->{comment} = "'" . quotemeta( $opt->{comment} ) . "'" if( exists( $opt->{comment} ) );
Branch: 1 branch
BranchTrueFalseTotal
if exists $opt->{"comment"} 0 0 0
100 0 ▶ $opt->{password} = "'" . $opt->{password} . "'" if( exists( $opt->{password} ) );
Branch: 1 branch
BranchTrueFalseTotal
if exists $opt->{"password"} 0 0 0
101 }
102 0 ▶ if( @errors )
Branch: 1 branch
BranchTrueFalseTotal
if (@errors) 0 0 0
103 {
104 0 warn( "The options '", join( ', ', @errors ), "' were either not recognized or malformed and thus were ignored.\n" );
105 }
106 # Check statement
107 0 my $select = '';
108 0 ▶ if( $sth && ref( $sth ) && ( $sth->isa( 'DB::Object::Statement' ) || $sth->can( 'as_string' ) ) )
Branch: 1 branch
BranchTrueFalseTotal
if ($sth and ref $sth and $sth->isa("DB::Object::Statement") || $sth->can("as_string")) 0 0 0
Condition0%0/9
$sth and ref $sth and $sth->isa("DB::Object::Statement") || $sth->can("as_string")
!ll&&!rl&&r
000
$sth and ref $sth
!ll&&!rl&&r
000
$sth->isa("DB::Object::Statement") or $sth->can("as_string")
l!l&&r!l&&!r
000
MC/DC0%0/4
$sth and ref $sth and $sth->isa("DB::Object::Statement") || $sth->can("as_string")
$sth ref $sth $sth->isa("DB::Object::Statement") $sth->can("as_string")
Truth table0%0/5
A and B and C or D
A= $sthB= ref $sthC= $sth->isa("DB::Object::Statement")D= $sth->can("as_string")
ABCDresult
0XXX0
10XX0
11000
111X1
11011
109 {
110 0 $select = $sth->as_string();
111 0 ▶ if( $select !~ /^\s*(?:IGNORE|REPLACE)*\s*\bSELECT\s+/ )
Branch: 1 branch
BranchTrueFalseTotal
unless ($select =~ /^\s*(?:IGNORE|REPLACE)*\s*\bSELECT\s+/) 0 0 0
112 {
113 0 return( $self->error( "SELECT statement to use to create table is invalid:\n$select" ) );
114 }
115 }
116 0 ▶ if( $self->exists() == 0 )
Branch: 1 branch
BranchTrueFalseTotal
if ($self->exists == 0) { } 0 0 0
117 {
118 0 ▶ my $query = 'CREATE ' . ( $temp ? 'TEMPORARY ' : '' ) . "TABLE $table ";
Branch: 1 branch
BranchTrueFalseTotal
$temp ? : 0 0 0
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 0 ▶ my $def = "(\n" . CORE::join( ",\n", @$data ) . "\n)" if( $data && ref( $data ) && @$data );
Branch: 1 branch
BranchTrueFalseTotal
if $data and ref $data and @$data 0 0 0
Condition0%0/6
$data and ref $data and @$data
!ll&&!rl&&r
000
$data and ref $data
!ll&&!rl&&r
000
MC/DC0%0/3
$data and ref $data and @$data
$data ref $data @$data
Truth table0%0/4
A and B and C
A= $dataB= ref $dataC= @$data
ABCresult
0XX0
10X0
1100
1111
123 0 my $tdef = CORE::join( ' ', map{ "\U$_\E = $opt->{ $_ }" } @options );
124 0 ▶ if( !$def && !$select )
Branch: 1 branch
BranchTrueFalseTotal
unless ($def or $select) 0 0 0
Condition0%0/3
$def or $select
l!l&&r!l&&!r
000
MC/DC0%0/2
$def or $select
$def $select
Truth table0%0/3
A or B
A= $defB= $select
ABresult
1X1
011
000
125 {
126 0 return( $self->error( "Lacking table '$table' structure information to create it." ) );
127 }
128 0 $query .= join( ' ', $def, $tdef, $select );
129 0 ▶ my $new = $self->prepare( $query ) ||
Condition0%0/2
$self->prepare($query) || (return $self->error("Error while preparing query to create table '${table}':\n$query", $self->errstr))
l!l
00
MC/DC0%0/1
$self->prepare($query) || (return $self->error("Error while preparing query to create table '${table}':\n$query", $self->errstr))
$self->prepare($query)
Truth table0%0/2
A
A= $self->prepare($query)
Aresult
11
00
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 0 ▶ if( !defined( wantarray() ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 0 0 0
133 {
134 0 ▶ $new->execute ||
Branch: 1 branch
BranchTrueFalseTotal
$new->execute or return $self->error("Error while executing query to create table '${table}':\n$query", $new->errstr) 0 0 0
135 return( $self->error( "Error while executing query to create table '$table':\n$query", $new->errstr() ) );
136 }
137 0 $self->reset_structure;
138 0 return( $new );
139 }
140 else
141 {
142 0 return( $self->error( "Table '$table' already exists." ) );
143 }
144 }
145  
146 sub create_info
147 {
148 0 ▶ my $self = shift( @_ );
Subroutine create_info: not called CC=10 SCAR=47.0
Pod documented
149 0 my $table = $self->{table};
150 0 ▶ $self->structure || return( $self->pass_error );
Branch: 1 branch
BranchTrueFalseTotal
$self->structure or return $self->pass_error 0 0 0
151 0 my $struct = $self->{structure};
152 0 my $fields = $self->{fields};
153 0 my $default = $self->{default};
154 0 my $primary = $self->{primary};
155 0 my @output = ();
156 0 foreach my $field ( sort{ $fields->{ $a } <=> $fields->{ $b } } keys( %$fields ) )
157 {
158 0 push( @output, "$field $struct->{ $field }" );
159 }
160 0 ▶ push( @output, "PRIMARY KEY(" . CORE::join( ',', @$primary ) . ")" ) if( $primary && @$primary );
Branch: 1 branch
BranchTrueFalseTotal
if $primary and @$primary 0 0 0
Condition0%0/3
$primary and @$primary
!ll&&!rl&&r
000
MC/DC0%0/2
$primary and @$primary
$primary @$primary
Truth table0%0/3
A and B
A= $primaryB= @$primary
ABresult
0X0
100
111
161 0 my $info = $self->stat( $table );
162 0 my @opt = ();
163 0 ▶ push( @opt, "TYPE = $info->{type}" ) if( $info->{type} );
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"type"} 0 0 0
164 0 my $addons = $info->{create_options};
165 0 ▶ if( $addons )
Branch: 1 branch
BranchTrueFalseTotal
if ($addons) 0 0 0
166 {
167 0 $addons =~ s/(\A|\s+)([\w\_]+)\s*=\s*/$1\U$2\E=/g;
168 0 push( @opt, $addons );
169 }
170 0 ▶ push( @opt, "COMMENT='" . quotemeta( $info->{comment} ) . "'" ) if( $info->{comment} );
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"comment"} 0 0 0
171 0 my $str = "CREATE TABLE $table (\n\t" . CORE::join( ",\n\t", @output ) . "\n)";
172 0 ▶ $str .= ' ' . CORE::join( ' ', @opt ) if( @opt );
Branch: 1 branch
BranchTrueFalseTotal
if @opt 0 0 0
173 0 $str .= ';';
174 0 ▶ return( @output ? $str : undef() );
Branch: 1 branch
BranchTrueFalseTotal
@output ? : 0 0 0
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 0 ▶sub exists { return( shift->table_exists( shift( @_ ) ) ); }
Subroutine exists: not called CC=1 SCAR=6.9
Pod documented
184  
185 0 ▶sub lock { return( shift->error( "There is no table locking in SQLite." ) ); }
Subroutine lock: not called CC=1 SCAR=6.9
Pod documented
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 0 ▶ my $self = shift( @_ );
Subroutine on_conflict: not called CC=5 SCAR=34.0
Pod documented
199 0 my $q = $self->_reset_query;
200 0 ▶ return( $q->on_conflict( @_ ) ) if( !defined( wantarray() ) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 0 0 0
201 0 ▶ if( wantarray() )
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
202 {
203 0 ▶ my( @val ) = $q->on_conflict( @_ ) || return( $self->pass_error( $q->error ) );
Condition0%0/2
$q->on_conflict(@_) || (return $self->pass_error($q->error))
l!l
00
MC/DC0%0/1
$q->on_conflict(@_) || (return $self->pass_error($q->error))
$q->on_conflict(@_)
Truth table0%0/2
A
A= $q->on_conflict(@_)
Aresult
11
00
204 0 return( @val );
205 }
206 else
207 {
208 0 ▶ my $val = $q->on_conflict( @_ ) || return( $self->pass_error( $q->error ) );
Condition0%0/2
$q->on_conflict(@_) || (return $self->pass_error($q->error))
l!l
00
MC/DC0%0/1
$q->on_conflict(@_) || (return $self->pass_error($q->error))
$q->on_conflict(@_)
Truth table0%0/2
A
A= $q->on_conflict(@_)
Aresult
11
00
209 0 return( $val );
210 }
211 }
212  
213 sub rename
214 {
215 0 ▶ my $self = shift( @_ );
Subroutine rename: not called CC=7 SCAR=40.3
Pod documented
216 my $table = $self->{table} ||
217 0 ▶ return( $self->error( 'No table was provided to rename' ) );
Condition0%0/2
$self->{'table'} || (return $self->error('No table was provided to rename'))
l!l
00
MC/DC0%0/1
$self->{'table'} || (return $self->error('No table was provided to rename'))
$self->{'table'}
Truth table0%0/2
A
A= $self->{'table'}
Aresult
11
00
218 0 ▶ my $new = shift( @_ ) ||
Condition0%0/2
shift @_ || (return $self->error("No new table name was provided to rename table '${table}'."))
l!l
00
MC/DC0%0/1
shift @_ || (return $self->error("No new table name was provided to rename table '${table}'."))
shift @_
Truth table0%0/2
A
A= shift @_
Aresult
11
00
219 return( $self->error( "No new table name was provided to rename table '$table'." ) );
220 0 ▶ if( $new !~ /^[a-zA-Z][\w\_]+$/ )
Branch: 1 branch
BranchTrueFalseTotal
unless ($new =~ /^[a-zA-Z][\w\_]+$/) 0 0 0
221 {
222 0 return( $self->error( "Bad new table name '$new'." ) );
223 }
224 0 my $query = "ALTER TABLE $table RENAME TO $new";
225 0 ▶ my $sth = $self->prepare( $query ) ||
Condition0%0/2
$self->prepare($query) || (return $self->error("Error while preparing query to rename table '${table}' into '${new}':\n$query", $self->errstr))
l!l
00
MC/DC0%0/1
$self->prepare($query) || (return $self->error("Error while preparing query to rename table '${table}' into '${new}':\n$query", $self->errstr))
$self->prepare($query)
Truth table0%0/2
A
A= $self->prepare($query)
Aresult
11
00
226 return( $self->error( "Error while preparing query to rename table '$table' into '$new':\n$query", $self->errstr() ) );
227 0 ▶ if( !defined( wantarray() ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 0 0 0
228 {
229 0 ▶ $sth->execute ||
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute or return $self->error("Error while executing query to rename table '${table}' into '${new}':\n$query", $sth->errstr) 0 0 0
230 return( $self->error( "Error while executing query to rename table '$table' into '$new':\n$query", $sth->errstr() ) );
231 }
232 0 $self->reset_structure;
233 0 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 57 ▶ my $self = shift( @_ );
Subroutine structure: called CC=25 SCAR=32.9
Pod documented
241 57 ▶ return( $self->_clone( $self->{_cache_structure} ) ) if( $self->{_cache_structure} && !CORE::length( $self->{_reset_structure} // '' ) );
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_cache_structure"} and not length($self->{"_reset_structure"} // "") 55 2 57
Condition60%3/5
$self->{"_cache_structure"} and not length($self->{"_reset_structure"} // "")
!ll&&!rl&&r
2055
$self->{"_reset_structure"} // ""
l!l
055
MC/DC50%1/2
$self->{"_cache_structure"} and not length($self->{"_reset_structure"} // "")
$self->{"_cache_structure"} $self->{"_reset_structure"}
Truth table66%2/3
A and not(B)
A= $self->{"_cache_structure"}B= $self->{"_reset_structure"}
ABresult
0X0
110
101
242 my $table = $self->{table} ||
243 2 ▶ return( $self->error( "No table provided to get its structure." ) );
Condition50%1/2
$self->{'table'} || (return $self->error('No table provided to get its structure.'))
l!l
20
MC/DC0%0/1
$self->{'table'} || (return $self->error('No table provided to get its structure.'))
$self->{'table'}
Truth table50%1/2
A
A= $self->{'table'}
Aresult
11
00
244 2 ▶ my $sth1 = $self->prepare_cached( "SELECT * FROM sqlite_master WHERE name = ?" ) ||
Condition50%1/2
$self->prepare_cached('SELECT * FROM sqlite_master WHERE name = ?') || (return $self->error(qq[An error occured while preparing the sql query to get the details of table "$table": ], $self->errstr))
l!l
20
MC/DC0%0/1
$self->prepare_cached('SELECT * FROM sqlite_master WHERE name = ?') || (return $self->error(qq[An error occured while preparing the sql query to get the details of table "$table": ], $self->errstr))
$self->prepare_cached('SELECT * FROM sqlite_master WHERE name = ?')
Truth table50%1/2
A
A= $self->prepare_cached('SELECT * FROM sqlite_master WHERE name = ?')
Aresult
11
00
245 return( $self->error( "An error occured while preparing the sql query to get the details of table \"$table\": ", $self->errstr() ) );
246 2 ▶ $sth1->execute( $table ) ||
Branch: 1 branch
BranchTrueFalseTotal
$sth1->execute($table) or return $self->error(qq[An error occured while executing the sql query to get the details of table "$table": ], $sth1->errstr) 0 2 2
247 return( $self->error( "An error occured while executing the sql query to get the details of table \"$table\": ", $sth1->errstr ) );
248 2 my $def = $sth1->fetchrow_hashref;
249 2 $sth1->finish;
250 # table or view
251 2 $self->{type} = $def->{type};
252 2 my $struct = $self->{structure};
253 2 my $fields = $self->{fields};
254 2 my $types_dict = $self->database_object->datatype_dict;
255 2 ▶ $self->_load_class( 'DB::Object::Fields::Field' ) || return( $self->pass_error );
Branch: 1 branch
BranchTrueFalseTotal
$self->_load_class("DB::Object::Fields::Field") or return $self->pass_error 0 2 2
256 2 my $q = $self->_reset_query;
257 # .header on
258 # PRAGMA table_info('dummy');
259 # cid|name|type|notnull|dflt_value|pk
260 2 my $query = "PRAGMA table_info(${table})";
261 # <https://www.sqlite.org/pragma.html>
262 2 ▶ my $sth = $self->database_object->prepare_cached( $query ) ||
Condition50%1/2
$self->database_object->prepare_cached($query) || (return $self->error("Error while preparing query to get table '${table}' columns specification: ", $self->errstr))
l!l
20
MC/DC0%0/1
$self->database_object->prepare_cached($query) || (return $self->error("Error while preparing query to get table '${table}' columns specification: ", $self->errstr))
$self->database_object->prepare_cached($query)
Truth table50%1/2
A
A= $self->database_object->prepare_cached($query)
Aresult
11
00
263 return( $self->error( "Error while preparing query to get table '$table' columns specification: ", $self->errstr() ) );
264 2 ▶ $sth->execute ||
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute or return $self->error("Error while executing query to get table '${table}' columns specification: ", $sth->errstr) 0 2 2
265 return( $self->error( "Error while executing query to get table '$table' columns specification: ", $sth->errstr() ) );
266 2 my @primary = ();
267 2 my $ref = '';
268 2 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 2 ▶ while( $ref = $sth->fetchrow_hashref() )
Branch: 1 branch
BranchTrueFalseTotal
if ($ref = $sth->fetchrow_hashref) 7 2 9
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 7 ▶ };
Branch: 2 branches
BranchTrueFalseTotal
$ref->{'notnull'} ? : 1 6 7
$ref->{'is_primary'} ? : 0 7 7
286 7 ▶ if( $def->{type} =~ /^([^\(]+)\(([^\)]+)\)$/ )
Branch: 1 branch
BranchTrueFalseTotal
if ($def->{"type"} =~ /^([^\(]+)\(([^\)]+)\)$/) 3 4 7
287 {
288 3 @$def{qw( type size )} = ( $1, $2 );
289 }
290  
291 7 my( $const_def, $dict );
292 7 ▶ if( CORE::exists( $types_dict->{ $def->{type} } ) )
Branch: 1 branch
BranchTrueFalseTotal
if (exists $$types_dict{$def->{'type'}}) { } 0 7 7
293 {
294 0 $const_def = $types_dict->{ $def->{type} };
295 }
296 else
297 {
298 # Get the constant
299 7 DATA_TYPE_RE: foreach my $type ( keys( %$types_dict ) )
300 {
301 148 ▶ if( $def->{type} =~ /$types_dict->{ $type }->{re}/i )
Branch: 1 branch
BranchTrueFalseTotal
if ($def->{"type"} =~ /$types_dict->{$type}{"re"}/i) 2 146 148
302 {
303 2 $const_def = $types_dict->{ $type };
304 2 last DATA_TYPE_RE;
305 }
306 }
307 }
308 7 ▶ if( defined( $const_def ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $const_def) 2 5 7
309 {
310 2 my $const_keys = [keys( %$const_def )];
311 2 my $dict = {};
312 2 @$dict{ @$const_keys } = @$const_def{ @$const_keys };
313 2 $def->{datatype} = $dict;
314 }
315 7 $def->{query_object} = $q;
316 7 $def->{table_object} = $self;
317 7 my @define = ( $def->{type} );
318 7 ▶ push( @define, "DEFAULT '$def->{default}'" ) if( defined( $def->{default} ) && length( $def->{default} // '' ) );
Branch: 1 branch
BranchTrueFalseTotal
if defined $def->{"default"} and length($def->{"default"} // "") 2 5 7
Condition60%3/5
defined $def->{"default"} and length($def->{"default"} // "")
!ll&&!rl&&r
502
$def->{"default"} // ""
l!l
20
MC/DC50%1/2
defined $def->{"default"} and length($def->{"default"} // "")
defined $def->{"default"} $def->{"default"}
Truth table66%2/3
A and B
A= defined $def->{"default"}B= $def->{"default"}
ABresult
0X0
100
111
319 7 ▶ push( @define, "NOT NULL" ) if( $ref->{notnull} );
Branch: 1 branch
BranchTrueFalseTotal
if $ref->{"notnull"} 1 6 7
320 7 ▶ push( @primary, $def->{name} ) if( $ref->{pk} );
Branch: 1 branch
BranchTrueFalseTotal
if $ref->{"pk"} 1 6 7
321 7 $struct->{ $def->{name} } = CORE::join( ' ', @define );
322 7 ▶ my $field = DB::Object::Fields::Field->new( %$def, debug => $self->debug ) ||
Condition50%1/2
'DB::Object::Fields::Field'->new(%$def, 'debug', $self->debug) || (return $self->pass_error('DB::Object::Fields::Field'->error))
l!l
70
MC/DC0%0/1
'DB::Object::Fields::Field'->new(%$def, 'debug', $self->debug) || (return $self->pass_error('DB::Object::Fields::Field'->error))
'DB::Object::Fields::Field'->new(%$def, 'debug', $self->debug)
Truth table50%1/2
A
A= 'DB::Object::Fields::Field'->new(%$def, 'debug', $self->debug)
Aresult
11
00
323 return( $self->pass_error( DB::Object::Fields::Field->error ) );
324 7 $fields->{ $def->{name} } = $field;
325 }
326 2 $sth->finish;
327 2 ▶ if( @primary )
Branch: 1 branch
BranchTrueFalseTotal
if (@primary) 1 1 2
328 {
329 1 $self->{primary} = \@primary;
330 }
331 2 $self->{fields} = $fields;
332 2 $self->{_cache_structure} = $struct;
333 2 return( $self->_clone( $struct ) );
334 }
335  
336 0 ▶sub table_info { return( shift->database_object->tables_info( @_ ) ); }
Subroutine table_info: not called CC=1 SCAR=6.9
Pod documented
337  
338 0 ▶sub unlock { return( shift->error( "Locking and unlocking of tables is unsupportde in SQLite." ) ); }
Subroutine unlock: not called CC=1 SCAR=6.9
Pod documented
339  
340 # NOTE: sub _simple_exist is inherited from DB::Object
341 # sub _simple_exist
342  
343 # NOTE: DESTROY
344 DESTROY
345 ▶{
Subroutine DESTROY: not called CC=1 SCAR=0.0
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 2 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
« blib/lib/DB/Object/SQLite/Query.pm ↑ Summary lib/DB/Object/SQLite/Query.pm »