Sticker/Database.pm

filter: Statementstmt 5.8% 23 / 396 Branchbran 0.0% 0 / 188 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 25.9% 7 / 27 Podpod 100% 14 / 14 totaltotal 6.6% 44 / 659 CC 118 SCAR 56.9
CC
118
Cov
4%
add_meta_to_db
930.0
get_all_tags
380.0
create_tables
272.0
CRAP 295.4
« Sticker/Derive/Common.pm ↑ Summary Sticker/Derive.pm »
1 package File::Sticker::Database;
2 1 $File::Sticker::Database::VERSION = '4.9';
3 =head1 NAME
4  
5 File::Sticker::Database - write info to database
6  
7 =head1 VERSION
8  
9 version 4.9
10  
11 =head1 SYNOPSIS
12  
13 use File::Sticker::Database;
14  
15 my $db = File::Sticker::Database->new(%args);
16  
17 $db->write_meta(%args);
18  
19 =head1 DESCRIPTION
20  
21 This will write meta-data from files in various formats, and standardize it to a common
22 nomenclature.
23  
24 =cut
25  
26 1 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 1 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 1 ▶use DBD::SQLite::Constants qw(:file_open);
Subroutine BEGIN: called CC=1 SCAR=0.0
30 1 ▶use Search::Query;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 1 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 1 ▶use YAML::Any;
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34 =head1 DEBUGGING
35  
36 =head2 whoami
37  
38 Used for debugging info
39  
40 =cut
41 0 ▶sub whoami { ( caller(1) )[3] }
Subroutine whoami: not called CC=1 SCAR=6.9
Pod documented
42  
43 =head1 METHODS
44  
45 =head2 new
46  
47 Create a new object, setting global values for the object.
48  
49 my $obj = File::Sticker::Database->new(
50 dbname=>$dbname,
51 wanted_fields=>\%wanted_fields,
52 field_order=>\@field_order,
53 primary_table=>$primary_table,
54 space_sep=>$space_sep,
55 );
56  
57 =cut
58  
59 0 ▶sub new {
Subroutine new: not called CC=2 SCAR=17.9
Pod documented
60 0 my $class = shift;
61 0 my %parameters = (@_);
62 0 ▶ my $self = bless ({%parameters}, ref ($class) || $class);
Condition0%0/3
ref $class || $class
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table0%0/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
63  
64 0 return ($self);
65 } # new
66  
67 =head2 do_connect
68  
69 Connect to the database if not connected already.
70  
71 =cut
72 0 ▶sub do_connect ($) {
Subroutine do_connect: not called CC=6 SCAR=37.4
Pod documented
73 0 my $self = shift;
74 0 ▶ say STDERR whoami() if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
75  
76 0 ▶ if ($self->{dbh})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"dbh"}) 0 0 0
77 {
78 0 return $self->{dbh};
79 }
80 0 my $database = $self->{dbname};
81 0 ▶ if ($database)
Branch: 1 branch
BranchTrueFalseTotal
if ($database) { } 0 0 0
82 {
83 my $dbh = DBI->connect("dbi:SQLite:dbname=$database", undef, undef,
84 {sqlite_open_flags => ($self->{readonly}
85 0 ▶ ? SQLITE_OPEN_READONLY
Branch: 1 branch
BranchTrueFalseTotal
$self->{'readonly'} ? : 0 0 0
86 : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE),
87 });
88 0 ▶ if (!$dbh)
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbh) 0 0 0
89 {
90 0 die "Can't connect to $database: $DBI::errstr";
91 }
92  
93 0 $self->{dbh} = $dbh;
94 0 return $dbh;
95 }
96 else
97 {
98 0 die "No Database given.";
99 }
100 } # do_connect
101  
102 =head2 create_tables
103  
104 Create the tables for the database.
105 Give them all prefixes so that multiple setups can use the same database.
106  
107 If the database is readonly, this does not create tables,
108 but it does set up configuration information, so it should still be called.
109  
110 =cut
111 0 ▶sub create_tables ($) {
Subroutine create_tables: not called CC=16 SCAR=56.1
Pod documented
112 0 my $self = shift;
113 0 ▶ say STDERR whoami() if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
114  
115 0 ▶ return unless $self->{dbh};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"dbh"} 0 0 0
116  
117 0 my $dbh = $self->{dbh};
118  
119 0 my @fieldnames = @{$self->{field_order}};
120 # need to define some fields as numeric, some as multi
121 0 my @field_defs = ();
122 0 my @multi_fields = ();
123 0 foreach my $field (@fieldnames)
124 {
125 0 ▶ if (exists $self->{wanted_fields}->{$field})
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{'wanted_fields'}{$field}) { } 0 0 0
126 {
127 0 my $type = $self->{wanted_fields}->{$field};
128 0 ▶ if ($type =~ /MULTI/i)
Branch: 1 branch
BranchTrueFalseTotal
if ($type =~ /MULTI/iu) { } 0 0 0
129 {
130 0 push @field_defs, $field . ' TEXT';
131 0 push @multi_fields, $field;
132 }
133 else
134 {
135 0 push @field_defs, $field . ' ' . $type;
136 }
137 }
138 else
139 {
140 0 push @field_defs, $field;
141 }
142 }
143 0 $self->{multi_fields} = \@multi_fields;
144  
145 0 my $primary_table = $self->{primary_table};
146  
147 # Only create tables is this is not readonly.
148 0 ▶ if (!$self->{readonly})
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"readonly"}) 0 0 0
149 {
150 0 my $q = "CREATE TABLE IF NOT EXISTS $primary_table (fileid INTEGER PRIMARY KEY, file TEXT NOT NULL UNIQUE, "
151 . join(", ", @field_defs) .");";
152 0 my $ret = $dbh->do($q);
153 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
154 {
155 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
156 }
157 0 foreach my $multi (@multi_fields)
158 {
159 0 my $deep_table = $self->_deep_table_name(${multi});
160 0 $q = "CREATE TABLE IF NOT EXISTS ${deep_table} (fileid INTEGER NOT NULL, ${multi}, FOREIGN KEY(fileid) REFERENCES ${primary_table}(fileid));";
161 0 $ret = $dbh->do($q);
162 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
163 {
164 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
165 }
166 0 $q = "CREATE UNIQUE INDEX IF NOT EXISTS ${deep_table}_index ON ${deep_table} (fileid, ${multi})";
167 0 $ret = $dbh->do($q);
168 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
169 {
170 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
171 }
172 }
173  
174 # ----------------------------------------------------------
175 # Create the "info" table
176 # This has the same as the primary_table, plus a faceted_tags field
177 # which combines the taggable information into one big collection
178 # of faceted tags.
179 # The taggable_fields hash contains the field names, and the prefix
180 # for the field, if one is desired.
181 # ----------------------------------------------------------
182 0 ▶ my $space_sep = ($self->{space_sep} ? $self->{space_sep} : '-');
Branch: 1 branch
BranchTrueFalseTotal
$self->{'space_sep'} ? : 0 0 0
183 0 ▶ if ($self->{taggable_fields})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"taggable_fields"}) 0 0 0
184 {
185 0 $q = "CREATE VIEW IF NOT EXISTS ${primary_table}_info AS SELECT fileid, file, ";
186 0 $q .= join(', ', @fieldnames);
187 # create the faceted_tags field
188 0 $q .= ", replace(";
189 0 my @tagdefs = ();
190 0 foreach my $fn (sort keys %{$self->{taggable_fields}})
191 {
192 0 my $prefix = $self->{taggable_fields}->{$fn};
193 0 ▶ if ($self->{wanted_fields}->{$fn} =~ /multi/i)
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'wanted_fields'}{$fn} =~ /multi/iu) { } 0 0 0
194 {
195 0 push @tagdefs, " ifnull('|$prefix' || replace($fn, '|', '|$prefix'), '')";
196 }
197 else # single-valued
198 {
199 0 push @tagdefs, " ifnull('|$prefix' || $fn, '')";
200 }
201 }
202 0 $q .= join(' || ', @tagdefs);
203 0 $q .= sprintf(', " ", "%s") ', $space_sep);
204  
205 0 $q .= " AS faceted_tags ";
206 0 $q .= " FROM $primary_table;";
207  
208 0 $ret = $dbh->do($q);
209 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
210 {
211 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
212 }
213 }
214 }
215  
216 0 return 1;
217 } # create_tables
218  
219 =head2 do_disconnect
220  
221 Disconnect from the database
222  
223 =cut
224 0 ▶sub do_disconnect ($) {
Subroutine do_disconnect: not called CC=3 SCAR=24.8
Pod documented
225 0 my $self = shift;
226 0 ▶ say STDERR whoami() if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
227  
228 0 ▶ if (!$self->{dbh})
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"dbh"}) 0 0 0
229 {
230 0 return;
231 }
232 0 $self->{dbh}->disconnect();
233 } # do_disconnect
234  
235 =head2 start_transaction
236  
237 Start a transaction.
238  
239 =cut
240 0 ▶sub start_transaction ($) {
Subroutine start_transaction: not called CC=4 SCAR=30.0
Pod documented
241 0 my $self = shift;
242 0 ▶ say STDERR whoami() if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
243  
244 0 ▶ if (!$self->{dbh})
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"dbh"}) 0 0 0
245 {
246 0 return;
247 }
248 0 my $ret = $self->{dbh}->do("BEGIN TRANSACTION;");
249 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
if (not $ret) 0 0 0
250 {
251 0 croak __PACKAGE__ . " failed 'BEGIN TRANSACTION' : $DBI::errstr";
252 }
253 } # start_transaction
254  
255 =head2 commit
256  
257 Commit a pending transaction.
258  
259 $self->commit();
260  
261 =cut
262 0 ▶sub commit ($%) {
Subroutine commit: not called CC=3 SCAR=24.8
Pod documented
263 0 my $self = shift;
264 0 my %args = @_;
265 0 my $meta = $args{meta};
266  
267 0 ▶ return unless $self->{dbh};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"dbh"} 0 0 0
268  
269 0 my $ret = $self->{dbh}->do("COMMIT;");
270 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
if (not $ret) 0 0 0
271 {
272 0 croak __PACKAGE__ . " failed 'COMMIT' : $DBI::errstr";
273 }
274 } # commit
275  
276 =head2 get_file_id
277  
278 Get the fileid of the given file
279  
280 my $fileid = $self->get_file_id($filename);
281  
282 =cut
283 0 ▶sub get_file_id ($$) {
Subroutine get_file_id: not called CC=7 SCAR=40.3
Pod documented
284 0 my $self = shift;
285 0 my $filename = shift;
286 0 ▶ say STDERR whoami() if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
287  
288 0 my $dbh = $self->do_connect();
289  
290 0 my $fullname = $filename;
291 0 ▶ if (-r $filename)
Branch: 1 branch
BranchTrueFalseTotal
if (-r $filename) { } 0 0 0
292 {
293 0 $fullname = path($filename)->realpath->stringify;
294 }
295 else
296 {
297 # Can't use realpath if the file isn't there
298 # But we need to be able to do this if we're deleting removed files
299 0 $fullname = path($filename)->absolute->stringify;
300 }
301 0 ▶ say STDERR "fullname=$fullname" if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
302  
303 0 my $q = 'SELECT fileid FROM ' . $self->{primary_table} . ' WHERE file = ?';
304 0 my $sth = $self->_prepare($q);
305 0 my $ret = $sth->execute($fullname);
306 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
307 {
308 0 die "FAILED '$q' $DBI::errstr";
309 }
310  
311 0 my $fileid = 0;
312 0 my @row;
313 0 ▶ while (@row = $sth->fetchrow_array)
Branch: 1 branch
BranchTrueFalseTotal
if (@row = $sth->fetchrow_array) 0 0 0
314 {
315 0 ▶ say STDERR "found a file: ", $row[0] if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
316 0 $fileid = $row[0];
317 }
318  
319 0 return $fileid;
320 } # get_file_id
321  
322 =head2 get_file_meta
323  
324 Get the meta-data for a single file.
325  
326 $meta = $self->get_file_meta($file);
327  
328 =cut
329  
330 0 ▶sub get_file_meta {
Subroutine get_file_meta: not called CC=7 SCAR=40.3
Pod documented
331 0 my $self = shift;
332 0 my $filename = shift;
333  
334 0 ▶ return unless $self->{dbh};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"dbh"} 0 0 0
335 0 my $dbh = $self->{dbh};
336 0 my $table = $self->{primary_table};
337 0 ▶ if ($self->{taggable_fields})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"taggable_fields"}) 0 0 0
338 {
339 0 $table = "${table}_info";
340 }
341 0 my $file_id = $self->get_file_id($filename);
342  
343 0 ▶ return undef if !$file_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $file_id 0 0 0
344  
345 0 my $q = "SELECT * FROM $table WHERE fileid = ?;";
346  
347 0 my $sth = $self->_prepare($q);
348 0 ▶ if (!$sth)
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
349 {
350 0 croak "FAILED to prepare '$q' $DBI::errstr";
351 }
352 0 my $ret = $sth->execute($file_id);
353 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
354 {
355 0 croak "FAILED to execute '$q' $DBI::errstr";
356 }
357 # return the first matching row because there should be only one row
358 0 my $meta = $sth->fetchrow_hashref;
359 0 ▶ if (!$meta)
Branch: 1 branch
BranchTrueFalseTotal
unless ($meta) 0 0 0
360 {
361 0 return undef;
362 }
363  
364 0 return $meta;
365 } # get_file_meta
366  
367 =head2 get_all_files
368  
369 Return a list of all the files in the database.
370  
371 my @files = @{$db->get_all_files()};
372  
373 =cut
374 0 ▶sub get_all_files {
Subroutine get_all_files: not called CC=1 SCAR=6.9
Pod documented
375 0 my $self = shift;
376  
377 0 $self->do_connect();
378 0 my $table = $self->{primary_table};
379  
380 0 my $files = $self->_do_one_col_query("SELECT file FROM $table ORDER BY file;");
381 0 return $files;
382 } # get_all_files
383  
384 =head2 get_all_tags
385  
386 Return a list of all the tags from the appropriate "deep*" table.
387  
388 my @tags = @{$db->get_all_tags()};
389  
390 =cut
391 0 ▶sub get_all_tags {
Subroutine get_all_tags: not called CC=19 SCAR=59.4
Pod documented
392 0 my $self = shift;
393  
394 0 $self->do_connect();
395  
396 # Tags are in taggable_fields. They may either be plain fields or multi_fields.
397 # Yes, there are multi_fields that aren't tags (such as multiple URLs).
398 # If there are no multifields and no taggable fields then... um?
399 0 ▶ if (!$self->{taggable_fields})
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"taggable_fields"}) 0 0 0
400 {
401 0 say STDERR Dump($self->{multi_fields});
402 0 return;
403 }
404  
405 # Process the multi_fields first,
406 # since they have to be read from the deep_* tables
407 0 my %mt_fields = ();
408 0 my %tags_hash = ();
409 0 ▶ my $space_sep = ($self->{space_sep} ? $self->{space_sep} : '-');
Branch: 1 branch
BranchTrueFalseTotal
$self->{'space_sep'} ? : 0 0 0
410 0 foreach my $t (@{$self->{multi_fields}})
411 {
412 # Only count as a tag if it is in taggable_fields
413 0 ▶ if (exists $self->{taggable_fields}->{$t})
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"taggable_fields"}{$t}) 0 0 0
414 {
415 0 my $deep_table = $self->_deep_table_name($t);
416 # In a readonly database, deep tables might not exist,
417 # so check for table existance before querying
418 0 ▶ if (!$self->{readonly} or $self->_table_exists($deep_table))
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->{'readonly'} or $self->_table_exists($deep_table)) { } 0 0 0
Condition0%0/3
not $self->{"readonly"} or $self->_table_exists($deep_table)
l!l&&r!l&&!r
000
MC/DC0%0/2
not $self->{"readonly"} or $self->_table_exists($deep_table)
not $self->{"readonly"} $self->_table_exists($deep_table)
Truth table0%0/3
not(A) or B
A= not $self->{"readonly"}B= $self->_table_exists($deep_table)
ABresult
1X1
011
000
419 {
420 0 $mt_fields{$t} = 1; # yes, we got a table, mark as processed
421 0 ▶ say STDERR "MT=$t" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
422 0 my $these_tags = $self->_do_one_col_query("SELECT DISTINCT replace($t, ' ', '${space_sep}') FROM ${deep_table} ORDER BY $t;");
423 0 my @prefixed_tags = $self->_add_tag_prefixes($t, $these_tags);
424 0 $tags_hash{$_}++ for (@prefixed_tags);
425 }
426 else # is a multi-tag, but does not have a deep table
427 {
428 0 $mt_fields{$t} = 2;
429 }
430 }
431 }
432  
433 # Now process the taggable_fields which are not multi_fields.
434 # (And the multi-fields that don't have deep tables)
435 # These have to be looked up in the primary table.
436 0 my $primary_table = $self->{primary_table};
437 0 foreach my $t (keys %{$self->{taggable_fields}})
438 {
439 0 ▶ if (!$mt_fields{$t}) # has not been processed as a multi-field
Branch: 2 branches
BranchTrueFalseTotal
if (not $mt_fields{$t}) { } 0 0 0
elsif ($mt_fields{$t} == 2) { } 0 0 0
440 {
441 0 ▶ say STDERR "TT=$t" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
442 0 my $these_tags = $self->_do_one_col_query("SELECT DISTINCT replace($t, ' ', '${space_sep}') FROM ${primary_table};");
443 0 my @prefixed_tags = $self->_add_tag_prefixes($t, $these_tags);
444 0 $tags_hash{$_}++ for (@prefixed_tags);
445 }
446 elsif ($mt_fields{$t} == 2) # multi-field without deep table
447 {
448 0 ▶ say STDERR "MT=$t" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
449 # Is a multi-tag field, but does not have a deep table to look at
450 # Will have to look at the primary table AND split each result
451 0 my $these_multi_tags = $self->_do_one_col_query("SELECT DISTINCT replace($t, ' ', '${space_sep}') FROM ${primary_table};");
452 0 foreach my $mt (@{$these_multi_tags})
453 {
454 0 my @these_split_tags = split(/[,|]/, $mt);
455 0 my @prefixed_tags = $self->_add_tag_prefixes($t, \@these_split_tags);
456 0 $tags_hash{$_}++ for (@prefixed_tags);
457 }
458 }
459 }
460 0 ▶ say STDERR "Tags hash:", Dump(\%tags_hash) if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
461  
462 0 my @tags = sort keys %tags_hash;
463 0 ▶ say STDERR "Sorted tags:", Dump(@tags) if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
464  
465 0 return \@tags;
466  
467 } # get_all_tags
468  
469 =head2 query_by_tags
470  
471 Use +tag -tag nomenclature for searching the database for matching files.
472 If the *info table exists, uses that, otherwise, it uses the "tagfield" in the primary table.
473  
474 =cut
475 0 ▶sub query_by_tags ($$$) {
Subroutine query_by_tags: not called CC=10 SCAR=47.0
Pod documented
476 0 my $self = shift;
477 0 my $query_string = shift;
478 0 ▶ printf "%s\n", whoami() if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
479  
480 0 my $dbh = $self->do_connect();
481 0 my $table = $self->{primary_table};
482 0 my $using_info_table = 0;
483 0 ▶ if ($self->{taggable_fields})
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"taggable_fields"}) 0 0 0
484 {
485 0 $table = $table . '_info';
486 0 $using_info_table = 1;
487 }
488 my $default_field = ($using_info_table
489 ? 'faceted_tags'
490 : ( $self->{tagfield}
491 ? $self->{tagfield}
492 0 ▶ : 'tags'
Branch: 2 branches
BranchTrueFalseTotal
$using_info_table ? : 0 0 0
$self->{'tagfield'} ? : 0 0 0
493 )
494 );
495  
496 0 ▶ say sprintf("Q='%s'", $query_string) if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
497 0 my @pfields = qw(fileid file);
498 0 ▶ push @pfields, @{$self->{field_order}},
Branch: 1 branch
BranchTrueFalseTotal
if $using_info_table 0 0 0
499 push @pfields, 'faceted_tags' if $using_info_table;
500 my $parser = Search::Query->parser(
501 query_class => 'SQL',
502 null_term => 'NULL',
503 query_class_opts => {
504 like => 'GLOB',
505 wildcard => '*',
506 },
507 # I don't want these to be case-insensitive
508 # because tags could start with these words
509 and_regex => qr/\&|AND/,
510 or_regex => qr/\||OR/,
511 not_regex => qr/NOT/,
512  
513 default_field => $default_field,
514 default_op => '~',
515 fields => \@pfields,
516 0 ▶ term_expander => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
517 0 my ($term, $field) = @_;
518 0 ▶ if (!$field || $field eq $default_field)
Branch: 1 branch
BranchTrueFalseTotal
if (not $field or $field eq $default_field) 0 0 0
Condition0%0/3
not $field or $field eq $default_field
l!l&&r!l&&!r
000
MC/DC0%0/2
not $field or $field eq $default_field
not $field $field eq $default_field
Truth table0%0/3
not(A) or B
A= not $fieldB= $field eq $default_field
ABresult
1X1
011
000
519 {
520 # search for pipe-delimited terms
521 0 my @newterms = ();
522 0 ▶ if (ref $term)
Branch: 1 branch
BranchTrueFalseTotal
if (ref $term) { } 0 0 0
523 {
524 0 foreach my $tt (@{$term})
525 {
526 0 push @newterms, $tt; # term alone
527 0 push @newterms, $tt . '|*'; # at start
528 0 push @newterms, '*|' . $tt . '|*'; # in middle
529 0 push @newterms, '*|' . $tt; # at end
530 }
531 }
532 else
533 {
534 # Fix embeddeds quotes for SQL quoting
535 # Can't use the "quote" method because that
536 # also puts quotes around the whole thing, which
537 # messes things up.
538 0 $term =~ s/\'/''/g;
539 0 push @newterms, $term; # term alone
540 0 push @newterms, $term . '|*'; # at start
541 0 push @newterms, '*|' . $term . '|*'; # in middle
542 0 push @newterms, '*|' . $term; # at end
543 }
544 0 return @newterms;
545 }
546 0 return ($term);
547 }
548 0 );
549 0 my $query = $parser->parse($query_string);
550  
551 0 my $q = "SELECT file FROM $table WHERE " . $query->stringify;
552 0 $q .= " ORDER BY file";
553 0 ▶ print $q, "\n" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
554 0 my $sth = $self->_prepare($q);
555 0 my $ret = $sth->execute();
556 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
557 {
558 0 die "FAILED '$q' $DBI::errstr";
559 }
560  
561 0 my @files = ();
562 0 my @row;
563 0 ▶ while (@row = $sth->fetchrow_array)
Branch: 1 branch
BranchTrueFalseTotal
if (@row = $sth->fetchrow_array) 0 0 0
564 {
565 0 push @files, $row[0];
566 }
567  
568 0 return \@files;
569 } # query_by_tags
570  
571 =head2 delete_file_from_db
572  
573 Delete the record for one file from the database
574  
575 $db->delete_file_from_db($filename);
576  
577 =cut
578 0 ▶sub delete_file_from_db ($$) {
Subroutine delete_file_from_db: not called CC=6 SCAR=37.4
Pod documented
579 0 my $self = shift;
580 0 my $filename = shift;
581 0 ▶ say STDERR whoami() if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
582  
583 0 my $dbh = $self->do_connect();
584 0 my $file_id = $self->get_file_id($filename);
585  
586 # If the file is in the db, DELETE
587 0 ▶ if ($file_id)
Branch: 1 branch
BranchTrueFalseTotal
if ($file_id) 0 0 0
588 {
589 # remove from deep* tables first
590 0 foreach my $t (@{$self->{multi_fields}})
591 {
592 0 my $deep_table = $self->_deep_table_name($t);
593 0 my $q = "DELETE FROM ${deep_table} WHERE fileid = ?;";
594 0 my $sth = $self->_prepare($q);
595 0 my $ret = $sth->execute($file_id);
596 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
597 {
598 0 die "FAILED query '$q' $DBI::errstr";
599 }
600 }
601  
602 0 my $q = 'DELETE FROM ' . $self->{primary_table} . ' WHERE fileid = ?;';
603 0 my $sth = $self->_prepare($q);
604 0 my $ret = $sth->execute($file_id);
605 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
if (not $ret) 0 0 0
606 {
607 0 die "FAILED query '$q' $DBI::errstr";
608 }
609 }
610  
611 } # delete_file_from_db
612  
613 =head2 add_meta_to_db
614  
615 Add the given file info to the database.
616  
617 $db->add_meta_to_db($filename, %meta);
618  
619 =cut
620 0 ▶sub add_meta_to_db {
Subroutine add_meta_to_db: not called CC=30 SCAR=68.4
Pod documented
621 0 my $self = shift;
622 0 my $filename = shift;
623 0 my %meta = @_;
624 0 ▶ say STDERR whoami() if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
625  
626 0 my $dbh = $self->do_connect();
627  
628 # ------------------------------------------------
629 # Values
630 # ------------------------------------------------
631 0 my @values = ();
632 0 foreach my $fn (@{$self->{field_order}})
633 {
634 0 my $val = $meta{$fn};
635 0 ▶ if (!defined $val)
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $val) { } 0 0 0
elsif (ref $val) { } 0 0 0
elsif (exists $self->{'wanted_fields'}{$fn} and defined $self->{'wanted_fields'}{$fn} and $self->{'wanted_fields'}{$fn} =~ /multi/iu) { } 0 0 0
636 {
637 0 push @values, undef;
638 }
639 elsif (ref $val)
640 {
641 0 $val = join("|", @{$val});
642 0 push @values, $val;
643 }
644 ▶ elsif (exists $self->{wanted_fields}->{$fn}
Condition0%0/6
exists $self->{"wanted_fields"}{$fn} and defined $self->{"wanted_fields"}{$fn} and $self->{"wanted_fields"}{$fn} =~ /multi/iu
!ll&&!rl&&r
000
exists $self->{"wanted_fields"}{$fn} and defined $self->{"wanted_fields"}{$fn}
!ll&&!rl&&r
000
MC/DC0%0/3
exists $self->{"wanted_fields"}{$fn} and defined $self->{"wanted_fields"}{$fn} and $self->{"wanted_fields"}{$fn} =~ /multi/iu
exists $self->{"wanted_fields"}{$fn} defined $self->{"wanted_fields"}{$fn} $self->{"wanted_fields"}{$fn} =~ /multi/iu
Truth table0%0/4
A and B and C
A= exists $self->{"wanted_fields"}{$fn}B= defined $self->{"wanted_fields"}{$fn}C= $self->{"wanted_fields"}{$fn} =~ /multi/iu
ABCresult
0XX0
10X0
1100
1111
645 and defined $self->{wanted_fields}->{$fn}
646 and $self->{wanted_fields}->{$fn} =~ /multi/i)
647 # convert comma-separated into pipe-separated
648 {
649 0 $val =~ s/,\s*/|/g;
650 0 push @values, $val;
651 }
652 else
653 {
654 0 push @values, $val;
655 }
656 0 ▶ say STDERR " $fn=$val " if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
657 }
658 0 my %multi_values = ();
659 0 foreach my $field (@{$self->{multi_fields}})
660 {
661 0 my $val = $meta{$field};
662 0 ▶ if (!defined $val)
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $val) { } 0 0 0
elsif (ref $val) { } 0 0 0
663 {
664 # do nothing
665 }
666 elsif (ref $val)
667 {
668 0 $multi_values{$field} = $val;
669 }
670 else
671 {
672 0 my @values = split(/[,|]/, $val);
673 0 $multi_values{$field} = \@values;
674 }
675 }
676  
677 # ------------------------------------------------
678 # Primary Table
679 # ------------------------------------------------
680  
681 # Check if the record exists in the table
682 # and do an INSERT or UPDATE depending on whether it does.
683 # This is faster than REPLACE because it doesn't need
684 # to rebuild indexes.
685 0 my $fullname = $filename;
686 0 ▶ if (-r $filename)
Branch: 1 branch
BranchTrueFalseTotal
if (-r $filename) { } 0 0 0
687 {
688 0 $fullname = path($filename)->realpath->stringify;
689 }
690 else
691 {
692 # Can't use realpath if the file isn't there
693 # But we need to be able to do this if we're deleting removed files
694 0 $fullname = path($filename)->absolute->stringify;
695 }
696 0 my $file_id = $self->get_file_id($fullname);
697 0 ▶ say STDERR "file_id=$file_id" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
698 0 my $q;
699 my $ret;
700 0 ▶ if ($file_id)
Branch: 1 branch
BranchTrueFalseTotal
if ($file_id) { } 0 0 0
701 {
702 0 $q = "UPDATE $self->{primary_table} SET ";
703 0 ▶ for (my $i=0; $i < @values; $i++)
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @values) 0 0 0
704 {
705 0 $q .= sprintf('%s = ?', $self->{field_order}->[$i]);
706 0 ▶ if ($i + 1 < @values)
Branch: 1 branch
BranchTrueFalseTotal
if ($i + 1 < @values) 0 0 0
707 {
708 0 $q .= ", ";
709 }
710 }
711 0 $q .= " WHERE fileid = '$file_id';";
712 0 my $sth = $self->_prepare($q);
713 0 ▶ if (!$sth)
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
714 {
715 0 croak __PACKAGE__ . " failed to prepare '$q' : $DBI::errstr";
716 }
717 0 $ret = $sth->execute(@values);
718 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
719 {
720 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
721 }
722  
723 # However, it's simpler to just delete everything from the deeptables
724 # and add the new tags below. I know, this is programmer laziness.
725 0 foreach my $t (@{$self->{multi_fields}})
726 {
727 0 my $deep_table = $self->_deep_table_name($t);
728 0 $q = "DELETE FROM ${deep_table} WHERE fileid = ?;";
729 0 my $sth = $self->_prepare($q);
730 0 $ret = $sth->execute($file_id);
731 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
732 {
733 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
734 }
735 }
736 }
737 else
738 {
739 0 my $placeholders = join ", ", ('?') x @{$self->{field_order}};
740 $q = 'INSERT INTO ' . $self->{primary_table} . ' (file, '
741 0 . join(", ", @{$self->{field_order}}) . ') VALUES (?, ' . $placeholders . ');';
742 0 ▶ say STDERR "q=$q" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
743  
744 0 my $sth = $self->_prepare($q);
745 0 ▶ if (!$sth)
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
746 {
747 0 croak __PACKAGE__ . " failed to prepare '$q' : $DBI::errstr";
748 }
749 0 $ret = $sth->execute($fullname, @values);
750 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
751 {
752 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
753 }
754  
755 # get the file_id of the newly-inserted file
756 0 $file_id = $self->get_file_id($fullname);
757 0 ▶ say STDERR "new file_id=$file_id" if $self->{verbose} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 1 0 0 0
758 }
759  
760 # ------------------------------------------------
761 # Deep tables
762 # ------------------------------------------------
763 0 foreach my $field (@{$self->{multi_fields}})
764 {
765 0 ▶ if (exists $multi_values{$field}
Branch: 1 branch
BranchTrueFalseTotal
if (exists $multi_values{$field} and defined $multi_values{$field}) 0 0 0
Condition0%0/3
exists $multi_values{$field} and defined $multi_values{$field}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $multi_values{$field} and defined $multi_values{$field}
exists $multi_values{$field} defined $multi_values{$field}
Truth table0%0/3
A and B
A= exists $multi_values{$field}B= defined $multi_values{$field}
ABresult
0X0
100
111
766 and defined $multi_values{$field})
767 {
768 0 my $deep_table = $self->_deep_table_name($field);
769 0 $q = "INSERT INTO ${deep_table} (fileid, ${field}) VALUES (?, ?);";
770 0 my $sth = $self->_prepare($q);
771 0 my @values = @{$multi_values{$field}};
772 0 foreach my $val (@values)
773 {
774 0 $ret = $sth->execute($file_id,$val);
775 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
776 {
777 0 croak __PACKAGE__ . " failed '$q' : $DBI::errstr";
778 }
779 }
780 }
781 }
782  
783 } # add_meta_to_db
784  
785 =head1 Helper Functions
786  
787 Private interface.
788  
789 =cut
790  
791 =head2 _deep_table_name
792  
793 Return the name of the given deep_* table.
794  
795 =cut
796 0 ▶sub _deep_table_name {
Subroutine _deep_table_name: not called CC=1 SCAR=6.9
797 0 my $self = shift;
798 0 my $field = shift;
799  
800 0 return $self->{primary_table} . '_deep_' . $field;
801 } # _deep_table_name
802  
803 =head2 _table_exists
804  
805 Checks if a given table exists.
806 This can be relevant with a readonly database where
807 tables are not guaranteed to have been created.
808  
809 =cut
810 0 ▶sub _table_exists {
Subroutine _table_exists: not called CC=4 SCAR=30.0
811 0 my $self = shift;
812 0 my $table = shift;
813 0 ▶ say STDERR whoami(), ' ', $table if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
814  
815 0 my $dbh = $self->{dbh};
816 0 my $type = "'TABLE','VIEW'";
817 0 my $sth = $dbh->table_info(undef, undef, $table, $type);
818  
819 0 my $table_does_exist = 0;
820 0 my $found_table = '';
821 0 my @row;
822 0 ▶ while (@row = $sth->fetchrow_array)
Branch: 1 branch
BranchTrueFalseTotal
if (@row = $sth->fetchrow_array) 0 0 0
823 {
824 say STDERR sprintf('found a table: %s (%s)', $row[2], $row[3])
825 0 ▶ if $self->{verbose} > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} > 2 0 0 0
826 0 $found_table = $row[2];
827 0 $table_does_exist = 1;
828 }
829 0 return $table_does_exist;
830 } # _table_exists
831  
832 =head2 _add_tag_prefixes
833  
834 Add prefixes to the given array of tags.
835  
836 my @pref_tags = $self->_add_tag_prefixes($field, \@values);
837  
838 =cut
839 0 ▶sub _add_tag_prefixes {
Subroutine _add_tag_prefixes: not called CC=3 SCAR=24.8
840 0 my $self = shift;
841 0 my $field = shift;
842 0 my $values = shift;
843  
844 0 my @prefixed_tags = ();
845 0 ▶ if ($self->{taggable_fields}->{$field}) # has a field-specific prefix
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'taggable_fields'}{$field}) { } 0 0 0
elsif ($self->{'tagprefix'}) { } 0 0 0
846 {
847 0 my $pr = $self->{taggable_fields}->{$field};
848 0 @prefixed_tags = map { "${pr}$_" } @{$values};
849 }
850 elsif ($self->{tagprefix}) # simple prefix for all tags
851 {
852 0 @prefixed_tags = map { "${field}-$_" } @{$values};
853 }
854 else # no prefix needed
855 {
856 0 @prefixed_tags = @{$values};
857 }
858 0 return @prefixed_tags;
859 } # _add_tag_prefixes
860  
861 =head2 _do_one_col_query
862  
863 Do a SELECT query, and return the first column of results.
864 This is a freeform query, so the caller must be careful to formulate it correctly.
865  
866 my $results = $self->_do_one_col_query($query);
867  
868 =cut
869  
870 0 ▶sub _do_one_col_query {
Subroutine _do_one_col_query: not called CC=5 SCAR=34.0
871 0 my $self = shift;
872 0 my $q = shift;
873  
874 0 ▶ if ($q !~ /^SELECT /)
Branch: 1 branch
BranchTrueFalseTotal
unless ($q =~ /^SELECT /u) 0 0 0
875 {
876 # bad boy! Not a SELECT.
877 0 return undef;
878 }
879 0 my $dbh = $self->{dbh};
880  
881 0 my $sth = $self->_prepare($q);
882 0 ▶ if (!$sth)
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
883 {
884 0 croak "FAILED to prepare '$q' $DBI::errstr";
885 }
886 0 my $ret = $sth->execute();
887 0 ▶ if (!$ret)
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret) 0 0 0
888 {
889 0 croak "FAILED to execute '$q' $DBI::errstr";
890 }
891 0 my @results = ();
892 0 my @row;
893 0 ▶ while (@row = $sth->fetchrow_array)
Branch: 1 branch
BranchTrueFalseTotal
if (@row = $sth->fetchrow_array) 0 0 0
894 {
895 0 push @results, $row[0];
896 }
897 0 return \@results;
898  
899 } # _do_one_col_query
900  
901 =head2 _prepare
902  
903 Prepare and cache prepared queries.
904  
905 my $sth = $self->_prepare($q);
906  
907 =cut
908 0 ▶sub _prepare {
Subroutine _prepare: not called CC=4 SCAR=30.0
909 0 my $self = shift;
910 0 my $q = shift;
911  
912 0 my $sth;
913 0 ▶ if (exists $self->{_queries}->{$q}
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{'_queries'}{$q} and defined $self->{'_queries'}{$q}) { } 0 0 0
Condition0%0/3
exists $self->{"_queries"}{$q} and defined $self->{"_queries"}{$q}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $self->{"_queries"}{$q} and defined $self->{"_queries"}{$q}
exists $self->{"_queries"}{$q} defined $self->{"_queries"}{$q}
Truth table0%0/3
A and B
A= exists $self->{"_queries"}{$q}B= defined $self->{"_queries"}{$q}
ABresult
0X0
100
111
914 and defined $self->{_queries}->{$q})
915 {
916 0 $sth = $self->{_queries}->{$q};
917 }
918 else
919 {
920 0 $sth = $self->{dbh}->prepare($q);
921 0 ▶ if (!$sth)
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth) 0 0 0
922 {
923 0 die "FAILED to prepare query '$q' $DBI::errstr";
924 }
925 0 $self->{_queries}->{$q} = $sth;
926 }
927 0 return $sth;
928 } # _prepare
929  
930 =head1 BUGS
931  
932 Please report any bugs or feature requests to the author.
933  
934 =cut
935  
936 1 1; # End of File::Sticker::Database
937 __END__
« Sticker/Derive/Common.pm ↑ Summary Sticker/Derive.pm »