lib/App/Standby/DB.pm

filter: Statementstmt 77.9% 85 / 109 Branchbran 53.1% 17 / 32 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 88.2% 15 / 17 Podpod 100% 6 / 6 totaltotal 75.0% 123 / 164 CC 17 SCAR 17.0
CC
17
Cov
72%
_check_db_version
11.3
_check_tables
8.5
prepexec
3.9
CRAP 5.5
« lib/App/Standby/Service/HTTP.pm ↑ Summary lib/App/Standby.pm »
1 package App::Standby::DB;
2 4 $App::Standby::DB::VERSION = '0.04';
3 4 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 $App::Standby::DB::AUTHORITY = 'cpan:TEX';
5 }
6 # ABSTRACT: Database abstraction/helper for App::Standby
7  
8 4 ▶use 5.010_000;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use mro 'c3';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use feature ':5.10';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 4 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 # use IO::Handle;
16 # use autodie;
17 # use MooseX::Params::Validate;
18 # use Carp;
19 # use English qw( -no_match_vars );
20 # use Try::Tiny;
21 4 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 # extends ...
24 # has ...
25 4 has 'dbh' => (
26 'is' => 'rw',
27 'isa' => 'DBI::db',
28 'lazy' => 1,
29 'builder' => '_init_dbh',
30 );
31 # with ...
32 4 with qw(Config::Yak::RequiredConfig Log::Tree::RequiredLogger);
33 # initializers ...
34 3 ▶sub _init_dbh {
Subroutine _init_dbh: called CC=2 SCAR=7.0
35 3 my $self = shift;
36  
37 3 my $db_file = $self->config()->get('App::Standby::DBFile', { Default => '/var/lib/standby-mgm/db.sqlite3'});
38  
39 3 my $dsn = 'DBI:SQLite:dbname='.$db_file;
40  
41 # see http://search.cpan.org/~adamk/DBD-SQLite-1.35/lib/DBD/SQLite.pm#Transaction_and_Database_Locking
42 3 my $dbh = DBI->connect($dsn, '', '', { sqlite_use_immediate_transaction => 1, });
43  
44 3 ▶ if($dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh) 3 0 3
45 3 $self->_check_tables($dbh);
46 }
47  
48 3 return $dbh;
49 }
50  
51  
52 3 ▶sub DEMOLISH {
Subroutine DEMOLISH: called CC=1 SCAR=0.0
Pod documented
53 3 my $self = shift;
54  
55 3 $self->dbh()->disconnect();
56  
57 3 return;
58 }
59  
60 # your code here ...
61 30 ▶sub prepare {
Subroutine prepare: called CC=1 SCAR=0.0
Pod documented
62 30 my $self = shift;
63 30 my $sqlstr = shift;
64  
65 30 return $self->dbh()->prepare($sqlstr);
66 }
67  
68  
69 7 ▶sub prepexec {
Subroutine prepexec: called CC=3 SCAR=13.6
Pod documented
70 7 my ( $self, $sqlstr, @params ) = @_;
71  
72 7 my $sth = $self->dbh()->prepare($sqlstr);
73  
74 7 ▶ if(!$sth) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 7 7
75 0 $self->logger()->log( message => 'Failed to prepare statement from SQL: '.$sqlstr.' w/ error: '.$self->dbh()->errstr, level => 'warning', );
76 0 return;
77 }
78 7 ▶ if($sth->execute(@params)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->execute(@params)) { } 7 0 7
79 7 return $sth;
80 } else {
81 0 $self->logger()->log( message => 'Failed to execute statement w/ error: '.$sth->errstr, level => 'warning', );
82 0 return;
83 }
84 }
85  
86  
87 0 ▶sub do {
Subroutine do: not called CC=1 SCAR=6.9
Pod documented
88 0 my $self = shift;
89  
90 0 return $self->dbh()->do(@_);
91 }
92  
93  
94 1 ▶sub last_insert_id {
Subroutine last_insert_id: called CC=1 SCAR=0.0
Pod documented
95 1 my $self = shift;
96  
97 1 return $self->dbh()->last_insert_id(@_);
98 }
99  
100  
101 0 ▶sub errstr {
Subroutine errstr: not called CC=1 SCAR=6.9
Pod documented
102 0 my $self = shift;
103 0 return $self->dbh()->errstr();
104 }
105  
106 3 ▶sub _check_tables {
Subroutine _check_tables: called CC=7 SCAR=21.5
107 3 my $self = shift;
108 3 my $dbh = shift;
109  
110 # TODO LOW handle corrupted DB somehow
111 # see http://www.sqlite.org/faq.html#q21 for possible approaches
112  
113 # TODO LOW add log table to record changes for some time
114 # see http://www.sqlite.org/pragma.html#pragma_auto_vacuum for keeping the
115 # disk usage low
116  
117 3 my $sql_meta = <<EOS;
118 CREATE TABLE IF NOT EXISTS meta (
119 key TEXT,
120 value TEXT,
121 CONSTRAINT ukey UNIQUE (key) ON CONFLICT ABORT
122 );
123 EOS
124 3 ▶ if($dbh->do($sql_meta)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->do($sql_meta)) { } 3 0 3
125 #$self->logger()->log( message => 'Table meta OK', level => 'debug', );
126 } else {
127 0 $self->logger()->log( message => 'Failed to create table meta: '.$dbh->errstr, level => 'error', );
128 }
129  
130 3 my $sql_config = <<EOS;
131 CREATE TABLE IF NOT EXISTS config (
132 id INTEGER PRIMARY KEY ASC,
133 key TEXT,
134 value TEXT,
135 group_id INTEGER,
136 CONSTRAINT fk_gid FOREIGN KEY (group_id) REFERENCES groups (id) ON DELETE CASCADE
137 );
138 EOS
139 3 ▶ if($dbh->do($sql_config)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->do($sql_config)) { } 3 0 3
140 #$self->logger()->log( message => 'Table config OK', level => 'debug', );
141 } else {
142 0 $self->logger()->log( message => 'Failed to create table config: '.$dbh->errstr, level => 'error', );
143 }
144  
145 3 my $sql_config_contacts = <<EOS;
146 CREATE TABLE IF NOT EXISTS config_contacts (
147 id INTEGER PRIMARY KEY ASC,
148 key TEXT,
149 value TEXT,
150 contact_id INTEGER,
151 CONSTRAINT fk_cid FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE
152 );
153 EOS
154 3 ▶ if($dbh->do($sql_config_contacts)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->do($sql_config_contacts)) { } 3 0 3
155 #$self->logger()->log( message => 'Table config OK', level => 'debug', );
156 } else {
157 0 $self->logger()->log( message => 'Failed to create table config_contacts: '.$dbh->errstr, level => 'error', );
158 }
159  
160 # check that all required tables exist and create them if they don't
161 3 my $sql_groups = <<EOS;
162 CREATE TABLE IF NOT EXISTS groups (
163 id INTEGER PRIMARY KEY ASC,
164 name TEXT,
165 key TEXT
166 );
167 EOS
168  
169 3 ▶ if($dbh->do($sql_groups)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->do($sql_groups)) { } 3 0 3
170 #$self->logger()->log( message => 'Table groups OK', level => 'debug', );
171 } else {
172 0 $self->logger()->log( message => 'Failed to create table groups: '.$dbh->errstr, level => 'error', );
173 }
174  
175 3 my $sql_group_services = <<EOS;
176 CREATE TABLE IF NOT EXISTS group_services (
177 id INTEGER PRIMARY KEY ASC,
178 group_id INTEGER,
179 name TEXT,
180 desc TEXT,
181 class TEXT,
182 CONSTRAINT fk_gid FOREIGN KEY (group_id) REFERENCES groups (id) ON DELETE CASCADE,
183 CONSTRAINT uq_name UNIQUE (group_id,name)
184 );
185 EOS
186  
187 3 ▶ if($dbh->do($sql_group_services)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->do($sql_group_services)) { } 3 0 3
188 #$self->logger()->log( message => 'Table groups OK', level => 'debug', );
189 } else {
190 0 $self->logger()->log( message => 'Failed to create table group_services: '.$dbh->errstr, level => 'error', );
191 }
192  
193 3 my $sql_ctcs = <<EOS;
194 CREATE TABLE IF NOT EXISTS contacts (
195 id INTEGER PRIMARY KEY ASC,
196 name TEXT,
197 cellphone TEXT,
198 group_id INTEGER,
199 is_enabled INTEGER,
200 ordinal INTEGER,
201 CONSTRAINT fk_gid FOREIGN KEY (group_id) REFERENCES groups (id) ON DELETE CASCADE
202 );
203 EOS
204  
205 3 ▶ if($dbh->do($sql_ctcs)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dbh->do($sql_ctcs)) { } 3 0 3
206 #$self->logger()->log( message => 'Table contacts OK', level => 'debug', );
207 } else {
208 0 $self->logger()->log( message => 'Failed to create table contacts: '.$dbh->errstr, level => 'error', );
209 }
210  
211 3 my $sql_log = <<EOS;
212 CREATE TABLE IF NOT EXISTS log (
213 id INTEGER PRIMARY KEY ASC,
214 group_id INTEGER,
215 remote_addr INTEGER,
216 msg TEXT,
217 );
218 EOS
219  
220 #if($dbh->do($sql_log)) {
221 # #$self->logger()->log( message => 'Table log OK', level => 'debug', );
222 #} else {
223 # $self->logger()->log( message => 'Failed to create table log: '.$dbh->errstr, level => 'error', );
224 #}
225  
226 3 my $sql_sstats = <<EOS;
227 CREATE TABLE IF NOT EXISTS shift_stats (
228 id INTEGER PRIMARY KEY ASC,
229 contact_id INTEGER,
230 num_shifts INTEGER,
231 CONSTRAINT fk_cid FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE
232 );
233 EOS
234  
235 #if($dbh->do($sql_sstats)) {
236 # #$self->logger()->log( message => 'Table shift_stats OK', level => 'debug', );
237 #} else {
238 # $self->logger()->log( message => 'Failed to create table shift_stats: '.$dbh->errstr, level => 'error', );
239 #}
240  
241 # SQLite honors FK constraints only if the are explicitly turned on ...
242 # http://www.sqlite.org/foreignkeys.html#fk_enable
243 3 $dbh->do('PRAGMA foreign_keys = ON;');
244  
245 # Speed up a bit, if we encounter a crash we have more to worry about than
246 # just a messed up spooler queue ...
247 # http://www.sqlite.org/pragma.html#pragma_synchronous
248 3 $dbh->do('PRAGMA synchronous = OFF;');
249  
250 3 $self->_check_db_version($dbh);
251  
252 3 return 1;
253 }
254  
255 3 ▶sub _check_db_version {
Subroutine _check_db_version: called CC=8 SCAR=24.2
256 3 my $self = shift;
257 3 my $dbh = shift;
258  
259 3 $dbh->do('BEGIN TRANSACTION');
260  
261 3 my $db_version = 0; # set default
262 3 my $sql = 'SELECT value FROM meta WHERE `key` = ?';
263 3 my $sth = $dbh->prepare($sql);
264 3 ▶ if($sth) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth) { } 3 0 3
265 3 ▶ if($sth->execute('version')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->execute('version')) { } 3 0 3
266 3 $db_version = $sth->fetchrow_array();
267 } else {
268 0 $self->logger()->log( message => 'Failed to execute statement w/ error: '.$sth->errstr, level => 'warning', );
269 }
270 3 $sth->finish();
271 } else {
272 0 $self->logger()->log( message => 'Failed to prepare statement from SQL: '.$sql.' w/ error: '.$dbh->errstr, level => 'warning', );
273 }
274  
275 # place any version independent statements here
276  
277 # place any version dependent statements inside
278 3 ▶ if(defined($db_version)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $db_version) 1 2 3
279 1 ▶ if($db_version < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db_version < 2) 0 1 1
280 # do upgrades to version 2 here
281 # remove column class from table groups
282 0 my $sql = <<EOS;
283 BEGIN TRANSACTION;
284 CREATE TEMPORARY TABLE groups_backup(id,name);
285 DROP TABLE groups;
286 CREATE TABLE IF NOT EXISTS groups (
287 id INTEGER PRIMARY KEY ASC,
288 name TEXT
289 );
290 INSERT INTO groups SELECT id,name FROM groups_backup;
291 DROP TABLE groups_backup;
292 COMMIT;
293 EOS
294 # TODO HIGH do multi-statements work es expected?
295 0 $dbh->do($sql);
296 }
297 1 ▶ if($db_version < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db_version < 3) 0 1 1
298 0 my $sql = 'ALTER TABLE groups ADD COLOUMN key TEXT';
299 0 $dbh->do($sql);
300 }
301 1 ▶ if($db_version < 4) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db_version < 4) 0 1 1
302 0 my $sql = 'DROP TABLE notify_order';
303 0 $dbh->do($sql);
304 }
305 1 ▶ if($db_version < 5) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db_version < 5) 0 1 1
306 # remove column class from table contacts
307 0 my $sql = <<EOS;
308 BEGIN TRANSACTION;
309 CREATE TEMPORARY TABLE contacts_backup(id,name,cellphone,group_id,is_enabled,ordinal);
310 DROP TABLE contacts;
311 CREATE TABLE IF NOT EXISTS contacts (
312 id INTEGER PRIMARY KEY ASC,
313 name TEXT,
314 cellphone TEXT,
315 group_id INTEGER,
316 is_enabled INTEGER,
317 ordinal INTEGER,
318 CONSTRAINT fk_gid FOREIGN KEY (group_id) REFERENCES groups (id) ON DELETE CASCADE
319 );
320 INSERT INTO contacts SELECT id,name,cellphone,group_id,is_enabled,ordinal FROM contacts_backup;
321 DROP TABLE contacts_backup;
322 COMMIT;
323 EOS
324 # TODO HIGH do multi-statements work es expected?
325 0 $dbh->do($sql);
326 }
327 }
328  
329 # finally we set the current version which we've reached by upgrading (or not)
330 3 $sql = "INSERT OR REPLACE INTO meta ('key','value') VALUES('version',5);";
331 3 $dbh->do($sql);
332  
333 3 $dbh->do('COMMIT');
334 3 return 1;
335 }
336  
337 4 ▶no Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
338 4 __PACKAGE__->meta->make_immutable;
339  
340 4 1;
341  
342 __END__
343  
344 =pod
345  
346 =encoding utf-8
347  
348 =head1 NAME
349  
350 App::Standby::DB - Database abstraction/helper for App::Standby
351  
352 =head1 METHODS
353  
354 =head2 DEMOLISH
355  
356 Disconnect from the DB.
357  
358 =head2 prepare
359  
360 Call prepare on the internal DBI object. Will return an DBI statement.
361  
362 =head2 prepexec
363  
364 Prepare an SQL statement and execute it right away. Return
365 the statement object.
366  
367 =head2 do
368  
369 See DBI::do
370  
371 =head2 last_insert_id
372  
373 See DBI::last_insert_id
374  
375 =head2 errstr
376  
377 See DBI::errstr
378  
379 =head1 NAME
380  
381 App::Standby::DB - Database abstraction/helper for App::Standby
382  
383 =head1 AUTHOR
384  
385 Dominik Schulz <dominik.schulz@gauner.org>
386  
387 =head1 COPYRIGHT AND LICENSE
388  
389 This software is copyright (c) 2012 by Dominik Schulz.
390  
391 This is free software; you can redistribute it and/or modify it under
392 the same terms as the Perl 5 programming language system itself.
393  
394 =cut
« lib/App/Standby/Service/HTTP.pm ↑ Summary lib/App/Standby.pm »