blib/lib/Trog/SQLite.pm

filter: Statementstmt 24.7% 44 / 178 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 46.4% 13 / 28 Podpod 100% 11 / 11 totaltotal 22.7% 68 / 299 CC 37 SCAR 33.9
CC
37
Cov
18%
dbh
72.0
bulk_insert
72.0
update
56.0
CRAP 29.6
↑ Summary
1 package Trog::SQLite 0.006;
2  
3 # ABSTRACT: An SQLite handle with its schema applied, its updates run, and its pragmas set
4  
5 1 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use re '/aasx';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 ▶use DBI();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # Named so that a missing driver fails here and not inside DBI->connect.
13 1 ▶use DBD::SQLite(); ## no critic (ProhibitUnusedImports)
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use DBD::SQLite::Constants qw{SQLITE_BUSY SQLITE_LIMIT_VARIABLE_NUMBER};
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use File::Basename();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use File::Find();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use File::Slurper();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use List::Util qw{any};
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use POSIX qw{floor};
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use Sub::Retry qw{retry};
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22  
23 # The handle cache, keyed by database file, and the process it belongs to. A
24 # forked child inherits both, and dbh empties the cache when the process differs.
25 1 my $handles = {};
26 1 my $owner = $$;
27  
28 # How long a statement waits for a lock, in milliseconds, and how long wal
29 # waits between its tries, in seconds.
30 1 our $BUSY_TIMEOUT = 5000;
31 1 our $WAL_DELAY = 0.05;
32  
33 1 my %OPTIONS = ( integrity_check => 1 );
34  
35 0 ▶sub dbh {
Subroutine dbh: not called CC=8 SCAR=42.8
Pod documented
36 0 my ( $schema, $dbname, $options ) = @_;
37 0 ▶ $options //= {};
Condition0%0/2
$options //= {}
l!l
00
MC/DC0%0/1
$options //= {}
$options
Truth table0%0/2
A
A= $options
Aresult
11
00
38 0 ▶ die "The options of dbh must be a HASH reference\n" unless ref $options eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $options eq "HASH" 0 0 0
39 0 my @unknown = grep { !$OPTIONS{$_} } sort keys %$options;
40 0 ▶ die "dbh has no option(s) @unknown\n" if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 0 0 0
41  
42 0 ▶ forget() if $owner != $$;
Branch: 1 branch
BranchTrueFalseTotal
if $owner != $$ 0 0 0
43 0 ▶ return $handles->{$dbname} if $handles->{$dbname};
Branch: 1 branch
BranchTrueFalseTotal
if $handles->{$dbname} 0 0 0
44  
45 # No touch first, because DBD::SQLite creates the file on connect.
46 0 my $db = DBI->connect( "dbi:SQLite:dbname=$dbname", q{}, q{}, { RaiseError => 1, PrintError => 0, AutoInactiveDestroy => 1 } );
47  
48 # Before the schema, because a second process that opens a new database at
49 # the same time must wait for the updates of the first one.
50 0 $db->do("PRAGMA busy_timeout = $BUSY_TIMEOUT");
51  
52 # Before the schema and the journal mode, so that a damaged file is not written to.
53 0 ▶ integrity_check($db) if $options->{integrity_check};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"integrity_check"} 0 0 0
54 0 wal($db);
55 0 $db->do('PRAGMA synchronous = NORMAL');
56  
57 0 ▶ if ($schema) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema) 0 0 0
58 0 apply( $db, $schema );
59 0 update( $db, $schema );
60 }
61  
62 # SQLite ignores this pragma inside a transaction, and an update that
63 # rebuilds a table must not be checked halfway through.
64 0 $db->do('PRAGMA foreign_keys = ON');
65  
66 0 $handles->{$dbname} = $db;
67 0 return $db;
68 }
69  
70  
71 0 ▶sub wal {
Subroutine wal: not called CC=2 SCAR=17.9
Pod documented
72 0 my ($db) = @_;
73  
74 0 my $error;
75 retry(
76 1 + int( $BUSY_TIMEOUT / 1000 / $WAL_DELAY ),
77 $WAL_DELAY,
78 0 ▶ sub { $db->do('PRAGMA journal_mode = WAL') },
Subroutine __ANON__: not called CC=1 SCAR=6.9
79  
80 # retry dies after its last try only with its default retry_if, so this keeps the error.
81 0 ▶ sub { $error = $@; return $error && ( $db->err // 0 ) == SQLITE_BUSY },
Subroutine __ANON__: not called CC=3 SCAR=24.8
Condition0%0/5
$error && ($db->err // 0) == &SQLITE_BUSY()
!ll&&!rl&&r
000
$db->err // 0
l!l
00
MC/DC0%0/2
$error && ($db->err // 0) == &SQLITE_BUSY()
$error $db->err
Truth table0%0/3
A && B
A= $errorB= $db->err
ABresult
0X0
100
111
82 0 );
83 0 ▶ die $error if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 0 0
84 0 return 1;
85 }
86  
87  
88 0 ▶sub integrity_check {
Subroutine integrity_check: not called CC=2 SCAR=17.9
Pod documented
89 0 my ($db) = @_;
90  
91 0 my @problems = map { $_->[0] } @{ $db->selectall_arrayref('PRAGMA integrity_check') };
92 0 ▶ return 1 if "@problems" eq 'ok';
Branch: 1 branch
BranchTrueFalseTotal
if join($", @problems) eq "ok" 0 0 0
93 0 die 'The integrity check of ' . $db->sqlite_db_filename() . " failed:\n" . join( "\n", @problems ) . "\n";
94 }
95  
96  
97 0 ▶sub apply {
Subroutine apply: not called CC=3 SCAR=24.8
Pod documented
98 0 my ( $db, $file ) = @_;
99  
100 # No test first, because read_text dies with the path and the errno.
101 0 my $sql = File::Slurper::read_text($file);
102 0 $db->{sqlite_allow_multiple_statements} = 1;
103 0 my $ok = eval { $db->do($sql); 1 };
104 0 $db->{sqlite_allow_multiple_statements} = 0;
105 0 ▶ die "Could not apply $file: " . ( $@ || $db->errstr ) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
Condition0%0/3
$@ || $db->errstr
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $db->errstr
$@ $db->errstr
Truth table0%0/3
A || B
A= $@B= $db->errstr
ABresult
1X1
011
000
106  
107 0 return 1;
108 }
109  
110  
111 0 ▶sub updates {
Subroutine updates: not called CC=3 SCAR=24.8
Pod documented
112 0 my ($schema) = @_;
113  
114 0 my $dir = File::Basename::dirname($schema);
115 0 my $name = File::Basename::basename( $schema, '.sql' );
116  
117 # The directory of the schema itself, and nothing below it.
118 0 my %path_of;
119 File::Find::find(
120 {
121 no_chdir => 1,
122 0 ▶ wanted => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
123 0 ▶ if ( -d $File::Find::name ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $File::Find::name) 0 0 0
124 0 ▶ $File::Find::prune = 1 unless $File::Find::name eq $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless $File::Find::name eq $dir 0 0 0
125 0 return;
126 }
127 0 my $file = File::Basename::basename($File::Find::name);
128 0 ▶ my ($version) = $file =~ m/\A\Q$name\E[.]v(\d+)[.]update[.]sql\z/ or return;
Branch: 1 branch
BranchTrueFalseTotal
my($version) = $file =~ /\A\Q$name\E[.]v(\d+)[.]update[.]sql\z/aasx or return 0 0 0
129 0 $path_of{$version} = "$dir/$file";
130 },
131 },
132 0 $dir
133 );
134  
135 0 my @versions = sort { $a <=> $b } keys %path_of;
136 0 foreach my $i ( 0 .. $#versions ) {
137 0 my $expected = $i + 1;
138 0 ▶ die "The updates of $schema skip version $expected: the next one is $path_of{ $versions[$i] }\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $versions[$i] == $expected 0 0 0
139 unless $versions[$i] == $expected;
140 }
141  
142 0 return map { [ $_, $path_of{$_} ] } @versions;
143 }
144  
145  
146 0 ▶sub schema_version {
Subroutine schema_version: not called CC=1 SCAR=6.9
Pod documented
147 0 my ($db) = @_;
148  
149 # One row, and the triggers keep it one, so that nothing can record two
150 # versions or none.
151 0 $db->{sqlite_allow_multiple_statements} = 1;
152 0 $db->do(<<'SQL');
153 CREATE TABLE IF NOT EXISTS trog_sqlite_schema_version (version INTEGER NOT NULL DEFAULT 0);
154 CREATE TRIGGER IF NOT EXISTS trog_sqlite_schema_version_one_row
155 BEFORE INSERT ON trog_sqlite_schema_version
156 WHEN (SELECT count(*) FROM trog_sqlite_schema_version) > 0
157 BEGIN SELECT RAISE(ABORT, 'trog_sqlite_schema_version holds one row'); END;
158 CREATE TRIGGER IF NOT EXISTS trog_sqlite_schema_version_kept
159 BEFORE DELETE ON trog_sqlite_schema_version
160 BEGIN SELECT RAISE(ABORT, 'trog_sqlite_schema_version holds one row'); END;
161 INSERT INTO trog_sqlite_schema_version (version)
162 SELECT 0 WHERE NOT EXISTS (SELECT 1 FROM trog_sqlite_schema_version);
163 SQL
164 0 $db->{sqlite_allow_multiple_statements} = 0;
165  
166 0 my ($version) = $db->selectrow_array('SELECT version FROM trog_sqlite_schema_version');
167 0 return $version;
168 }
169  
170  
171 0 ▶sub update {
Subroutine update: not called CC=7 SCAR=40.3
Pod documented
172 0 my ( $db, $schema ) = @_;
173  
174 0 my $version = schema_version($db);
175 0 foreach my $update ( updates($schema) ) {
176 0 my ( $number, $file ) = @$update;
177 0 ▶ next if $number <= $version;
Branch: 1 branch
BranchTrueFalseTotal
if $number <= $version 0 0 0
178  
179 0 $db->do('BEGIN IMMEDIATE');
180 0 my $ok = eval {
181  
182 # Again inside the lock, because another process can have run it
183 # since the read above.
184 0 my ($now) = $db->selectrow_array('SELECT version FROM trog_sqlite_schema_version');
185 0 ▶ if ( $number > $now ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($number > $now) 0 0 0
186 0 apply( $db, $file );
187  
188 0 my $broken = $db->selectall_arrayref('PRAGMA foreign_key_check');
189 0 ▶ die "$file leaves " . scalar(@$broken) . " rows that break a foreign key, in the table $broken->[0][0]\n" if @$broken;
Branch: 1 branch
BranchTrueFalseTotal
if @$broken 0 0 0
190  
191 0 $db->do( 'UPDATE trog_sqlite_schema_version SET version = ?', undef, $number );
192 }
193 0 $db->do('COMMIT');
194 0 1;
195 };
196  
197 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
198 0 ▶ my $err = $@ || "Could not update the schema with $file\n";
Condition0%0/2
$@ || "Could not update the schema with $file\n"
l!l
00
MC/DC0%0/1
$@ || "Could not update the schema with $file\n"
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
199 0 eval { $db->do('ROLLBACK') }; ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval) -- report $err, not a failed rollback after it
200 0 die $err;
201 }
202  
203 0 $version = $number;
204 }
205  
206 0 return $version;
207 }
208  
209  
210 0 ▶sub forget {
Subroutine forget: not called CC=1 SCAR=6.9
Pod documented
211 0 $handles = {};
212 0 $owner = $$;
213 0 return 1;
214 }
215  
216  
217 0 ▶sub transaction {
Subroutine transaction: not called CC=4 SCAR=30.0
Pod documented
218 0 my ( $db, $work ) = @_;
219  
220 # begin_work dies rather than nest.
221 0 ▶ if ( !$db->{AutoCommit} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($db->{"AutoCommit"}) 0 0 0
222 0 $work->();
223 0 return 1;
224 }
225  
226 0 $db->begin_work();
227 0 my $ok = eval { $work->(); $db->commit(); 1 };
228 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
229 0 ▶ my $err = $@ || "The transaction failed\n";
Condition0%0/2
$@ || "The transaction failed\n"
l!l
00
MC/DC0%0/1
$@ || "The transaction failed\n"
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
230 0 eval { $db->rollback() }; ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval) -- report $err, not a failed rollback after it
231 0 die $err;
232 }
233  
234 0 return 1;
235 }
236  
237  
238 0 ▶sub do_with_update_hook {
Subroutine do_with_update_hook: not called CC=3 SCAR=24.8
Pod documented
239 0 my ( $db, $hook, $sql, @bind ) = @_;
240  
241 0 my $was = $db->sqlite_update_hook($hook);
242 0 my $result;
243 0 my $ok = eval { $result = $db->do( $sql, undef, @bind ); 1 };
244 0 ▶ my $err = $@ || "The statement failed\n";
Condition0%0/2
$@ || "The statement failed\n"
l!l
00
MC/DC0%0/1
$@ || "The statement failed\n"
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
245 0 $db->sqlite_update_hook($was);
246 0 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
247  
248 0 return $result;
249 }
250  
251  
252 0 ▶sub bulk_insert {
Subroutine bulk_insert: not called CC=8 SCAR=42.8
Pod documented
253 0 my ( $db, $table, $keys, $action, @values ) = @_;
254 0 ▶ $action //= 'IGNORE';
Condition0%0/2
$action //= "IGNORE"
l!l
00
MC/DC0%0/1
$action //= "IGNORE"
$action
Truth table0%0/2
A
A= $action
Aresult
11
00
255  
256 0 ▶ die "unsupported insert action $action\n" unless any { $action eq $_ } qw{ROLLBACK ABORT FAIL IGNORE REPLACE};
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless &any(sub { $action eq $_; } , "ROLLBACK", "ABORT", "FAIL", "IGNORE", "REPLACE") 0 0 0
257 0 ▶ die "keys must be a nonempty ARRAYREF\n" unless ref $keys eq 'ARRAY' && @$keys;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $keys eq "ARRAY" and @$keys 0 0 0
Condition0%0/3
ref $keys eq "ARRAY" and @$keys
!ll&&!rl&&r
000
MC/DC0%0/2
ref $keys eq "ARRAY" and @$keys
ref $keys eq "ARRAY" @$keys
Truth table0%0/3
A and B
A= ref $keys eq "ARRAY"B= @$keys
ABresult
0X0
100
111
258 0 ▶ die "the number of values must be a multiple of the number of keys\n" if @values % @$keys;
Branch: 1 branch
BranchTrueFalseTotal
if @values % @$keys 0 0 0
259  
260 0 my $width = @$keys;
261 0 my $limit = floor( $db->sqlite_limit(SQLITE_LIMIT_VARIABLE_NUMBER) / $width ) * $width;
262  
263 # Identifiers quoted, and the action checked against its list above.
264 0 my $insert = "INSERT OR $action INTO " . $db->quote_identifier($table) . ' (' . join( ',', map { $db->quote_identifier($_) } @$keys ) . ') VALUES '; ## no critic (ValuesAndExpressions::PreventSQLInjection) -- quoted identifiers, and an action from a fixed list
265 0 my $tuple = '(' . join( ',', ('?') x $width ) . ')';
266  
267 0 my ( $statement, $prepared_for ) = ( undef, 0 );
268 0 ▶ while (@values) {
Branch: 1 branch
BranchTrueFalseTotal
if (@values) 0 0 0
269 0 my @params = splice( @values, 0, $limit );
270 0 my $rows = @params / $width;
271  
272 # The last batch is shorter, and needs a statement of its own size.
273 0 ▶ ( $statement, $prepared_for ) = ( $db->prepare( $insert . join( ',', ($tuple) x $rows ) ), $rows ) unless $prepared_for == $rows;
Branch: 1 branch
BranchTrueFalseTotal
unless $prepared_for == $rows 0 0 0
274 0 $statement->execute(@params);
275 }
276  
277 0 return 1;
278 }
279  
280 1 1;
281  
282 __END__
↑ Summary