lib/Smolder/DB.pm

filter: Statementstmt 18.8% 25 / 133 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 39.1% 9 / 23 Podpod n/a totaltotal 16.8% 34 / 202 CC 25 SCAR 36.2
CC
25
Cov
14%
dump_database
110.0
run_sql_file
42.0
create_database
42.0
CRAP 37.2
« blib/lib/Smolder/DB/SmokeReport.pm ↑ Summary lib/Smolder/Build.pm »
1 package Smolder::DB;
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use base 'Class::DBI::SQLite';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Smolder::Conf qw(SQLDir DataDir);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Class::DBI::Plugin::RetrieveAll;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use File::Spec::Functions qw(catfile);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use DateTime::Format::Strptime;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 __PACKAGE__->connection(
12 "dbi:SQLite:dbname=" . __PACKAGE__->db_file(),
13 '', '',
14 {
15 RaiseError => 1,
16 PrintError => 0,
17 Warn => 0,
18 PrintWarn => 0,
19 AutoCommit => 1,
20 FetchHashKeyName => 'NAME_lc',
21 ShowErrorStatement => 1,
22 ChopBlanks => 1,
23 RootClass => 'DBIx::ContextualFetch',
24 }
25 );
26  
27 =head1 NAME
28  
29 Smolder::DB
30  
31 Database connections and Object-Relational-Mapper methods
32  
33 =head1 SYNOPSIS
34  
35 In your subclass,
36  
37 use base 'Smolder::DB';
38  
39 and now you have Class::DBI::mysql methods ready for use.
40  
41 my $obj = Smolder::DB::Class->new;
42  
43 =head1 DESCRIPTION
44  
45 This class provides a single place for handling all of the database connections in Smolder.
46 It is a subclass of L<Class::DBI::mysql> and provides a base class
47 for object persistence using Class::DBI.
48  
49 It also provides a connect() method for getting a DBI connection from non Class::DBI code.
50  
51 =head1 INTERFACE
52  
53 =head2 dbh
54  
55 Get the database handle.
56  
57 =cut
58  
59 0 ▶sub dbh {
Subroutine dbh: not called CC=1 SCAR=6.9
60 0 return shift->db_Main;
61 }
62  
63 =head2 commit
64  
65 Commit the current transaction
66  
67 =cut
68  
69 0 ▶sub commit {
Subroutine commit: not called CC=1 SCAR=6.9
70 0 shift->db_Main->commit();
71 }
72  
73 =head2 rollback
74  
75 Rollback to the last C<commit>
76  
77 =cut
78  
79 0 ▶sub dbi_rollback {
Subroutine dbi_rollback: not called CC=1 SCAR=6.9
80 0 shift->db_Main->rollback();
81 }
82  
83 =head2 disconnect
84  
85 Disconnects the current database handle stored in db_Main.
86  
87 =cut
88  
89 0 ▶sub disconnect {
Subroutine disconnect: not called CC=1 SCAR=6.9
90 0 return shift->db_Main->disconnect;
91 }
92  
93 =head2 vars
94  
95 Object method that returns a hash where the keys are the names of the
96 columns and the values are the current values of those columns.
97  
98 =cut
99  
100 0 ▶sub vars {
Subroutine vars: not called CC=1 SCAR=6.9
101 0 my $self = shift;
102 0 my %vars = map { $_ => $self->get($_) } ($self->columns);
103 0 return %vars;
104 }
105  
106 =head2 enum_values
107  
108 Returns an arrayref containing the different values that an emum column can hold.
109 If used as a method on a subclass then it will use that class to determine which
110 table to use. Else, if called on the L<Smolder::DB> base class, it will accept
111 2 arguments, the first being the table to use.
112  
113 my $values = Smolder::DB::Foo->enum_values('some_column');
114  
115 my $values = Smolder::DB->enum_values('table', 'some_column');
116  
117 =cut
118  
119 # SQLite doesn't support enums, so we just have to maintain this table
120 my %ENUMS = (
121 preference => {
122 email_type => [qw(full summary link)],
123 email_freq => [qw(on_new on_fail never)],
124 },
125 project => {graph_start => [qw(project year month week day)],},
126 smoke_report => {format => [qw(XML YAML)],},
127 );
128  
129 0 ▶sub enum_values {
Subroutine enum_values: not called CC=4 SCAR=30.0
130 0 my $self = shift;
131 0 my ($table, $column);
132  
133 0 ▶ if (ref $self || $self ne __PACKAGE__) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self or $self ne __PACKAGE__) { } 0 0 0
Condition0%0/3
ref $self or $self ne __PACKAGE__
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $self or $self ne __PACKAGE__
ref $self $self ne __PACKAGE__
Truth table0%0/3
A or B
A= ref $selfB= $self ne __PACKAGE__
ABresult
1X1
011
000
134 0 $table = $self->table();
135 } else {
136 0 $table = shift;
137 }
138 0 $column = shift;
139 0 ▶ return $ENUMS{$table}->{$column} || [];
Condition0%0/2
$ENUMS{$table}{$column} || []
l!l
00
MC/DC0%0/1
$ENUMS{$table}{$column} || []
$ENUMS{$table}{$column}
Truth table0%0/2
A
A= $ENUMS{$table}{$column}
Aresult
11
00
140 }
141  
142 =head2 column_values
143  
144 Returns an array ref of all the unique values in a table's column
145 This must be used in a sub class (it's an abstract method).
146  
147 my $values = Smolder::DB::Foo->column_values($column);
148  
149 May also be passed a second optional argument which will be used to
150 limit the values returned to those that start with the given string.
151  
152 For example, to retrieve all of the values for a given C<$column> that
153 begin with the letter 's':
154  
155 my $values = Smolder::DB::Foo->column_values($column, 's');
156  
157 =cut
158  
159 0 ▶sub column_values {
Subroutine column_values: not called CC=3 SCAR=24.8
160 0 my ($self, $column, $substr) = @_;
161 0 my $table = $self->table();
162 0 my $sql = qq(
163 SELECT DISTINCT $column FROM $table WHERE $column IS NOT NULL
164 AND $column != ''
165 );
166 0 my @bind_cols = ();
167  
168 # add the substring clause if we need to
169 0 ▶ if ($substr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($substr) 0 0 0
170 0 $substr .= '%';
171 0 $sql .= " AND $column LIKE ? ";
172 0 push(@bind_cols, $substr);
173 }
174  
175 0 my $sth = Smolder::DB->db_Main()->prepare_cached($sql);
176 0 $sth->execute(@bind_cols);
177 0 my @values;
178 0 ▶ while (my $row = $sth->fetchrow_arrayref()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_arrayref) 0 0 0
179 0 push(@values, $row->[0]);
180 }
181 0 return \@values;
182 }
183  
184 =head2 refresh
185  
186 TODO
187 CURRENT DOES NOT WORK!!!!
188  
189 This object method will through away the object in memory and re-fetch
190 it from the database. This is useful when changes could be made in the db
191 in another thread (such as testing) and you want to make sure the object is
192 current.
193  
194 =cut
195  
196 # TODO - make this work
197 0 ▶sub refresh {
Subroutine refresh: not called CC=1 SCAR=6.9
198 0 my $self = shift;
199 0 $self->remove_from_object_index();
200 0 my $class = ref $self;
201 0 my $id = $self->id;
202 0 $self = undef;
203 0 $self = $class->retrieve($id);
204 0 return $self;
205 }
206  
207 =head2 retrieve_all_sorted_by($column_name)
208  
209 This object methed is exported from L<Class::DBI::Plugin::RetrieveAll>. It takes
210 a name of the data field that you wish to sort by. Otherwise it works
211 like a normal Class::DBI retrieve_all. Please see L<Class::DBI::Plugin::RetrieveAll>
212 or more details.
213  
214 =head2 retrieve_all_sort_field($column_name)
215  
216 This object method changes the default retrieve_all() in the Class to be
217 auto-sorted by the specified column. Please see
218 L<Class::DBI::Plugin::RetrieveAll> for more details.
219  
220  
221 =head2 db_file
222  
223 Returns the full path to the SQLite DB file.
224  
225 =cut
226  
227 1 ▶sub db_file {
Subroutine db_file: called CC=1 SCAR=0.0
228 1 return catfile(DataDir, "smolder.sqlite");
229 }
230  
231 =head2 run_sql_file
232  
233 Given the runs the SQL contained in the file against out SQLite DB
234  
235 Smolder::DB->run_sql_file('/usr/local/smolder/foo.sql');
236  
237 =cut
238  
239 0 ▶sub run_sql_file {
Subroutine run_sql_file: not called CC=6 SCAR=37.4
240 0 my ($class, $file) = @_;
241 0 ▶ open(my $IN, '<', $file) or die "Could not open file '$file' for reading: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $IN, "<", $file or die "Could not open file '${file}' for reading: $!" 0 0 0
242  
243 0 require Smolder::DB;
244 0 my $dbh = Smolder::DB->db_Main();
245  
246 0 my $sql = '';
247  
248 # read each line
249 0 ▶ while (my $line = <$IN>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $IN)) 0 0 0
250  
251 # skip comments
252 0 ▶ next if ($line =~ /^--/);
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^--/ 0 0 0
253 0 $sql .= $line;
254  
255 # if we have a ';' at the end of the line then it should
256 # be the end of the statement
257 0 ▶ if ($line =~ /;\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /;\s*$/) 0 0 0
258 0 ▶ $dbh->do($sql)
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do($sql) or die "Could not execute SQL '${sql}': $!" 0 0 0
259 or die "Could not execute SQL '$sql': $!";
260 0 $sql = '';
261 }
262 }
263  
264 0 close($file);
265 }
266  
267 =head2 dump_database
268  
269 Given the filename of where to put the dump, this method will create the SQL necessary
270 to restore the database to it's present state including all schema creationg statements.
271  
272 Smolder::DB->dump_database('/usr/local/smolder/dump.sql');
273  
274 =cut
275  
276 0 ▶sub dump_database {
Subroutine dump_database: not called CC=10 SCAR=47.0
277 0 my ($class, $file) = @_;
278  
279 # open the file we want to print to
280 0 ▶ open(my $OUT, '>', $file)
Branch: 1 branch
BranchTrueFalseTotal
open my $OUT, ">", $file or die "Could not open file '${file}' for writing: $!" 0 0 0
281 or die "Could not open file '$file' for writing: $!";
282  
283 # get the list of tables
284 0 require Smolder::DB;
285 0 my $dbh = Smolder::DB->db_Main();
286 0 my $sth = $dbh->prepare(
287 q(
288 SELECT name FROM sqlite_master WHERE type = 'table'
289 AND name NOT LIKE 'sqlite_%' AND sql NOT NULL
290 )
291 );
292 0 $sth->execute();
293 0 my (@tables, $table);
294 0 $sth->bind_col(1, \$table);
295  
296 0 ▶ while ($sth->fetch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->fetch) 0 0 0
297 0 push(@tables, $table);
298 }
299 0 $sth->finish();
300  
301 # now get the SQL for each table and output it
302 0 foreach my $t (@tables) {
303  
304 # first the schema
305 0 $sth = $dbh->prepare(
306 q(
307 SELECT sql FROM sqlite_master
308 WHERE type = 'table' AND name = ?
309 )
310 );
311 0 $sth->execute($t);
312 0 my $sql;
313 0 $sth->bind_col(1, \$sql);
314 0 ▶ while ($sth->fetch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->fetch) 0 0 0
315 0 print $OUT "$sql;\n";
316 }
317 0 $sth->finish();
318  
319 # now the indexes
320 0 $sth = $dbh->prepare(
321 q(
322 SELECT sql FROM sqlite_master
323 WHERE type = 'index' AND tbl_name = ?
324 )
325 );
326 0 $sth->execute($t);
327 0 $sth->bind_col(1, \$sql);
328 0 ▶ while ($sth->fetch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sth->fetch) 0 0 0
329 0 ▶ print $OUT "$sql;\n" if ($sql);
Branch: 1 branch
BranchTrueFalseTotal
if $sql 0 0 0
330 }
331 0 $sth->finish();
332 0 print $OUT "\n\n";
333  
334 # now get all of the data in this table
335 0 $sth = $dbh->prepare(qq(SELECT * FROM $t));
336 0 $sth->execute();
337 0 ▶ while (my $row = $sth->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_arrayref) 0 0 0
338  
339 # massage each value so we can create the SQL
340 0 my @values;
341 0 foreach my $value (@$row) {
342  
343 # NULLs
344 0 ▶ if (!defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value) { } 0 0 0
345 0 $value = 'NULL';
346  
347 # escape and quote it
348 } else {
349 0 $value =~ s/"/\\"/g;
350 0 $value = qq("$value");
351 }
352 0 push(@values, $value);
353 }
354  
355 # create the SQL
356 0 my $sql = "INSERT INTO $t VALUES (" . join(', ', @values) . ");\n";
357 0 print $OUT $sql;
358 }
359  
360 0 print $OUT "\n\n";
361 }
362 0 close($OUT);
363 }
364  
365 =head2 create_database
366  
367 This method will create a brand new, completely empty database file for Smolder.
368  
369 Smolder::DB->create_database();
370  
371 =cut
372  
373 0 ▶sub create_database {
Subroutine create_database: not called CC=6 SCAR=37.4
374 0 my $class = shift;
375 0 my $file = $class->db_file();
376  
377 # create a new file by this name whether it exists or not
378 0 ▶ open(FH, '>', $file) or die "Could not open file '$file' for writing: $!";
Branch: 1 branch
BranchTrueFalseTotal
open FH, ">", $file or die "Could not open file '${file}' for writing: $!" 0 0 0
379 0 ▶ close(FH) or die "Could not close file '$file': $!";
Branch: 1 branch
BranchTrueFalseTotal
close FH or die "Could not close file '${file}': $!" 0 0 0
380  
381 0 my @files = glob(catfile(SQLDir, '*.sql'));
382 0 foreach my $f (@files) {
383 0 eval { $class->run_sql_file($f) };
384 0 ▶ die "Couldn't load SQL file $f! $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
385 }
386  
387 # Set the db_version
388 0 my $version = $Smolder::VERSION;
389 0 my $dbh = $class->db_Main;
390 0 eval { $dbh->do("UPDATE db_version set db_version=$version") };
391 0 ▶ die "Could not update db_version! $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
392 }
393  
394 =head2 unique_failure_msg
395  
396 Given a DB failure message, will return true if the message was a failure due to a
397 failed UNIQUE contstraint, else will return false.
398  
399 eval { $class->create(%args) };
400 if( $@ ) {
401 die unless Smolder::DB->unique_failure_msg($@);
402 }
403  
404 =cut
405  
406 0 ▶sub unique_failure_msg {
Subroutine unique_failure_msg: not called CC=1 SCAR=6.9
407 0 my ($class, $msg) = @_;
408 0 return $msg =~ /not unique/i;
409 }
410  
411 =head2 format_datetime
412  
413 Given a L<DateTime> object, return the string we want to store in the database
414  
415 =cut
416  
417 0 ▶sub format_datetime {
Subroutine format_datetime: not called CC=1 SCAR=6.9
418 0 my ($class, $dt) = @_;
419 0 return $dt->strftime('%Y-%m-%d %H:%M:%S');
420 }
421  
422 =head2 parse_datetime
423  
424 Given a date string, return the L<DateTime> object it represents.
425  
426 =cut
427  
428 my $DATE_FMT = DateTime::Format::Strptime->new(
429 pattern => '%Y-%m-%d %H:%M:%S',
430 time_zone => 'local'
431 );
432 0 ▶sub parse_datetime {
Subroutine parse_datetime: not called CC=1 SCAR=6.9
433 0 my ($class, $string) = @_;
434 0 return $DATE_FMT->parse_datetime($string);
435 }
436  
437 1;
438  
439 __END__
« blib/lib/Smolder/DB/SmokeReport.pm ↑ Summary lib/Smolder/Build.pm »