blib/lib/DBIO/SQLite/Storage.pm

filter: Statementstmt 90.3% 214 / 237 Branchbran 71.7% 89 / 124 Conditioncond 62.7% 54 / 86 MC/DCmcdc 43.7% 21 / 48 Subroutinesub 97.8% 46 / 47 Podpod 85.7% 6 / 7 totaltotal 78.3% 430 / 549 CC 96 SCAR 27.4
CC
96
Cov
80%
_ping
83.4
_dbh_execute
19.2
_dbi_attrs_for_bind
18.0
CRAP 15.5
« blib/lib/DBIO/SQLite/Diff.pm ↑ Summary blib/lib/DBIO/SQLite/Test/Conformance.pm »
1 package DBIO::SQLite::Storage;
2 # ABSTRACT: SQLite storage driver for DBIO
3  
4 205 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 205 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 205 our $VERSION = '0.900007';
8  
9 205 ▶use base qw/DBIO::Storage::DBI/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 205 ▶use mro 'c3';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 205 __PACKAGE__->register_driver('SQLite' => __PACKAGE__);
13  
14 205 ▶use Context::Preserve 'preserve_context';
Subroutine BEGIN: called CC=1 SCAR=0.0
15 205 ▶use DBIO::Util qw(file_path iv_size mkpath modver_gt_or_eq os_name sigwarn_silencer);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 205 ▶use DBIO::SQLite::Util qw(column_is_nullable libsqlite_version pk_is_rowid_alias);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 205 ▶use DBIO::SQLite::Extension ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 205 ▶use DBIO::Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 205 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 205 ▶use File::Basename ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 205 ▶use File::Copy ();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 205 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 205 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 205 __PACKAGE__->sql_maker_class('DBIO::SQLite::SQLMaker');
26 205 __PACKAGE__->sql_quote_char ('"');
27 205 __PACKAGE__->datetime_parser_type ('DateTime::Format::SQLite');
28  
29 # F02 / F10 -- transactional DDL. Of every driver in this family that answers
30 # 0, SQLite is the one whose engine HAS it: CREATE / DROP / ALTER TABLE run
31 # inside an ordinary transaction and a ROLLBACK really does take them back,
32 # which elsewhere (PostgreSQL, Firebird, SQL Server) is what a 1 is for. The 0
33 # below is therefore not an engine limitation like it is for MySQL, Oracle or
34 # ClickHouse, and that is exactly why it has to be written down here rather
35 # than left to core's conservative default (which is also 0): judged by the
36 # engine alone this driver looks like an oversight, and "tidying" the omission
37 # into a 1 is a one-character change that breaks the upgrade path.
38 #
39 # What the 0 protects is the in-place table rebuild. SQLite cannot ALTER a
40 # column's type, nullability or default, so DBIO::SQLite::Diff escalates any
41 # such change to a DBIO::SQLite::Diff::Rebuild -- the documented create-new /
42 # copy / drop-old / rename dance -- and that op's statement list opens with
43 # PRAGMA foreign_keys=OFF and closes with PRAGMA foreign_keys=ON. Both
44 # brackets are no-ops inside a transaction, by SQLite's own rule: "This pragma
45 # is a no-op within a transaction; foreign key constraint enforcement may only
46 # be enabled or disabled when there is no pending BEGIN or SAVEPOINT"
47 # (sqlite.org/pragma.html#pragma_foreign_keys). Nothing throws and nothing
48 # warns -- the statement is accepted and simply does not take.
49 #
50 # So had this capability been true, DBIO::Deploy::Base::_execute_ddl would
51 # bracket its loop in $storage->txn_do, the BEGIN would come first, and
52 # enforcement would still be ON at the DROP TABLE in the middle of the
53 # rebuild. A DROP TABLE under enforced foreign keys performs an implicit
54 # DELETE FROM, so dropping the old table while another table still references
55 # its rows raises "FOREIGN KEY constraint failed"; the rebuild dies half way
56 # and the ALTER TABLE ... RENAME TO behind it then collides with the table
57 # that never got dropped. Measured on libsqlite 3.51.1 / DBD::SQLite 1.78.
58 # t/37-rebuild.t part C is that exact scenario -- a connection with
59 # PRAGMA foreign_keys = ON rebuilding a table another table references -- and
60 # it passes today only because the statement-at-a-time path leaves AutoCommit
61 # on, where the pragma does take.
62 #
63 # SQLite's own recipe orders it the same way: PRAGMA foreign_keys=OFF is step
64 # 1, BEFORE the transaction opened in step 2, and the restore is step 12,
65 # after the commit (sqlite.org/lang_altertable.html, "Making Other Kinds Of
66 # Table Schema Changes"). Turning this into a 1 is therefore not a flag flip:
67 # the pragmas would first have to move out of the diff op's statement list to
68 # around core's bracket (or _ddl_statement_is_transactional would have to
69 # answer false for them), and DBIO::SQLite::Deploy::apply's PRAGMA
70 # foreign_key_check, which today runs after the batch, would have to move
71 # inside the bracket to be able to roll one back.
72 #
73 # Core special-cases nothing: DBIO::Deploy::Base's TRANSACTIONAL DDL section
74 # lists SQLite as "capable, but deliberately answering no" and points back at
75 # this declaration as the only thing carrying the decision. The price is core's
76 # one-time "non-transactional DDL" notice, and it is accurate -- an apply that
77 # fails part way leaves the earlier statements applied; recovery is re-running
78 # the upgrade, whose diff is recomputed against live state. Value and
79 # declaredness are pinned by t/42-deploy-transactional-ddl.t.
80 205 __PACKAGE__->_use_transactional_ddl(0);
81  
82 # Must be defined AFTER `use namespace::clean` — a sub declared before it
83 # is wiped from the symbol table at end of compile, which would make
84 # DBIO::Schema/deploy fall back to the (unsupported) SQL::Translator path.
85 408 ▶sub dbio_deploy_class { 'DBIO::SQLite::Deploy' }
Subroutine dbio_deploy_class: called CC=1 SCAR=0.0
Pod undocumented
86  
87 # The dialect the DDL splitter reads this engine's text in (core karr k332,
88 # DBIO::Storage::DBI::Capabilities "DDL SPLITTING"); karr k78.
89 765 ▶sub _ddl_sql_dialect { 'sqlite' }
Subroutine _ddl_sql_dialect: called CC=1 SCAR=0.0
90  
91 # --- extensions (ADR 0066): the activation of a new connection ---------------
92  
93  
94 728 ▶sub _extension_activation {
Subroutine _extension_activation: called CC=3 SCAR=11.0
95 728 my ($self) = @_;
96  
97 728 ▶ my $list = DBIO::SQLite::Extension->resolve_list($self->schema)
Branch: 1 branch
BranchTrueFalseTotal
my $list = "DBIO::SQLite::Extension"->resolve_list($self->schema) or return undef 20 707 727
98 or return undef;
99  
100 20 require DBIO::Extension::Protocol;
101 20 my $activation = DBIO::Extension::Protocol->new(
102 entries => [ $list->entries ],
103 driver => DBIO::SQLite::Extension->driver_helpers,
104 connection_schema => undef,
105 restricted => 0,
106 )->activation;
107  
108 19 ▶ return @{ $activation->{load} } ? $activation : undef;
Branch: 1 branch
BranchTrueFalseTotal
@{$activation->{'load'};} ? : 11 8 19
109 }
110  
111  
112 7 ▶sub _activate_extensions {
Subroutine _activate_extensions: called CC=4 SCAR=13.9
113 7 my ($self, $activation) = @_;
114  
115 $self->throw_exception(
116 'A SQLite extension library is loaded into the connection handle, which '
117 . 'a statement runner of an async pool does not give: the libraries of '
118 . 'sqlite_extensions ('
119 1 . join(', ', @{ $activation->{load} }) . ') cannot be activated there'
120 7 ▶ ) if $self->{_pool_connect_runner};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_pool_connect_runner"} 1 6 7
121  
122 6 my $dbh = $self->_dbh;
123 6 for my $library (@{ $activation->{load} }) {
124 7 my $ok = eval {
125 7 local $dbh->{RaiseError} = 1;
126 7 $dbh->sqlite_enable_load_extension(1);
127 7 $dbh->sqlite_load_extension($library);
128 5 $dbh->sqlite_enable_load_extension(0);
129 5 1;
130 };
131 7 ▶ next if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 5 2 7
132  
133 2 my $error = $@;
134 2 $error =~ s/\s+\z//;
135 2 eval { $dbh->sqlite_enable_load_extension(0) };
136  
137 # A handle without its extensions is not one to leave in the storage
138 # (the rule of DBIO::Storage::DBI/_do_connection_actions): the next use
139 # would get a connection that silently lacks the library.
140 2 $self->_dbh(undef);
141 2 $self->throw_exception("Cannot load the SQLite extension library '$library': $error");
142 }
143  
144 4 return $self;
145 }
146  
147 31043 ▶sub sql_maker {
Subroutine sql_maker: called CC=3 SCAR=11.6
Pod documented
148 31043 my $self = shift;
149 31043 my $sm = $self->next::method(@_);
150 # SQLite always uses double-quote identifier quoting — ensure it is
151 # active even when the caller did not pass quote_names in connect_info.
152 31043 ▶ $sm->{quote_char} //= $self->sql_quote_char;
Condition66%2/3
$sm->{"quote_char"} //= $self->sql_quote_char
l!l&&r!l&&!r
3104030
MC/DC0%0/2
$sm->{"quote_char"} //= $self->sql_quote_char
$sm->{"quote_char"} $self->sql_quote_char
Truth table66%2/3
A //= B
A= $sm->{"quote_char"}B= $self->sql_quote_char
ABresult
1X1
011
000
153 31043 ▶ $sm->{name_sep} //= $self->sql_name_sep;
Condition33%1/3
$sm->{"name_sep"} //= $self->sql_name_sep
l!l&&r!l&&!r
3104300
MC/DC0%0/2
$sm->{"name_sep"} //= $self->sql_name_sep
$sm->{"name_sep"} $self->sql_name_sep
Truth table33%1/3
A //= B
A= $sm->{"name_sep"}B= $self->sql_name_sep
ABresult
1X1
011
000
154 31043 $sm;
155 }
156  
157 13 ▶sub _dbh_columns_info_for {
Subroutine _dbh_columns_info_for: called CC=8 SCAR=21.3
158 13 my ($self, $dbh, $table) = @_;
159  
160 13 ▶ my $result = $self->SUPER::_dbh_columns_info_for($dbh, $table) // {};
Condition50%1/2
$self->SUPER::_dbh_columns_info_for($dbh, $table) // {}
l!l
130
MC/DC0%0/1
$self->SUPER::_dbh_columns_info_for($dbh, $table) // {}
$self->SUPER::_dbh_columns_info_for($dbh, $table)
Truth table50%1/2
A
A= $self->SUPER::_dbh_columns_info_for($dbh, $table)
Aresult
11
00
161  
162 # DBD::SQLite's column_info (and its prepared-statement NULLABLE fallback)
163 # do not report is_nullable reliably -- PK columns come back as nullable,
164 # and columns in unique constraints may also be wrong. PRAGMA table_info
165 # is the authoritative source: notnull=1 means NOT NULL. Layer its truth
166 # over the parent's result so that PK columns are correctly NOT NULL.
167 # Strip any "schema." prefix the caller may have supplied.
168 13 my $bare = $table;
169 13 $bare =~ s/^.*\.//;
170  
171 13 my $sth = eval { $dbh->prepare(sprintf 'PRAGMA table_info(%s)', $dbh->quote($bare)) };
172 13 ▶ return $result unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 13 13
173 13 $sth->execute;
174 13 my @rows;
175 13 ▶ while (my $row = $sth->fetchrow_hashref) { push @rows, $row }
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 32 13 45
176 13 $sth->finish;
177  
178 # A PRIMARY KEY column carries no NOT NULL attribute of its own, so PRAGMA
179 # table_info reports notnull=0 for it -- but on SQLite that is not merely a
180 # reporting quirk: every key except the INTEGER PRIMARY KEY rowid alias
181 # really does store NULL on a rowid table (karr k29). One probe per table
182 # settles which kind of key this is, and only when there is a key at all.
183 # column_is_nullable is the single source of truth for the rule itself,
184 # shared with DBIO::SQLite::Introspect so both paths answer the same.
185 13 ▶ my $alias = (grep { $_->{pk} } @rows) ? pk_is_rowid_alias($dbh, $bare) : 1;
Branch: 1 branch
BranchTrueFalseTotal
grep({$_->{'pk'};} @rows) ? : 13 0 13
186  
187 13 for my $row (@rows) {
188 32 my $col = $row->{name};
189 32 ▶ next unless $col && exists $result->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless $col and exists $result->{$col} 0 32 32
Condition33%1/3
$col and exists $result->{$col}
!ll&&!rl&&r
0032
MC/DC0%0/2
$col and exists $result->{$col}
$col exists $result->{$col}
Truth table33%1/3
A and B
A= $colB= exists $result->{$col}
ABresult
0X0
100
111
190 $result->{$col}{is_nullable} =
191 32 column_is_nullable($row->{notnull}, $row->{pk}, $alias);
192 }
193  
194 13 return $result;
195 }
196  
197  
198  
199 3 ▶sub _determine_supports_multicolumn_in {
Subroutine _determine_supports_multicolumn_in: called CC=2 SCAR=7.6
200 3 ▶ ( shift->_server_info->{normalized_dbms_version} < '3.014' )
Branch: 1 branch
BranchTrueFalseTotal
+(shift())->_server_info->{'normalized_dbms_version'} < '3.014' ? : 0 3 3
201 ? 0
202 : 1
203 }
204  
205 # INSERT ... RETURNING exists since libsqlite 3.35 (2021-03-12). Without it
206 # every insert of an autoinc / retrieve_on_insert column costs an extra
207 # round-trip (last_insert_id + follow-up SELECT in DBIO::Storage::DBI::insert).
208 # Deliberately NOT declaring insert_returning_bound: like PostgreSQL, and
209 # unlike Oracle's "RETURNING ... INTO :bind", SQLite hands the values back as
210 # an ordinary result set on the statement handle, which is exactly what core
211 # fetches when no returning_container is requested.
212 215 ▶sub _determine_supports_insert_returning {
Subroutine _determine_supports_insert_returning: called CC=2 SCAR=7.6
213 215 ▶ ( shift->_server_info->{normalized_dbms_version} < '3.035' )
Branch: 1 branch
BranchTrueFalseTotal
+(shift())->_server_info->{'normalized_dbms_version'} < '3.035' ? : 0 215 215
214 ? 0
215 : 1
216 }
217  
218 # ADR 0036 -- atomic upsert. SQLite has had the INSERT ... ON CONFLICT grammar
219 # since libsqlite 3.24 (2018-06-04), but grammar is not the gate here.
220 #
221 # The ADR makes it a hard driver obligation: declare supports_upsert only if the
222 # identity handed back is provably the row that was written. Core retrieves it
223 # with last_insert_id() plus a follow-up SELECT on the PRIMARY KEY -- it never
224 # re-finds by conflict target. An upsert that takes the DO UPDATE branch
225 # performs no insert, so last_insert_rowid() still reports the PREVIOUS insert
226 # and core would hand back a confidently wrong, unrelated row. Silent bad data,
227 # worse than undef.
228 #
229 # RETURNING is therefore the precondition, not the round-trip saving it looks
230 # like -- so gate on the effective insert_returning capability rather than on
231 # the libsqlite version a second time. Same 3.35 threshold in practice, but it
232 # also stays correct when RETURNING is deliberately switched off with
233 # __PACKAGE__->_use_insert_returning(0): a plain version test would keep
234 # claiming upsert there and go straight back to returning the wrong row.
235 # Losing upsert on 3.24 - 3.34 is the honest trade.
236 3 ▶sub _determine_supports_supports_upsert {
Subroutine _determine_supports_supports_upsert: called CC=2 SCAR=6.9
237 3 ▶ shift->_use_insert_returning ? 1 : 0
Branch: 1 branch
BranchTrueFalseTotal
(shift())->_use_insert_returning ? : 2 1 3
238 }
239  
240 # ADR 0036 / core k105 -- the conditional conflict branch, DO UPDATE ... WHERE.
241 #
242 # Deliberately NOT gated the way supports_upsert above is. That gate is about
243 # naming the written row (RETURNING), a requirement the condition does not add
244 # to: an upsert whose condition does not hold writes nothing and core hands
245 # back undef, which is why it refuses result => 'row_or_die' with update_where
246 # up front. The clause itself is coeval with the ON CONFLICT grammar -- both
247 # arrived in libsqlite 3.24 -- so there is no version left to test either, and
248 # no configuration in which this driver renders ON CONFLICT but not its WHERE.
249 #
250 # What is left is a plain fact about the SQL generator, which is exactly what
251 # the capability means (see DBIO::Storage::DBI::Capabilities: "implies nothing
252 # on its own -- it is only ever consulted together with supports_upsert").
253 # Restating the RETURNING coupling here would make the flag answer a question
254 # it was not asked; core checks both, in that order, and reports whichever is
255 # missing.
256 #
257 # Declared through _determine_supports_* rather than as __PACKAGE__->_use_ class
258 # data, matching the driver's other capability declarations. The originally
259 # recorded reason -- "so that the tier-1 force slot stays the caller's" -- was
260 # refuted by core k137 / ADR 0041: the per-storage force and the class-level
261 # declaration are two different slots (instance hash vs the
262 # $Class::__cag_<field> package variable), so neither declaration form takes
263 # the caller's force away, and the undef-clearing fix made both forms measure
264 # 1 / 0 / 1. What the tier-3 form still changes is _supports_X, which answers
265 # the declaration here but would answer core's default 0 alongside a tier-2
266 # declaration; no core consumer reads _supports_X for a decision, so this is
267 # consistency, not correctness.
268 2 ▶sub _determine_supports_supports_upsert_where { 1 }
Subroutine _determine_supports_supports_upsert_where: called CC=1 SCAR=0.0
269  
270 # ADR 0037 -- the boolean-valued EXISTS query behind DBIO::ResultSet::results_exist
271 # and its two siblings. This driver overrides nothing: core's base rendering,
272 # SELECT CASE WHEN EXISTS (<inner>) THEN 1 ELSE 0 END, is already the spelling
273 # SQLite wants. Only the engines that refuse a FROM-less SELECT have to override
274 # _exists_value_sql and append their dummy table (Oracle DUAL, DB2
275 # SYSIBM.SYSDUMMY1, Firebird RDB$DATABASE); SQLite has no such rule.
276 #
277 # The flag is still not vacuous here -- it asserts that somebody checked, which
278 # is why the default is 0 and why declaring it is a separate act from inheriting
279 # the hook.
280 #
281 # Ungated on purpose, unlike the two capabilities above. CASE arrived in
282 # libsqlite 2.4.4 (2002-03-30) and the EXISTS operator in 3.1.0 (2005-01-21),
283 # while DBD::SQLite refuses to build against an external libsqlite below 3.6.0
284 # at all -- so there is no reachable build where a version test could answer
285 # anything but yes, and a gate that cannot fail only hides what it was for.
286 # 3.014 and 3.035 above are real thresholds; this one would be decoration.
287 #
288 # DECLARED IN THE _determine_ SLOT, NOT AS __PACKAGE__->_use_supports_exists_query(1)
289 # (karr k27). ADR 0037 section 2 names the _use_ form and the other drivers took
290 # it, so the deviation is recorded here rather than left to be re-discovered.
291 # Core's own contract POD blesses both -- "register their engine value via
292 # __PACKAGE__->_use_X(0|1) OR by defining _determine_supports_X"
293 # (DBIO::Storage::DBI::Capabilities) -- and since core k137 / ADR 0041 they are
294 # interchangeable in every way this driver's suite exercises.
295 #
296 # The reason for the deviation originally recorded here is refuted there. It
297 # claimed a class-level _use_ declaration shares the tier-1 FORCE slot with a
298 # caller's instance-level force, so $storage->_use_X(0) followed by
299 # $storage->_use_X(undef) leaves the capability off for the life of the storage,
300 # the undef falling through to core's default 0. Neither half holds.
301 # Class::Accessor::Grouped::set_inherited writes two physically different places
302 # depending on the invocant -- the instance hash for a storage, the
303 # $Class::__cag_<field> package variable for a class -- so the class-level
304 # declaration was never overwritten by any force; measured directly, the package
305 # variable held 1 throughout. The 0 the old measurement saw was a get_inherited
306 # defect one level down: it reads an instance with exists(), not defined(), so
307 # the force's own undef left a tombstone in the instance slot that shadowed the
308 # declaration. undef was not a clear. Core fixed that in set_use_dbms_capability,
309 # which deletes the slot on undef (commit 3a440360f); both declaration forms now
310 # measure 1 / 0 / 1, and t/23-results-exist.t's force-and-clear round-trip works
311 # in either form. ADR 0037 section 2 stands as written.
312 #
313 # What still differs is get_dbms_capability('_supports_supports_exists_query')
314 # versus _use_supports_exists_query. With the declaration in tier 3 both answer
315 # the same 1; the class-level _use_ form leaves the former answering core's
316 # default 0 on a storage that does support the query. Core verified that no
317 # consumer reads _supports_X for a decision -- they all read _use_X, which the
318 # POD documents as the read accessor -- so this is consistency, not correctness.
319 #
320 # What the class-level _use_ form buys instead is a class-method answer
321 # (DBIO::SQLite::Storage->_use_supports_exists_query), which the determine form
322 # cannot give -- get_dbms_capability throws on a class invocant by design (core
323 # k119). Nothing in core asks the class; ResultSet::results_exist probes
324 # the instance.
325 #
326 # This is the same choice as supports_upsert_where above. The general question
327 # the deviation once raised -- which tier is THE declaration form -- is settled:
328 # ADR 0041 made the two equivalent, so keeping this declaration where it is
329 # costs nothing and aligning it to ADR 0037's named form would buy nothing. The
330 # deviation stands as a record, not a disagreement.
331 3 ▶sub _determine_supports_supports_exists_query { 1 }
Subroutine _determine_supports_supports_exists_query: called CC=1 SCAR=0.0
332  
333 # ADR 0039 -- the one seam for all six set operations, which replaced the
334 # single-operation _except_operator of ADR 0037 section 3. Two of the six have
335 # no spelling on this engine at all, so this hook's other job applies: refuse.
336 #
337 # SQLite's compound operators are UNION, UNION ALL, INTERSECT and EXCEPT --
338 # ALL attaches to UNION alone (sqlite.org/lang_select.html, "Compound Select
339 # Statements", and the compound-operator syntax diagram). Unconditionally so:
340 # the four arrived together on 2000-06-06, before version 1.0, and the set has
341 # never grown -- the changelog through 3.53.4 has no INTERSECT ALL and no
342 # EXCEPT ALL entry. So unlike Oracle (MINUS ALL in 21c) or MySQL (EXCEPT in
343 # 8.0.31), there is no version boundary here that ADR 0039 section 7's
344 # "refuse unconditionally and pay for it on the versions that do have it"
345 # trade would be paying for. Nothing is withheld from anybody.
346 #
347 # The four operations SQLite does have are NOT re-spelled: they go to
348 # next::method and come back with core's base ANSI keyword, which is what this
349 # engine speaks.
350 28 ▶sub _set_operation_keyword {
Subroutine _set_operation_keyword: called CC=5 SCAR=16.1
351 28 my ($self, $op) = @_;
352  
353 28 ▶ if (defined $op and ($op eq 'intersect_all' or $op eq 'except_all')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $op and $op eq "intersect_all" || $op eq "except_all") 10 18 28
Condition83%5/6
defined $op and $op eq "intersect_all" || $op eq "except_all"
!ll&&!rl&&r
01810
$op eq "intersect_all" or $op eq "except_all"
l!l&&r!l&&!r
4618
MC/DC66%2/3
defined $op and $op eq "intersect_all" || $op eq "except_all"
defined $op $op eq "intersect_all" $op eq "except_all"
Truth table75%3/4
A and B or C
A= defined $opB= $op eq "intersect_all"C= $op eq "except_all"
ABCresult
0XX0
1000
11X1
1011
354 10 (my $keyword = uc $op) =~ s/_/ /;
355 10 ▶ my $nearest = $op eq 'except_all' ? 'except' : 'intersect';
Branch: 1 branch
BranchTrueFalseTotal
$op eq 'except_all' ? : 6 4 10
356  
357 10 $self->throw_exception(
358 "SQLite has no $keyword operator, so \$rs->$op cannot be rendered on "
359 . 'this engine. Its compound operators are UNION, UNION ALL, INTERSECT '
360 . 'and EXCEPT -- ALL attaches to UNION alone. That has been true of every '
361 . 'SQLite there is: the four arrived together in 2000, before version '
362 . '1.0, and none has been added since, so this refusal is unconditional '
363 . 'rather than version-gated and withholds nothing from a newer '
364 . "libsqlite. \$rs->$nearest is the nearest operation this engine does "
365 . 'have, but it is not a drop-in -- it removes duplicate rows, which is '
366 . "exactly what $keyword is asked for, so that substitution is yours to "
367 . 'make deliberately and not this driver\'s to make silently.'
368 );
369 }
370  
371 18 return $self->next::method($op);
372 }
373  
374 # ADR 0040 / karr k23 -- the WHOLE operation of obtaining a query plan, the hook
375 # that replaced the string-valued _explain_sql. This driver has to override it,
376 # and of the whole family it was the most urgent to: SQLite is the one engine
377 # here on which core's inherited default does not fail loudly.
378 #
379 # A bare EXPLAIN is ACCEPTED by SQLite. It answers with the VDBE bytecode of the
380 # compiled statement -- addr/opcode/p1..p5/comment, one row per virtual machine
381 # instruction -- which is a perfectly well-formed arrayref of row arrayrefs and
382 # therefore indistinguishable, to the caller of DBIO::ResultSet::explain, from
383 # the plan that was asked for. No exception, no empty result, no clue: the wrong
384 # question, confidently answered. Every other engine that needed this rollout
385 # either speaks EXPLAIN or refuses it where somebody notices.
386 #
387 # The plan lives behind EXPLAIN QUERY PLAN (sqlite.org/eqp.html), whose rows are
388 # id/parent/notused/detail and whose detail column carries the SCAN / SEARCH ...
389 # USING INDEX text that is the entire reason to call explain -- "most
390 # significantly, EXPLAIN QUERY PLAN reports on the way in which the query uses
391 # database indices". The bytecode dump does not contain that answer in any form
392 # a caller can read: it does not name the index at all. t/25-explain-query-plan.t
393 # pins both halves against the engine.
394 #
395 # All four assumptions ADR 0040 found baked into the old string shape do hold
396 # here -- one statement, executed, returning rows, and those rows are the plan --
397 # so unlike Oracle, DB2, SQL Server and Firebird this override is core's base
398 # implementation with three words changed, and it stays that shape on purpose
399 # rather than composing anything of its own.
400 #
401 # The statement still goes through _execute_rendered. That is the contract's hard
402 # rule and it has no engine-named exceptions: it keeps _query_start / _query_end
403 # tracing and therefore redact_bind_value (ADR 0025) over what are the user's own
404 # WHERE-clause values, dbh_do retry over a dropped connection, NoBindVars
405 # interpolation, and -- on a DBIO::Replicated::Storage -- the read handler rather
406 # than the master's handle. Those four are exactly what core k112 restored by
407 # routing explain through the storage in the first place, and reaching for
408 # $self->dbh here would hand every one of them back.
409 7 ▶sub _explain_query {
Subroutine _explain_query: called CC=1 SCAR=0.0
410 7 my ($self, $sql, $bind) = @_;
411  
412 7 my (undef, $sth) = $self->_execute_rendered("EXPLAIN QUERY PLAN $sql", $bind);
413  
414 7 return $sth->fetchall_arrayref;
415 }
416  
417 2 ▶sub backup {
Subroutine backup: called CC=10 SCAR=24.3
Pod documented
418 2 my ($self, $dir) = @_;
419 2 ▶ $dir //= './';
Condition100%2/2
$dir //= "./"
l!l
11
MC/DC100%1/1
$dir //= "./"
$dir
Truth table100%2/2
A
A= $dir
Aresult
11
00
420  
421 ## Where is the db file?
422 2 my $dsn = $self->_dbi_connect_info()->[0];
423  
424 2 ▶ my $dbname = $1 if($dsn =~ /dbname=([^;]+)/);
Branch: 1 branch
BranchTrueFalseTotal
if $dsn =~ /dbname=([^;]+)/ 0 2 2
425 2 ▶ if(!$dbname)
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbname) 1 1 2
426 {
427 1 ▶ $dbname = $1 if($dsn =~ /^dbi:SQLite:(.+)$/i);
Branch: 1 branch
BranchTrueFalseTotal
if $dsn =~ /^dbi:SQLite:(.+)$/i 1 0 1
428 }
429 2 ▶ $self->throw_exception("Cannot determine name of SQLite db file")
Branch: 1 branch
BranchTrueFalseTotal
unless $dbname and -f $dbname 0 2 2
Condition33%1/3
$dbname and -f $dbname
!ll&&!rl&&r
002
MC/DC0%0/2
$dbname and -f $dbname
$dbname -f $dbname
Truth table33%1/3
A and B
A= $dbnameB= -f $dbname
ABresult
0X0
100
111
430 if(!$dbname || !-f $dbname);
431  
432 2 my $file = File::Basename::basename($dbname);
433 2 $file = POSIX::strftime("%Y-%m-%d-%H_%M_%S", localtime()) . $file;
434 2 ▶ $file = "B$file" while(-f $file);
Branch: 1 branch
BranchTrueFalseTotal
-f $file and do { $file = "B$file" } 0 2 2
435  
436 2 ▶ mkpath($dir) unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 2 2
437 2 my $backupfile = file_path($dir, $file);
438  
439 2 my $res = File::Copy::copy($dbname, $backupfile);
440 2 ▶ $self->throw_exception("Backup failed! ($!)") if(!$res);
Branch: 1 branch
BranchTrueFalseTotal
unless $res 0 2 2
441  
442 2 return $backupfile;
443 }
444  
445  
446 7 ▶sub vacuum {
Subroutine vacuum: called CC=3 SCAR=11.0
Pod documented
447 7 my ($self, $into) = @_;
448  
449 7 ▶ return $self->_do_query('VACUUM')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $into 2 5 7
450 unless defined $into;
451  
452 # VACUUM INTO is libsqlite 3.27+; an older one answers it with a bare
453 # 'near "INTO": syntax error'. Say what is missing before any statement.
454 5 my ($version, $numeric) = libsqlite_version($self->_get_dbh);
455 5 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $numeric < 3027000 2 3 5
456 "VACUUM INTO needs libsqlite 3.27 or newer, this is libsqlite $version"
457 ) if $numeric < 3_027_000;
458  
459 # The target filename MUST go as a bind parameter, so the emitted SQL is
460 # "VACUUM INTO ?" -- never interpolated into the statement text.
461 3 return $self->_do_query([ 'VACUUM INTO ?', undef, $into ]);
462 }
463  
464  
465 21 ▶sub _exec_svp_begin {
Subroutine _exec_svp_begin: called CC=1 SCAR=0.0
466 21 my ($self, $name) = @_;
467  
468 21 $self->_dbh->do("SAVEPOINT $name");
469 }
470  
471 9 ▶sub _exec_svp_release {
Subroutine _exec_svp_release: called CC=1 SCAR=0.0
472 9 my ($self, $name) = @_;
473  
474 9 $self->_dbh->do("RELEASE SAVEPOINT $name");
475 }
476  
477 14 ▶sub _exec_svp_rollback {
Subroutine _exec_svp_rollback: called CC=3 SCAR=14.2
478 14 my ($self, $name) = @_;
479  
480 14 $self->_dbh->do("ROLLBACK TO SAVEPOINT $name");
481  
482 # resync state for older DBD::SQLite (RT#67843)
483 # https://github.com/DBD-SQLite/DBD-SQLite/commit/9b3cdbf
484 14 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (not &modver_gt_or_eq("DBD::SQLite", "1.33") and $self->_dbh->FETCH("AutoCommit")) 0 14 14
Condition33%1/3
not &modver_gt_or_eq("DBD::SQLite", "1.33") and $self->_dbh->FETCH("AutoCommit")
!ll&&!rl&&r
1400
MC/DC0%0/2
not &modver_gt_or_eq("DBD::SQLite", "1.33") and $self->_dbh->FETCH("AutoCommit")
not &modver_gt_or_eq("DBD::SQLite", "1.33") $self->_dbh->FETCH("AutoCommit")
Truth table33%1/3
not(A) and B
A= not &modver_gt_or_eq("DBD::SQLite", "1.33")B= $self->_dbh->FETCH("AutoCommit")
ABresult
0X0
100
111
485 ! modver_gt_or_eq('DBD::SQLite', '1.33')
486 and
487 $self->_dbh->FETCH('AutoCommit')
488 ) {
489 0 $self->_dbh->STORE('AutoCommit', 0);
490 0 $self->_dbh->STORE('BegunWork', 1);
491 }
492 }
493  
494 1272 ▶sub _ping {
Subroutine _ping: called CC=15 SCAR=44.2
495 1272 my $self = shift;
496  
497 # Be extremely careful what we do here. SQLite is notoriously bad at
498 # synchronizing its internal transaction state with {AutoCommit}
499 # https://metacpan.org/source/ADAMK/DBD-SQLite-1.37/lib/DBD/SQLite.pm#L921
500 # There is a function http://www.sqlite.org/c3ref/get_autocommit.html
501 # but DBD::SQLite does not expose it (nor does it seem to properly use it)
502  
503 # Therefore only execute a "ping" when we have no other choice *AND*
504 # scrutinize the thrown exceptions to make sure we are where we think we are
505 1272 ▶ my $dbh = $self->_dbh or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = $self->_dbh or return undef 1272 0 1272
506 1272 ▶ return undef unless $dbh->FETCH('Active');
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->FETCH("Active") 0 1272 1272
507 1272 ▶ return undef unless $dbh->ping;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh->ping 0 1272 1272
508  
509 1272 my $ping_fail;
510  
511 # older DBD::SQLite does not properly synchronize commit state between
512 # the libsqlite and the $dbh
513 1272 ▶ unless (defined $DBD::SQLite::__DBIO_TXN_SYNC_SANE__) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $DBD::SQLite::__DBIO_TXN_SYNC_SANE__) 190 1082 1272
514 190 $DBD::SQLite::__DBIO_TXN_SYNC_SANE__ = modver_gt_or_eq('DBD::SQLite', '1.38_02');
515 }
516  
517 # fallback to travesty
518 1272 ▶ unless ($DBD::SQLite::__DBIO_TXN_SYNC_SANE__) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($DBD::SQLite::__DBIO_TXN_SYNC_SANE__) 0 1272 1272
519 # since we do not have access to sqlite3_get_autocommit(), do a trick
520 # to attempt to *safely* determine what state are we *actually* in.
521 # FIXME
522 # also using T::T here leads to bizarre leaks - will figure it out later
523 0 my $really_not_in_txn = do {
524 0 local $@;
525  
526 # older versions of DBD::SQLite do not properly detect multiline BEGIN/COMMIT
527 # statements to adjust their {AutoCommit} state. Hence use such a statement
528 # pair here as well, in order to escape from poking {AutoCommit} needlessly
529 # https://rt.cpan.org/Public/Bug/Display.html?id=80087
530 eval {
531 # will fail instantly if already in a txn
532 0 $dbh->do("-- multiline\nBEGIN");
533 0 $dbh->do("-- multiline\nCOMMIT");
534 0 1;
535 0 ▶ } or do {
Condition0%0/3
eval { do { $dbh->do("-- multiline\nBEGIN"); $dbh->do("-- multiline\nCOMMIT"); 1 } } || do { $@ =~ /transaction within a transaction/ ? 0 : undef }
l!l&&r!l&&!r
000
MC/DC0%0/2
eval { do { $dbh->do("-- multiline\nBEGIN"); $dbh->do("-- multiline\nCOMMIT"); 1 } } || do { $@ =~ /transaction within a transaction/ ? 0 : undef }
eval { do { $dbh->do("-- multiline\nBEGIN"); $dbh->do("-- multiline\nCOMMIT"); 1 } } do { $@ =~ /transaction within a transaction/ ? 0 : undef }
Truth table0%0/3
A || B
A= eval { do { $dbh->do("-- multiline\nBEGIN"); $dbh->do("-- multiline\nCOMMIT"); 1 } }B= do { $@ =~ /transaction within a transaction/ ? 0 : undef }
ABresult
1X1
011
000
536 0 ▶ ($@ =~ /transaction within a transaction/)
Branch: 1 branch
BranchTrueFalseTotal
$@ =~ /transaction within a transaction/ ? : 0 0 0
537 ? 0
538 : undef
539 ;
540 };
541 };
542  
543 # if we were unable to determine this - we may very well be dead
544 0 ▶ if (not defined $really_not_in_txn) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $really_not_in_txn) { } 0 0 0
elsif ($really_not_in_txn xor $dbh->{'AutoCommit'}) { } 0 0 0
545 0 $ping_fail = 1;
546 }
547 # check the AC sync-state
548 ▶ elsif ($really_not_in_txn xor $dbh->{AutoCommit}) {
Condition0%0/4
$really_not_in_txn xor $dbh->{"AutoCommit"}
l&&rl&&!r!l&&r!l&&!r
0000
MC/DC0%0/2
$really_not_in_txn xor $dbh->{"AutoCommit"}
$really_not_in_txn $dbh->{"AutoCommit"}
Truth table0%0/4
A xor B
A= $really_not_in_txnB= $dbh->{"AutoCommit"}
ABresult
110
101
011
000
549 carp_unique (sprintf
550 'Internal transaction state of handle %s (apparently %s a transaction) does not seem to '
551 . 'match its AutoCommit attribute setting of %s - this is an indication of a '
552 . 'potentially serious bug in your transaction handling logic',
553 $dbh,
554 $really_not_in_txn ? 'NOT in' : 'in',
555 0 ▶ $dbh->{AutoCommit} ? 'TRUE' : 'FALSE',
Branch: 2 branches
BranchTrueFalseTotal
$really_not_in_txn ? : 0 0 0
$dbh->{'AutoCommit'} ? : 0 0 0
556 );
557  
558 # it is too dangerous to execute anything else in this state
559 # assume everything works (safer - worst case scenario next statement throws)
560 0 return 1;
561 }
562 }
563  
564 # do the actual test and return on no failure
565 1272 ▶ ( $ping_fail ||= ! try { $dbh->do('SELECT * FROM sqlite_master LIMIT 1'); 1 } )
Subroutine __ANON__: called CC=1 SCAR=0.0
566 1272 ▶ or return 1; # the actual RV of _ping()
Branch: 1 branch
BranchTrueFalseTotal
$ping_fail ||= !&try(sub { $dbh->do("SELECT * FROM sqlite_master LIMIT 1"); 1; } ) or return 1 0 1272 1272
Condition33%1/3
$ping_fail ||= !&try(sub { $dbh->do("SELECT * FROM sqlite_master LIMIT 1"); 1; } )
l!l&&r!l&&!r
001272
MC/DC0%0/2
$ping_fail ||= !&try(sub { $dbh->do("SELECT * FROM sqlite_master LIMIT 1"); 1; } )
$ping_fail !&try(sub { $dbh->do("SELECT * FROM sqlite_master LIMIT 1"); 1; } )
Truth table33%1/3
A ||= not(B)
A= $ping_failB= !&try(sub { $dbh->do("SELECT * FROM sqlite_master LIMIT 1"); 1; } )
ABresult
1X1
011
000
567  
568 # ping failed (or so it seems) - need to do some cleanup
569 # it is possible to have a proper "connection", and have "ping" return
570 # false anyway (e.g. corrupted file). In such cases DBD::SQLite still
571 # keeps the actual file handle open. We don't really want this to happen,
572 # so force-close the handle via DBI itself
573 #
574 0 local $@; # so that we do not clobber the real error as set above
575 0 eval { $dbh->disconnect }; # if it fails - it fails
576 0 undef; # the actual RV of _ping()
577 }
578  
579 2480 ▶sub bind_attribute_by_data_type {
Subroutine bind_attribute_by_data_type: called CC=2 SCAR=6.9
Pod documented
580  
581 # According to http://www.sqlite.org/datatype3.html#storageclasses
582 # all numeric types are dynamically allocated up to 8 bytes per
583 # individual value
584 # Thus it should be safe and non-wasteful to bind everything as
585 # SQL_BIGINT and have SQLite deal with storage/comparisons however
586 # it deems correct
587 2480 ▶ $_[1] =~ /^ (?: int(?:[1248]|eger)? | (?:tiny|small|medium|big)int ) $/ix
Branch: 1 branch
BranchTrueFalseTotal
$_[1] =~ /^ (?: int(?:[1248]|eger)? | (?:tiny|small|medium|big)int ) $/xi ? : 760 1720 2480
588 ? DBI::SQL_BIGINT()
589 : undef
590 ;
591 }
592  
593  
594 # The bind attributes of a statement as one string: empty when none of the
595 # placeholders is typed. See _prepare_sth.
596 18384 ▶my $bind_types_key = sub {
Subroutine __ANON__: called CC=6 SCAR=19.3
597 18384 ▶ my $attrs = $_[0] or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $attrs = $_[0] or return "" 18384 0 18384
598  
599 18384 ▶ return '' unless grep { defined } @$attrs;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {defined $_;} @$attrs 1803 16581 18384
600  
601 return join ',', map {
602 16581 my $attr = $_;
603 ! defined $attr ? ''
604 0 ▶ : ref $attr eq 'HASH' ? join(';', map { "$_=" . ($attr->{$_} // '') } sort keys %$attr)
Branch: 2 branches
BranchTrueFalseTotal
!defined($attr) ? : 10612 30877 41489
ref $attr eq 'HASH' ? : 0 30877 30877
Condition0%0/2
$attr->{$_} // ""
l!l
00
MC/DC0%0/1
$attr->{$_} // ""
$attr->{$_}
Truth table0%0/2
A
A= $attr->{$_}
Aresult
11
00
605 : "$attr"
606 } @$attrs;
607 205 };
608  
609 # FIXME - what the flying fuck... work around RT#76395
610 # DBD::SQLite warns on binding >32 bit values with 32 bit IVs
611 10945 ▶sub _dbh_execute {
Subroutine _dbh_execute: called CC=8 SCAR=29.6
612 10945 my $self = $_[0];
613  
614 # see _prepare_sth: the statement this execute prepares is the one for
615 # these bind types
616 10945 local $self->{_sth_bind_types} = $bind_types_key->($_[4]);
617  
618 10945 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (&iv_size() < 8 || &os_name() eq "MSWin32" and not defined $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT) 0 10945 10945
Condition33%2/6
&iv_size() < 8 || &os_name() eq "MSWin32" and not defined $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
!ll&&!rl&&r
1094500
&iv_size() < 8 or &os_name() eq "MSWin32"
l!l&&r!l&&!r
0010945
MC/DC0%0/3
&iv_size() < 8 || &os_name() eq "MSWin32" and not defined $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
&iv_size() < 8 &os_name() eq "MSWin32" not defined $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
Truth table20%1/5
A or B and not(C)
A= &iv_size() < 8B= &os_name() eq "MSWin32"C= not defined $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
ABCresult
00X0
1X00
0100
1X11
0111
619 (
620 iv_size < 8
621 or
622 os_name eq 'MSWin32'
623 )
624 and
625 ! defined $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
626 ) {
627 0 ▶ $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT = (
Branch: 1 branch
BranchTrueFalseTotal
&modver_gt_or_eq('DBD::SQLite', '1.37') ? : 0 0 0
628 modver_gt_or_eq('DBD::SQLite', '1.37')
629 ) ? 1 : 0;
630 }
631  
632 10945 ▶ local $SIG{__WARN__} = sigwarn_silencer( qr/
Branch: 1 branch
BranchTrueFalseTotal
if &iv_size() < 8 || &os_name() eq "MSWin32" and $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT 0 10945 10945
Condition33%2/6
&iv_size() < 8 || &os_name() eq "MSWin32" and $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
!ll&&!rl&&r
1094500
&iv_size() < 8 or &os_name() eq "MSWin32"
l!l&&r!l&&!r
0010945
MC/DC0%0/3
&iv_size() < 8 || &os_name() eq "MSWin32" and $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
&iv_size() < 8 &os_name() eq "MSWin32" $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
Truth table20%1/5
A or B and C
A= &iv_size() < 8B= &os_name() eq "MSWin32"C= $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
ABCresult
00X0
1X00
0100
1X11
0111
633 \Qdatatype mismatch: bind\E \s (?:
634 param \s+ \( \d+ \) \s+ [-+]? \d+ (?: \. 0*)? \Q as integer\E
635 |
636 0 \d+ \s type \s @{[ DBI::SQL_BIGINT() ]} \s as \s [-+]? \d+ (?: \. 0*)?
637 )
638 /x ) if (
639 (
640 iv_size < 8
641 or
642 os_name eq 'MSWin32'
643 )
644 and
645 $DBD::SQLite::__DBIO_CHECK_dbd_mishandles_bound_BIGINT
646 );
647  
648 10945 $self->next::method(@_[1 .. $#_]);
649 }
650  
651 0 ▶sub _dbh_prepare {
Subroutine _dbh_prepare: not called CC=1 SCAR=6.9
652 0 my $self = $_[0];
653  
654 0 local $self->{_sth_bind_types} = $bind_types_key->($_[4]);
655  
656 0 $self->next::method(@_[1 .. $#_]);
657 }
658  
659 # Statements are cached by their SQL text alone (DBI's prepare_cached), and
660 # DBD::SQLite keeps the type a placeholder was last bound with until another
661 # one is given -- sqlite_bind_ph stores a type only when there is one, and no
662 # type code puts a placeholder back to "untyped". So a bind without an
663 # attribute does not get the DBD default (TEXT, or a guess under
664 # sqlite_see_if_its_a_number), it gets what the previous call that shared the
665 # SQL text bound there: '01234' goes out as INTEGER 1234 after a literal 99999
666 # ran through the same statement (karr k61).
667 #
668 # A cached handle is therefore shared only between calls that bind the same
669 # types: the types go into the cache key, as a private attribute of
670 # prepare_cached, which DBI folds into the key and DBD::SQLite ignores. A
671 # call without any bind attribute keeps the plain key, so that handle is one
672 # that no placeholder was ever typed on.
673 25816 ▶sub _prepare_sth {
Subroutine _prepare_sth: called CC=5 SCAR=16.1
674 25816 my ($self, $dbh, $sql) = @_;
675  
676 25816 my $types = $self->{_sth_bind_types};
677  
678 25816 ▶ if (defined $types and length $types and ! $self->disable_sth_caching) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $types and length $types and not $self->disable_sth_caching) 16578 9238 25816
Condition100%6/6
defined $types and length $types and not $self->disable_sth_caching
!ll&&!rl&&r
9235316578
defined $types and length $types
!ll&&!rl&&r
7444179116581
MC/DC100%3/3
defined $types and length $types and not $self->disable_sth_caching
defined $types length $types not $self->disable_sth_caching
Truth table100%4/4
A and B and not(C)
A= defined $typesB= length $typesC= not $self->disable_sth_caching
ABCresult
0XX0
10X0
1100
1111
679 # 3 is the if_active parameter which avoids active sth re-use
680 16578 my $sth = $dbh->prepare_cached($sql, { private_dbio_bind_types => $types }, 3);
681 16575 ▶ return $sth if $sth;
Branch: 1 branch
BranchTrueFalseTotal
if $sth 16575 0 16575
682 # failed: the base class prepares again and reports it
683 }
684  
685 9238 return $self->next::method($dbh, $sql);
686 }
687  
688 # populate: the base class prepares the statement before it knows the bind
689 # attributes (they come with the proto-bind, handed to this method), then
690 # binds the proto-bind once and lets execute_for_fetch inherit the types from
691 # the handle. Swap in the handle for these types before that happens.
692 #
693 # The swap is assigned to $_[2] on purpose: that is the caller's own $sth, so
694 # _insert_bulk hands back the handle that ran, not the one it prepared.
695 7439 ▶sub _dbh_execute_for_fetch {
Subroutine _dbh_execute_for_fetch: called CC=3 SCAR=11.0
696 7439 my ($self, $source, $sth, $proto_bind) = @_[0..3];
697  
698 7439 my $types = $bind_types_key->($self->_dbi_attrs_for_bind($source, $proto_bind));
699  
700 7439 ▶ if (length $types and ! $self->disable_sth_caching) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $types and not $self->disable_sth_caching) 7428 11 7439
Condition66%2/3
length $types and not $self->disable_sth_caching
!ll&&!rl&&r
1107428
MC/DC50%1/2
length $types and not $self->disable_sth_caching
length $types not $self->disable_sth_caching
Truth table66%2/3
A and not(B)
A= length $typesB= not $self->disable_sth_caching
ABresult
0X0
100
111
701 7428 local $self->{_sth_bind_types} = $types;
702 7428 $_[2] = $self->_prepare_sth($sth->{Database}, $sth->{Statement});
703 }
704  
705 7439 $self->next::method(@_[1 .. $#_]);
706 }
707  
708 # True for a plain scalar holding an integer in canonical decimal spelling
709 # that fits SQLite's 64 bit INTEGER: no leading zero, no plus sign, no
710 # whitespace, no '-0', no fraction or exponent. Only such a value survives
711 # being bound as an integer unchanged -- SQLite renders it back to exactly
712 # the string it was given.
713 175 ▶my $is_canonical_integer = sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
714 175 ▶ return 0 if ref $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] 33 142 175
715  
716 142 ▶ my ($sign, $digits) = $_[0] =~ /\A (-?) ( 0 | [1-9][0-9]{0,18} ) \z/x
Branch: 1 branch
BranchTrueFalseTotal
() = $_[0] =~ /\A (-?) ( 0 | [1-9][0-9]{0,18} ) \z/x or return 0 84 58 142
717 or return 0;
718  
719 84 ▶ return 0 if $sign and $digits eq '0';
Branch: 1 branch
BranchTrueFalseTotal
if $sign and $digits eq 0 1 83 84
Condition100%3/3
$sign and $digits eq 0
!ll&&!rl&&r
7581
MC/DC100%2/2
$sign and $digits eq 0
$sign $digits eq 0
Truth table100%3/3
A and B
A= $signB= $digits eq 0
ABresult
0X0
100
111
720  
721 83 ▶ return 1 if length $digits < 19;
Branch: 1 branch
BranchTrueFalseTotal
if length $digits < 19 77 6 83
722  
723 6 ▶ return $digits le ( $sign ? '9223372036854775808' : '9223372036854775807' )
Branch: 2 branches
BranchTrueFalseTotal
$digits le ($sign ? '9223372036854775808' : '9223372036854775807') ? : 4 2 6
$sign ? : 2 4 6
724 ? 1
725 : 0;
726 205 };
727  
728 # DBD::SQLite before 1.37 can not bind an integer occupying more than 32
729 # bits. True when this DBD::SQLite is such a one and the value of the bind is
730 # such an integer: the caller then binds it as a string, and the warning
731 # raised here says so. Hand it a value that is known to be an integer.
732 93 ▶my $warn_integer_too_wide_for_dbd = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
733 93 my ($bind, $i) = @_;
734  
735 93 ▶ return 0 if $DBD::SQLite::__DBIO_CHECK_dbd_can_bind_bigint_values;
Branch: 1 branch
BranchTrueFalseTotal
if $DBD::SQLite::__DBIO_CHECK_dbd_can_bind_bigint_values 69 24 93
736  
737 24 ▶ return 0 unless $bind->[1] > 0x7fff_ffff or $bind->[1] < -0x8000_0000;
Branch: 1 branch
BranchTrueFalseTotal
unless $bind->[1] > 2147483647 or $bind->[1] < '-2147483648' 12 12 24
Condition100%3/3
$bind->[1] > 2147483647 or $bind->[1] < '-2147483648'
l!l&&r!l&&!r
8412
MC/DC100%2/2
$bind->[1] > 2147483647 or $bind->[1] < '-2147483648'
$bind->[1] > 2147483647 $bind->[1] < '-2147483648'
Truth table100%3/3
A or B
A= $bind->[1] > 2147483647B= $bind->[1] < '-2147483648'
ABresult
1X1
011
000
738  
739 carp_unique( sprintf (
740 "An integer value occupying more than 32 bits was supplied for column '%s' "
741 . 'which your version of DBD::SQLite (%s) can not bind properly so DBIO '
742 . 'will treat it as a string instead, consider upgrading to at least '
743 . 'DBD::SQLite version 1.37',
744 12 ▶ $bind->[0]{dbic_colname} || "# $i",
Condition100%2/2
$bind->[0]{'dbic_colname'} || "# $i"
l!l
111
MC/DC100%1/1
$bind->[0]{'dbic_colname'} || "# $i"
$bind->[0]{'dbic_colname'}
Truth table100%2/2
A
A= $bind->[0]{'dbic_colname'}
Aresult
11
00
745 DBD::SQLite->VERSION,
746 ) );
747  
748 12 return 1;
749 205 };
750  
751 # DBD::SQLite (at least up to version 1.31 has a bug where it will
752 # non-fatally numify a string value bound as an integer, resulting
753 # in insertions of '0' into supposed-to-be-numeric fields
754 # Since this can result in severe data inconsistency, remove the
755 # bind attr if such a situation is detected
756 #
757 # FIXME - when a DBD::SQLite version is released that eventually fixes
758 # this situation (somehow) - no-op this override once a proper DBD
759 # version is detected
760 25821 ▶sub _dbi_attrs_for_bind {
Subroutine _dbi_attrs_for_bind: called CC=18 SCAR=28.9
761 25821 my ($self, $ident, $bind) = @_;
762  
763 25821 my $bindattrs = $self->next::method($ident, $bind);
764  
765 25821 ▶ if (! defined $DBD::SQLite::__DBIO_CHECK_dbd_can_bind_bigint_values) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $DBD::SQLite::__DBIO_CHECK_dbd_can_bind_bigint_values) 163 25658 25821
766 163 ▶ $DBD::SQLite::__DBIO_CHECK_dbd_can_bind_bigint_values
Branch: 1 branch
BranchTrueFalseTotal
&modver_gt_or_eq('DBD::SQLite', '1.37') ? : 163 0 163
767 = modver_gt_or_eq('DBD::SQLite', '1.37') ? 1 : 0;
768 }
769  
770 25821 for my $i (0.. $#$bindattrs) {
771  
772 63856 ▶ if (defined $bindattrs->[$i]) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $bindattrs->[$i]) { } 44252 19604 63856
elsif (defined $bind->[$i][1] and not exists $bind->[$i][0]{'dbd_attrs'} and !$bind->[$i][0]{'dbic_colname'} || $bind->[$i][0]{'dbic_colname'} =~ /\(/) { } 181 19493 19674
773 # Validate existing integer bind attributes
774 44252 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bind->[$i][1] and grep {$bindattrs->[$i] eq $_;} &DBI::SQL_INTEGER(), &DBI::SQL_TINYINT(), &DBI::SQL_SMALLINT(), &DBI::SQL_BIGINT()) 43580 672 44252
Condition100%3/3
defined $bind->[$i][1] and grep {$bindattrs->[$i] eq $_;} &DBI::SQL_INTEGER(), &DBI::SQL_TINYINT(), &DBI::SQL_SMALLINT(), &DBI::SQL_BIGINT()
!ll&&!rl&&r
667543580
MC/DC100%2/2
defined $bind->[$i][1] and grep {$bindattrs->[$i] eq $_;} &DBI::SQL_INTEGER(), &DBI::SQL_TINYINT(), &DBI::SQL_SMALLINT(), &DBI::SQL_BIGINT()
defined $bind->[$i][1] grep {$bindattrs->[$i] eq $_;} &DBI::SQL_INTEGER(), &DBI::SQL_TINYINT(), &DBI::SQL_SMALLINT(), &DBI::SQL_BIGINT()
Truth table100%3/3
A and B
A= defined $bind->[$i][1]B= grep {$bindattrs->[$i] eq $_;} &DBI::SQL_INTEGER(), &DBI::SQL_TINYINT(), &DBI::SQL_SMALLINT(), &DBI::SQL_BIGINT()
ABresult
0X0
100
111
775 defined $bind->[$i][1]
776 and
777 174340 grep { $bindattrs->[$i] eq $_ } (
778 DBI::SQL_INTEGER(), DBI::SQL_TINYINT(), DBI::SQL_SMALLINT(), DBI::SQL_BIGINT()
779 )
780 ) {
781 43580 ▶ if ( $bind->[$i][1] !~ /^ [\+\-]? [0-9]+ (?: \. 0* )? $/x ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $bind->[$i][1] =~ /^ [\+\-]? [0-9]+ (?: \. 0* )? $/x) { } 6 43574 43580
elsif (not $DBD::SQLite::__DBIO_CHECK_dbd_can_bind_bigint_values) { } 12 43562 43574
782 carp_unique( sprintf (
783 "Non-integer value supplied for column '%s' despite the integer datatype",
784 6 ▶ $bind->[$i][0]{dbic_colname} || "# $i"
Condition50%1/2
$bind->[$i][0]{'dbic_colname'} || "# $i"
l!l
60
MC/DC0%0/1
$bind->[$i][0]{'dbic_colname'} || "# $i"
$bind->[$i][0]{'dbic_colname'}
Truth table50%1/2
A
A= $bind->[$i][0]{'dbic_colname'}
Aresult
11
00
785 ) );
786 6 undef $bindattrs->[$i];
787 }
788 elsif (
789 ! $DBD::SQLite::__DBIO_CHECK_dbd_can_bind_bigint_values
790 ) {
791 12 ▶ if ( $warn_integer_too_wide_for_dbd->($bind->[$i], $i) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$warn_integer_too_wide_for_dbd($bind->[$i], $i)) { } 6 6 12
792 6 undef $bindattrs->[$i];
793 }
794 else {
795 6 $bindattrs->[$i] = DBI::SQL_INTEGER()
796 }
797 }
798 }
799 }
800 ▶ elsif (
Condition100%9/9
defined $bind->[$i][1] and not exists $bind->[$i][0]{"dbd_attrs"} and !$bind->[$i][0]{"dbic_colname"} || $bind->[$i][0]{"dbic_colname"} =~ /\(/
!ll&&!rl&&r
7019353181
defined $bind->[$i][1] and not exists $bind->[$i][0]{"dbd_attrs"}
!ll&&!rl&&r
67319534
not $bind->[$i][0]{"dbic_colname"} or $bind->[$i][0]{"dbic_colname"} =~ /\(/
l!l&&r!l&&!r
1671419353
MC/DC100%4/4
defined $bind->[$i][1] and not exists $bind->[$i][0]{"dbd_attrs"} and !$bind->[$i][0]{"dbic_colname"} || $bind->[$i][0]{"dbic_colname"} =~ /\(/
defined $bind->[$i][1] not exists $bind->[$i][0]{"dbd_attrs"} not $bind->[$i][0]{"dbic_colname"} $bind->[$i][0]{"dbic_colname"} =~ /\(/
Truth table100%5/5
A and not(B) and not(C) or D
A= defined $bind->[$i][1]B= not exists $bind->[$i][0]{"dbd_attrs"}C= not $bind->[$i][0]{"dbic_colname"}D= $bind->[$i][0]{"dbic_colname"} =~ /\(/
ABCDresult
0XXX0
10XX0
11000
111X1
11011
801 # SQLite binds all parameters as TEXT by default (sqlite3_bind_text).
802 # This causes cross-type comparison failures: INTEGER < TEXT is always
803 # true in SQLite's type sort order, so e.g. COUNT(x) > ? with a text
804 # bind always returns FALSE. Fix by hinting integer values as SQL_INTEGER
805 # when no type info is available.
806 #
807 # Apply to:
808 # - Anonymous binds (no dbic_colname) from literal SQL
809 # - Expression binds (colname contains parens, e.g. 'COUNT(x)')
810 # Do NOT apply to plain column aliases (e.g. 'newest_cd_year') as
811 # these may reference TEXT-typed columns containing numeric strings.
812 # Do NOT touch a bind carrying dbd_attrs, even an undef one: the caller
813 # took the binding over.
814 defined $bind->[$i][1]
815 and
816 ! exists $bind->[$i][0]{dbd_attrs}
817 and
818 (
819 ! $bind->[$i][0]{dbic_colname}
820 or
821 $bind->[$i][0]{dbic_colname} =~ /\(/ # expression (COUNT, MAX, etc.)
822 )
823 ) {
824 # SQL_INTEGER ONLY for a value that is certainly a number: an integer
825 # in canonical spelling, see $is_canonical_integer, on a bind that
826 # states no datatype of its own. Whatever merely looks like a number
827 # ('01234', '+5', ' 5') would reach SQLite respelled and silently stop
828 # matching the TEXT it is compared with. A non-integer is not hinted
829 # either: as SQL_INTEGER DBD::SQLite rejects it with a 'datatype
830 # mismatch' warning and binds TEXT anyway, and as a REAL it would be
831 # respelled just the same ('1.50', '1e3').
832 #
833 # Everything else is stated as text rather than left without an
834 # attribute. Stating it is a decision, not a safeguard against
835 # inheritance: a cached statement is no longer shared with calls that
836 # bind other types (see _prepare_sth), so an attribute-less bind would
837 # get what DBD::SQLite does by default. That default is text, but it
838 # turns into a guess under sqlite_see_if_its_a_number, which an explicit
839 # type switches off for these binds (karr k62).
840 #
841 # An integer this DBD::SQLite can not bind as one is text as well, with
842 # a warning (karr k63). That question comes last: it is asked only of a
843 # value that would have gone out as an integer.
844 $bindattrs->[$i] = (
845 ! $bind->[$i][0]{sqlt_datatype}
846 and
847 181 ▶ $is_canonical_integer->($bind->[$i][1])
Branch: 1 branch
BranchTrueFalseTotal
!$bind->[$i][0]{'sqlt_datatype'} && &$is_canonical_integer($bind->[$i][1]) && !&$warn_integer_too_wide_for_dbd($bind->[$i], $i) ? : 75 106 181
Condition100%6/6
not $bind->[$i][0]{"sqlt_datatype"} and &$is_canonical_integer($bind->[$i][1]) and not &$warn_integer_too_wide_for_dbd($bind->[$i], $i)
!ll&&!rl&&r
100675
not $bind->[$i][0]{"sqlt_datatype"} and &$is_canonical_integer($bind->[$i][1])
!ll&&!rl&&r
69481
MC/DC100%3/3
not $bind->[$i][0]{"sqlt_datatype"} and &$is_canonical_integer($bind->[$i][1]) and not &$warn_integer_too_wide_for_dbd($bind->[$i], $i)
not $bind->[$i][0]{"sqlt_datatype"} &$is_canonical_integer($bind->[$i][1]) not &$warn_integer_too_wide_for_dbd($bind->[$i], $i)
Truth table100%4/4
not(A) and B and not(C)
A= not $bind->[$i][0]{"sqlt_datatype"}B= &$is_canonical_integer($bind->[$i][1])C= not &$warn_integer_too_wide_for_dbd($bind->[$i], $i)
ABCresult
0XX0
10X0
1100
1111
848 and
849 ! $warn_integer_too_wide_for_dbd->($bind->[$i], $i)
850 ) ? DBI::SQL_INTEGER() : DBI::SQL_VARCHAR();
851 }
852  
853 }
854  
855 25821 return $bindattrs;
856 }
857  
858 2 ▶sub with_deferred_fk_checks {
Subroutine with_deferred_fk_checks: called CC=1 SCAR=0.0
Pod documented
859 2 my ($self, $sub) = @_;
860  
861 2 my $txn_scope_guard = $self->txn_scope_guard;
862  
863 2 $self->_do_query('PRAGMA defer_foreign_keys = ON');
864  
865 2 ▶ return preserve_context { $sub->() } after => sub { $txn_scope_guard->commit };
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
866 }
867  
868  
869 80 ▶sub connect_call_use_foreign_keys {
Subroutine connect_call_use_foreign_keys: called CC=1 SCAR=0.0
Pod documented
870 80 my $self = shift;
871  
872 80 $self->_do_query(
873 'PRAGMA foreign_keys = ON'
874 );
875 }
876  
877  
878  
879 205 1;
880  
881 __END__
« blib/lib/DBIO/SQLite/Diff.pm ↑ Summary blib/lib/DBIO/SQLite/Test/Conformance.pm »