AtteanX/Store/DBI.pm

filter: Statementstmt 70.3% 503 / 715 Branchbran 50.4% 105 / 208 Conditioncond 33.3% 17 / 51 MC/DCmcdc 14.2% 4 / 28 Subroutinesub 76.3% 58 / 76 Podpod 80.7% 21 / 26 totaltotal 64.1% 708 / 1104 CC 134 SCAR 34.1
CC
134
Cov
64%
plans_for_algebra
101.6
_get_term
67.2
_get_term_id
33.0
CRAP 30.3
↑ Summary Test/AtteanX/Store/DBI.pm »
1 =head1 NAME
2  
3 AtteanX::Store::DBI - Database quad-store
4  
5 =head1 VERSION
6  
7 This document describes AtteanX::Store::DBI version 0.003_02
8  
9 =head1 SYNOPSIS
10  
11 use Attean;
12 my $store = Attean->get_store('DBI')->new( dbh => $dbh );
13  
14 =head1 DESCRIPTION
15  
16 AtteanX::Store::DBI provides a quad-store backed by a relational database.
17  
18 =head1 ATTRIBUTES
19  
20 =over 4
21  
22 =item C<< dbh >>
23  
24 =back
25  
26 =cut
27  
28 3 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 3 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 3 package AtteanX::Store::DBI {
33 3 our $VERSION = '0.003_02';
34 3 ▶ use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 3 ▶ use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 3 ▶ use Attean 0.013;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 3 ▶ use Cache::LRU;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 3 ▶ use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 3 ▶ use DBI::Const::GetInfoType;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 3 ▶ use DBIx::MultiStatementDo;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 3 ▶ use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 3 ▶ use File::ShareDir qw(dist_dir dist_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
43 3 ▶ use File::Slurp;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 3 ▶ use List::MoreUtils qw(zip);
Subroutine BEGIN: called CC=1 SCAR=0.0
45 3 ▶ use List::Util qw(any all first mesh);
Subroutine BEGIN: called CC=1 SCAR=0.0
46 3 ▶ use Scalar::Util qw(refaddr reftype blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
47 3 ▶ use Set::Scalar;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 3 ▶ use Type::Tiny::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 3 ▶ use Types::Standard qw(Bool Int Str ArrayRef HashRef ConsumerOf InstanceOf);
Subroutine BEGIN: called CC=1 SCAR=0.0
50 3 ▶ use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
51  
52 3 our $CURRENT_MODEL_VERSION = 1;
53
54 3 with 'Attean::API::MutableQuadStore';
55 3 with 'Attean::API::BulkUpdatableStore';
56 3 with 'Attean::API::QuadStore';
57 3 with 'Attean::API::CostPlanner';
58  
59 3 my @pos_names = Attean::API::Quad->variables;
60  
61 =head1 ROLES
62  
63 This class consumes L<Attean::API::QuadStore>,
64 L<Attean::API::MutableQuadStore>, and L<Attean::API::BulkUpdatableStore>.
65  
66 =head1 METHODS
67  
68 =over 4
69  
70 =item C<< new ( dbh => $dbh ) >>
71  
72 Returns a new quad-store object backed by the database referenced by the
73 supplied database handle.
74  
75 =cut
76  
77 21 ▶ sub BUILDARGS {
Subroutine BUILDARGS: called CC=4 SCAR=17.5
Pod undocumented
78 21 my $class = shift;
79 21 my @params = @_;
80 21 my @connect;
81
82 my %args;
83 21 ▶ if (scalar(@params) % 2 == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar(@params) % 2 == 0) { } 21 0 21
84 21 my %params = @params;
85
86 21 ▶ if (my $i = delete $params{'init'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $i = delete $params{"init"}) 0 21 21
87 0 $args{'should_init'} = $i;
88 }
89
90 21 ▶ if (my $dbh = $params{ dbh }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dbh = $params{"dbh"}) 21 0 21
91 21 return \%params;
92 }
93 0 my $type = delete($params{ type });
94 0 @connect = $class->dbi_connect_args($type, %params);
95 } else {
96 0 my $type = shift(@params);
97 0 @connect = $class->dbi_connect_args($type, @params);
98 }
99 0 $args{dbh} = DBI->connect(@connect);
100 0 return \%args;
101 }
102  
103 3 has should_init => (is => 'ro', isa => Bool, default => 0);
104 3 has dbh => (is => 'ro', isa => InstanceOf['DBI::db'], required => 1);
105 21 ▶ has _i2t_cache => (is => 'ro', default => sub { Cache::LRU->new( size => 256 ) });
Subroutine __ANON__: called CC=1 SCAR=0.0
106 21 ▶ has _t2i_cache => (is => 'ro', default => sub { Cache::LRU->new( size => 256 ) });
Subroutine __ANON__: called CC=1 SCAR=0.0
107 18 ▶ has insert_term_sth => (is => 'ro', lazy => 1, default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
108 18 my $self = shift;
109 18 my $dbh = $self->dbh;
110 18 return $dbh->prepare('INSERT INTO term (type, value, datatype_id, language) VALUES (?, ?, ?, ?)');
111 3 });
112 18 ▶ has insert_quad_sth => (is => 'ro', lazy => 1, default => sub {
Subroutine __ANON__: called CC=4 SCAR=17.3
113 18 my $self = shift;
114 18 my $dbh = $self->dbh;
115 18 my $type = $self->database_type;
116 18 my $sql = 'INSERT INTO quad (subject, predicate, object, graph) VALUES (?, ?, ?, ?)';
117 18 ▶ if ($type eq 'sqlite') {
Branch: 3 branches
BranchTrueFalseTotal
if ($type eq 'sqlite') { } 18 0 18
elsif ($type eq 'mysql') { } 0 0 0
elsif ($type eq 'postgresql') { } 0 0 0
118 18 $sql = 'INSERT OR IGNORE INTO quad (subject, predicate, object, graph) VALUES (?, ?, ?, ?)';
119 } elsif ($type eq 'mysql') {
120 0 $sql = 'INSERT IGNORE INTO quad (subject, predicate, object, graph) VALUES (?, ?, ?, ?)';
121 } elsif ($type eq 'postgresql') {
122 0 $sql = 'INSERT INTO quad (subject, predicate, object, graph) SELECT ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM quad WHERE subject = ? AND predicate = ? AND object = ? AND graph = ?)';
123 }
124 18 return $self->dbh->prepare($sql);
125 3 });
126 0 ▶ has get_term_sth => (is => 'ro', lazy => 1, default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
127 0 my $self = shift;
128 0 my $dbh = $self->dbh;
129 0 return $self->dbh->prepare('SELECT term.type, term.value, dtterm.value AS datatype, term.language, tt.subject, tt.predicate, tt.object FROM term LEFT JOIN term dtterm ON (term.datatype_id = dtterm.term_id) LEFT JOIN triple_term tt ON (term.term_id = tt.term_id) WHERE term.term_id = ?');
130 3 });
131 19 ▶ has get_term_id_sth => (is => 'ro', lazy => 1, default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
132 19 my $self = shift;
133 19 my $dbh = $self->dbh;
134 19 return $self->dbh->prepare('SELECT term_id FROM term WHERE type = ? AND value = ?');
135 3 });
136 0 ▶ has get_literal_term_id_sth => (is => 'ro', lazy => 1, default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
137 0 my $self = shift;
138 0 my $dbh = $self->dbh;
139 0 return $self->dbh->prepare('SELECT term_id FROM term WHERE type = ? AND value = ? AND datatype_id = ? AND language = ?');
140 3 });
141  
142 21 ▶ sub BUILD {
Subroutine BUILD: called CC=2 SCAR=8.1
Pod undocumented
143 21 my $self = shift;
144 21 ▶ if ($self->should_init) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->should_init) 0 21 21
145 0 $self->init();
146 }
147 }
148  
149 =item C<< init() >>
150  
151 Create the tables and indexes required for using the database as a quadstore.
152  
153 =cut
154 0 ▶ sub init {
Subroutine init: not called CC=2 SCAR=17.9
Pod documented
155 0 my $self = shift;
156 0 my $dbh = $self->dbh;
157 0 my $batch = DBIx::MultiStatementDo->new( dbh => $dbh );
158 0 ▶ my $file = $self->create_schema_file or die 'No schema files available for store initialization';
Branch: 1 branch
BranchTrueFalseTotal
my $file = $self->create_schema_file or die "No schema files available for store initialization" 0 0 0
159 0 my $sql = read_file($file);
160 0 $batch->do($sql);
161 }
162
163 =item C<< temporary_store() >>
164  
165 Returns a temporary (in-memory, SQLite) store.
166  
167 =cut
168 0 ▶ sub temporary_store {
Subroutine temporary_store: not called CC=1 SCAR=6.9
Pod documented
169 0 my $class = shift;
170 0 my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:', '', '', {
171 RaiseError => 1,
172 sqlite_unicode => 1,
173 });
174 0 my $store = $class->new(dbh => $dbh);
175 0 $store->init();
176 0 return $store;
177 }
178
179 259 ▶ sub _last_insert_id {
Subroutine _last_insert_id: called CC=1 SCAR=0.0
180 259 my $self = shift;
181 259 my $table = shift;
182 259 my $dbh = $self->dbh;
183 259 return $dbh->last_insert_id(undef, undef, $table, undef);
184 }
185  
186 53 ▶ sub _get_term {
Subroutine _get_term: called CC=9 SCAR=42.1
187 53 my $self = shift;
188 53 my $id = shift;
189 53 ▶ if (my $term = $self->_i2t_cache->get($id)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $term = $self->_i2t_cache->get($id)) 53 0 53
190 53 return $term;
191 }
192 0 my $sth = $self->get_term_sth;
193 0 $sth->execute($id);
194 0 my $row = $sth->fetchrow_hashref;
195 0 my $type = $row->{type};
196 0 my $term;
197 0 my $value = $row->{value};
198 0 my $datatype = $row->{datatype};
199 0 my $lang = $row->{language};
200 0 ▶ if ($type eq 'iri') {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'iri') { } 0 0 0
elsif ($type eq 'blank') { } 0 0 0
elsif ($type eq 'literal') { } 0 0 0
elsif ($type eq 'triple') { } 0 0 0
201 0 $term = Attean::IRI->new( value => $value );
202 } elsif ($type eq 'blank') {
203 0 $term = Attean::Blank->new( value => $value );
204 } elsif ($type eq 'literal') {
205 0 my %args = (value => $value, datatype => Attean::IRI->new(value => $datatype));
206 0 ▶ if ($lang) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lang) 0 0 0
207 0 ▶ if ($lang =~ /--/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lang =~ /--/u) { } 0 0 0
208 0 my ($l, $dir) = split('--', $lang);
209 0 $args{language} = $l;
210 0 $args{base_dir} = $dir;
211 } else {
212 0 $args{language} = $lang;
213 }
214 }
215 0 $term = Attean::Literal->new( %args );
216 } elsif ($type eq 'triple') {
217 0 my @ids = @{ $row }{ qw(subject predicate object) };
218 0 my ($s,$p,$o) = map { $self->_get_term($_) } @ids;
219 0 $term = Attean::Triple->new(subject => $s, predicate => $p, object => $o);
220 }
221 0 ▶ if ($term) {
Branch: 1 branch
BranchTrueFalseTotal
if ($term) 0 0 0
222 0 $self->_i2t_cache->set($id => $term);
223 0 return $term;
224 }
225 0 die "Failed to load term values for bad ID " . Dumper($id);
226 }
227
228 41 ▶ sub _get_term_id {
Subroutine _get_term_id: called CC=9 SCAR=35.0
229 41 my $self = shift;
230 41 my $term = shift;
231 41 ▶ if (my $id = $self->_t2i_cache->get($term->as_string)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $self->_t2i_cache->get($term->as_string)) 37 4 41
232 37 return $id;
233 }
234 4 my $dbh = $self->dbh;
235 4 my $tid;
236 4 ▶ if ($term->does('Attean::API::IRI')) {
Branch: 4 branches
BranchTrueFalseTotal
if ($term->does('Attean::API::IRI')) { } 4 0 4
elsif ($term->does('Attean::API::Blank')) { } 0 0 0
elsif ($term->does('Attean::API::Literal')) { } 0 0 0
elsif ($term->does('Attean::API::TriplePattern') and $term->is_ground) { } 0 0 0
237 4 my $sth = $self->get_term_id_sth;
238 4 my $value = $term->value;
239 4 $sth->execute('iri', $value);
240 4 ($tid) = $sth->fetchrow_array;
241 } elsif ($term->does('Attean::API::Blank')) {
242 0 my $sth = $self->get_term_id_sth;
243 0 my $value = $term->value;
244 0 $sth->execute('blank', $value);
245 0 ($tid) = $sth->fetchrow_array;
246 } elsif ($term->does('Attean::API::Literal')) {
247 0 my $dtid = $self->_get_or_create_term_id($term->datatype);
248 0 my $sth = $self->get_literal_term_id_sth;
249 0 my $value = $term->value;
250 0 my $lang = $term->lang_dir;
251 0 $sth->execute('literal', $value, $dtid, $lang);
252 0 ($tid) = $sth->fetchrow_array;
253 ▶ } elsif ($term->does('Attean::API::TriplePattern') and $term->is_ground) {
Condition0%0/3
$term->does("Attean::API::TriplePattern") and $term->is_ground
!ll&&!rl&&r
000
MC/DC0%0/2
$term->does("Attean::API::TriplePattern") and $term->is_ground
$term->does("Attean::API::TriplePattern") $term->is_ground
Truth table0%0/3
A and B
A= $term->does("Attean::API::TriplePattern")B= $term->is_ground
ABresult
0X0
100
111
254 0 my @terms = $term->values;
255 0 ▶ my @ids = map { $self->_get_term_id($_) || 0 } @terms;
Condition0%0/2
$self->_get_term_id($_) || 0
l!l
00
MC/DC0%0/1
$self->_get_term_id($_) || 0
$self->_get_term_id($_)
Truth table0%0/2
A
A= $self->_get_term_id($_)
Aresult
11
00
256 0 my $value = join(' ', map { +$_ } @ids);
257 0 my $sth = $self->get_term_id_sth;
258 0 $sth->execute('triple', $value);
259 0 ($tid) = $sth->fetchrow_array;
260 } else {
261 0 die "Failed to get ID for term: " . $term->as_string;
262 }
263 4 ▶ if (defined($tid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tid) 0 4 4
264 0 $self->_t2i_cache->set($term->as_string => $tid);
265 0 return $tid;
266 }
267 4 return;
268 }
269
270 648 ▶ sub _get_or_create_term_id {
Subroutine _get_or_create_term_id: called CC=12 SCAR=25.0
271 648 my $self = shift;
272 648 my $term = shift;
273 648 ▶ if (my $id = $self->_t2i_cache->get($term->as_string)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $self->_t2i_cache->get($term->as_string)) 389 259 648
274 389 return $id;
275 }
276 259 my $dbh = $self->dbh;
277 259 my $tid;
278 259 my $insert_term_sth = $self->insert_term_sth;
279 259 ▶ if ($term->does('Attean::API::IRI')) {
Branch: 4 branches
BranchTrueFalseTotal
if ($term->does('Attean::API::IRI')) { } 145 114 259
elsif ($term->does('Attean::API::Blank')) { } 42 72 114
elsif ($term->does('Attean::API::Literal')) { } 70 2 72
elsif ($term->does('Attean::API::Triple')) { } 2 0 2
280 145 my $sth = $self->get_term_id_sth;
281 145 my $value = $term->value;
282 145 $sth->execute('iri', $value);
283 145 ($tid) = $sth->fetchrow_array;
284 145 ▶ unless (defined($tid)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $tid) 145 0 145
285 145 $insert_term_sth->execute('iri', $value, undef, undef);
286 145 $tid = $self->_last_insert_id('term');
287 }
288 } elsif ($term->does('Attean::API::Blank')) {
289 42 my $sth = $self->get_term_id_sth;
290 42 my $value = $term->value;
291 42 $sth->execute('blank', $value);
292 42 ($tid) = $sth->fetchrow_array;
293 42 ▶ unless (defined($tid)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $tid) 42 0 42
294 42 $insert_term_sth->execute('blank', $value, undef, undef);
295 42 $tid = $self->_last_insert_id('term');
296 }
297 } elsif ($term->does('Attean::API::Literal')) {
298 70 my $dtid = $self->_get_or_create_term_id($term->datatype);
299 70 my $sql = 'SELECT term_id FROM term WHERE type = ? AND value = ? AND datatype_id = ?';
300 70 my $value = $term->value;
301 70 my @bind = ('literal', $value, $dtid);
302 70 my $lang = $term->lang_dir;
303 70 ▶ if ($lang) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lang) 14 56 70
304 14 $sql .= ' AND language = ?';
305 14 push(@bind, $lang);
306 }
307 70 my $sth = $dbh->prepare($sql);
308 70 $sth->execute(@bind);
309 70 ($tid) = $sth->fetchrow_array;
310 70 ▶ unless (defined($tid)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $tid) 70 0 70
311 70 $insert_term_sth->execute('literal', $value, $dtid, $lang);
312 70 $tid = $self->_last_insert_id('term');
313 }
314 } elsif ($term->does('Attean::API::Triple')) {
315 2 my $insert_triple_term_sth = $dbh->prepare('INSERT INTO triple_term (term_id, subject, predicate, object) VALUES (?, ?, ?, ?)');
316 2 my @terms = $term->values;
317 2 my @ids = map { $self->_get_or_create_term_id($_) } @terms;
318 2 my $value = join(' ', map { +$_ } @ids);
319 2 my $sth = $dbh->prepare('SELECT term_id FROM triple_term WHERE subject = ? AND predicate = ? AND object = ?');
320
321 2 $sth->execute(@ids);
322 2 ($tid) = $sth->fetchrow_array;
323 2 ▶ unless (defined($tid)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $tid) 2 0 2
324 2 $insert_term_sth->execute('triple', $value, undef, undef);
325 2 $tid = $self->_last_insert_id('term');
326 2 $insert_triple_term_sth->execute($tid, @ids);
327 }
328 } else {
329 0 die "Failed to get ID for term: " . $term->as_string;
330 }
331
332 259 ▶ if (defined($tid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tid) 259 0 259
333 259 $self->_t2i_cache->set($term->as_string => $tid);
334 259 $self->_i2t_cache->set($tid => $term);
335 259 return $tid;
336 }
337 0 die;
338 }
339  
340 =item C<< get_quads ( $subject, $predicate, $object, $graph ) >>
341  
342 Returns a stream object of all statements matching the specified subject,
343 predicate and objects. Any of the arguments may be undef to match any value,
344 or an ARRAY reference of terms that are allowable in the respective quad
345 position.
346  
347 =cut
348  
349 8 ▶ sub get_quads {
Subroutine get_quads: called CC=11 SCAR=24.0
Pod documented
350 8 my $self = shift;
351 8 ▶ my @nodes = map { ref($_) eq 'ARRAY' ? $_ : [$_] } @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 0 11 11
352 8 my @where;
353 my @bind;
354 8 my %post_filters;
355 8 foreach my $i (0 .. 3) {
356 26 my $name = $pos_names[$i];
357 26 my $terms = $nodes[$i];
358 26 ▶ if (defined($terms)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $terms) 10 16 26
359 10 ▶ next if (scalar(@$terms) == 1 and not defined($terms->[0]));
Branch: 1 branch
BranchTrueFalseTotal
if scalar @$terms == 1 and not defined $terms->[0] 4 6 10
Condition66%2/3
scalar @$terms == 1 and not defined $terms->[0]
!ll&&!rl&&r
064
MC/DC50%1/2
scalar @$terms == 1 and not defined $terms->[0]
scalar @$terms == 1 not defined $terms->[0]
Truth table66%2/3
A and not(B)
A= scalar @$terms == 1B= not defined $terms->[0]
ABresult
0X0
100
111
360 6 ▶ if (any { $_->does('Attean::API::TriplePattern') and not($_->is_ground) } @$terms) {
Branch: 1 branch
BranchTrueFalseTotal
if (&any(sub { $_->does('Attean::API::TriplePattern') and not $_->is_ground; } , @$terms)) { } 1 5 6
361 # we'll do the full scan, and post-filter to ensure the triple matches
362 1 ▶ if (any { not($_->does('Attean::API::Variable')) } @$terms) {
Branch: 1 branch
BranchTrueFalseTotal
if (&any(sub { not $_->does("Attean::API::Variable"); } , @$terms)) 1 0 1
363 1 $post_filters{ $name } = $terms;
364 }
365 } else {
366 5 ▶ next if (any { $_->does('Attean::API::Variable') } @$terms);
Branch: 1 branch
BranchTrueFalseTotal
if &any(sub { $_->does("Attean::API::Variable"); } , @$terms) 1 4 5
367
368 4 my @ids = map { $self->_get_term_id($_) } @$terms;
369 4 ▶ unless (scalar(@ids)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @ids) 2 2 4
370 2 return Attean::ListIterator->new( values => [], item_type => 'Attean::API::Quad' );
371 }
372 2 push(@where, "$name IN (" . join(', ', ('?') x scalar(@ids)) . ")");
373 2 push(@bind, @ids);
374 }
375 }
376 }
377 6 my $sql = 'SELECT subject, predicate, object, graph FROM quad';
378 6 ▶ if (scalar(@where)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @where) 2 4 6
379 2 $sql .= ' WHERE ' . join(' AND ', @where);
380 }
381 6 my $sth = $self->dbh->prepare($sql);
382 6 $sth->execute(@bind);
383 6 my $ok = 1;
384 my $sub = sub {
385 return unless ($ok);
386 ROW: while (my $row = $sth->fetchrow_arrayref) {
387 my @terms = map { $self->_get_term($_) } @$row;
388 my %args;
389 @args{ @pos_names } = @terms;
390 my $quad = Attean::Quad->new(%args);
391 if (%post_filters) {
392 # there was a triple term pattern in the match request, so validate that here
393 foreach my $pos (keys %post_filters) {
394 my $terms = $post_filters{ $pos };
395 my $got = $quad->$pos();
396 foreach my $expected (@$terms) {
397 if ($expected->does('Attean::API::TriplePattern') and $expected->matches($got)) {
398 return $quad;
399 } elsif (eval { $got->equals($expected) }) {
400 return $quad;
401 }
402 }
403 next ROW; # no requested term matched the value in this quad
404 }
405 }
406  
407 return $quad;
408 }
409 $ok = 0;
410 return;
411 6 };
412 6 my $iter = Attean::CodeIterator->new( generator => $sub, item_type => 'Attean::API::Quad' );
413 6 return $iter;
414 }
415  
416 =item C<< count_quads ( $subject, $predicate, $object, $graph ) >>
417  
418 Returns the count of all statements matching the specified subject,
419 predicate and objects. Any of the arguments may be undef to match any value,
420 or an ARRAY reference of terms that are allowable in the respective quad
421 position.
422  
423 =cut
424  
425 17 ▶ sub count_quads {
Subroutine count_quads: called CC=9 SCAR=22.0
Pod documented
426 17 my $self = shift;
427 17 ▶ my @nodes = map { ref($_) eq 'ARRAY' ? $_ : [$_] } @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 0 7 7
428 17 my @where;
429 my @bind;
430 17 foreach my $i (0 .. 3) {
431 62 my $name = $pos_names[$i];
432 62 my $terms = $nodes[$i];
433 62 ▶ if (defined($terms)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $terms) 7 55 62
434 7 ▶ unless (scalar(@$terms) == 1 and not defined($terms->[0])) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @$terms == 1 and not defined $terms->[0]) 5 2 7
Condition66%2/3
scalar @$terms == 1 and not defined $terms->[0]
!ll&&!rl&&r
052
MC/DC50%1/2
scalar @$terms == 1 and not defined $terms->[0]
scalar @$terms == 1 not defined $terms->[0]
Truth table66%2/3
A and not(B)
A= scalar @$terms == 1B= not defined $terms->[0]
ABresult
0X0
100
111
435 5 ▶ unless (any { $_->does('Attean::API::Variable') } @$terms) {
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless (&any(sub { $_->does("Attean::API::Variable"); } , @$terms)) 4 1 5
436 4 my @ids = map { $self->_get_term_id($_) } @$terms;
437 4 ▶ return 0 unless scalar(@ids);
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @ids 2 2 4
438 2 push(@where, "$name IN (" . join(', ', ('?') x scalar(@ids)) . ")");
439 2 push(@bind, @ids);
440 }
441 }
442 }
443 }
444 15 my $sql = 'SELECT COUNT(*) FROM quad';
445 15 ▶ if (scalar(@where)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @where) 2 13 15
446 2 $sql .= ' WHERE ' . join(' AND ', @where);
447 }
448 15 my $sth = $self->dbh->prepare($sql);
449 15 $sth->execute(@bind);
450 15 my ($count) = $sth->fetchrow_array;
451 15 return $count;
452 }
453  
454 =item C<< get_graphs >>
455  
456 Returns an iterator over the Attean::API::Term objects comprising
457 the set of graphs of the stored quads.
458  
459 =cut
460  
461 10 ▶ sub get_graphs {
Subroutine get_graphs: called CC=1 SCAR=0.0
Pod documented
462 10 my $self = shift;
463 10 my $sth = $self->dbh->prepare('SELECT DISTINCT value FROM quad JOIN term ON (quad.graph = term.term_id)');
464 10 $sth->execute;
465 15 ▶ my $sub = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
466 15 my $row = $sth->fetchrow_arrayref;
467 15 ▶ return unless ref($row);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row 9 6 15
468 6 my ($value) = @$row;
469 6 return Attean::IRI->new(value => $value);
470 10 };
471 10 return Attean::CodeIterator->new( generator => $sub, item_type => 'Attean::API::Term' );
472 }
473  
474 # -----------------------------------------------------------------------------
475  
476 0 ▶ around 'add_iter' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
477 0 my $orig = shift;
478 0 my $self = shift;
479 0 my $dbh = $self->dbh;
480 0 local($dbh->{AutoCommit}) = 0;
481 0 return $self->$orig(@_);
482 3 };
483  
484  
485 =item C<< add_quad ( $quad ) >>
486  
487 Adds the specified C<$quad> to the underlying model.
488  
489 =cut
490
491 sub add_quad {
492 my $self = shift;
493 my $st = shift;
494 my @ids = map { $self->_get_or_create_term_id($_) } $st->values;
495 if (any { not defined($_) } @ids) {
496 return;
497 }
498
499 my $type = $self->database_type;
500 my @bind = @ids;
501 my $sth = $self->insert_quad_sth;
502 if ($type eq 'postgresql') {
503 push(@bind, @ids);
504 }
505 $sth->execute(@bind);
506 return;
507 }
508  
509 =item C<< remove_quad ( $statement ) >>
510  
511 Removes the specified C<$statement> from the underlying model.
512  
513 =cut
514  
515 147 ▶ sub remove_quad {
Subroutine remove_quad: called CC=3 SCAR=11.2
Pod documented
516 147 my $self = shift;
517 147 my $st = shift;
518 147 my @ids = map { $self->_get_term_id($_) } $st->values;
519 147 ▶ unless (scalar(@ids) == 4) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @ids == 4) 0 147 147
520 0 return;
521 }
522 147 ▶ unless (all { defined($_) } @ids) {
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
unless (&all(sub { defined $_; } , @ids)) 0 147 147
523 143 return;
524 }
525 147 my $sth = $self->dbh->prepare('DELETE FROM quad WHERE subject = ? AND predicate = ? AND object = ? AND graph = ?');
526 147 $sth->execute(@ids);
527 4 return;
528 }
529  
530 =item C<< create_graph( $graph ) >>
531  
532 This is a no-op function for the memory quad-store.
533  
534 =cut
535  
536 4 ▶ sub create_graph {
Subroutine create_graph: called CC=1 SCAR=0.0
Pod documented
537 # no-op on a quad-store
538 }
539  
540 =item C<< drop_graph( $graph ) >>
541  
542 Removes all quads with the given C<< $graph >>.
543  
544 =cut
545  
546 2 ▶ sub drop_graph {
Subroutine drop_graph: called CC=1 SCAR=0.0
Pod documented
547 145 my $self = shift;
548 2 return $self->clear_graph(@_);
549 }
550  
551 =item C<< clear_graph( $graph ) >>
552  
553 Removes all quads with the given C<< $graph >>.
554  
555 =cut
556  
557 4 ▶ sub clear_graph {
Subroutine clear_graph: called CC=2 SCAR=7.0
Pod documented
558 4 my $self = shift;
559 4 my $graph = shift;
560 4 my $gid = $self->_get_term_id($graph);
561 4 ▶ return unless defined($gid);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gid 0 4 4
562 4 my $sth = $self->dbh->prepare('DELETE FROM quad WHERE graph = ?');
563 4 $sth->execute($gid);
564 4 return;
565 }
566
567 =item C<< begin_transaction >>
568  
569 Begin a database transaction.
570  
571 =cut
572  
573 0 ▶ sub begin_transaction {
Subroutine begin_transaction: not called CC=1 SCAR=6.9
Pod documented
574 # warn 'begin transaction';
575 0 my $self = shift;
576 0 $self->dbh->begin_work;
577 }
578
579 =item C<< abort_transaction >>
580  
581 Rollback the current database transaction.
582  
583 =cut
584  
585 0 ▶ sub abort_transaction {
Subroutine abort_transaction: not called CC=1 SCAR=6.9
Pod documented
586 # warn 'abort transaction';
587 0 my $self = shift;
588 0 $self->dbh->rollback;
589 }
590
591 =item C<< end_transaction >>
592  
593 Commit the current database transaction.
594  
595 =cut
596  
597 0 ▶ sub end_transaction {
Subroutine end_transaction: not called CC=1 SCAR=6.9
Pod documented
598 # warn 'end transaction';
599 0 my $self = shift;
600 0 $self->dbh->commit;
601 }
602
603 =item C<< begin_bulk_updates >>
604  
605 Begin a database transaction.
606  
607 =cut
608  
609 0 ▶ sub begin_bulk_updates {
Subroutine begin_bulk_updates: not called CC=1 SCAR=6.9
Pod documented
610 0 my $self = shift;
611 0 $self->dbh->begin_work;
612 }
613
614 =item C<< end_bulk_updates >>
615  
616 Commit the current database transaction.
617  
618 =cut
619  
620 0 ▶ sub end_bulk_updates {
Subroutine end_bulk_updates: not called CC=1 SCAR=6.9
Pod documented
621 0 my $self = shift;
622 0 $self->dbh->commit;
623 }
624
625 =item C<< database_type >>
626  
627 Returns the database type name as a string (e.g. 'mysql', 'sqlite', or 'postgresql').
628  
629 =cut
630  
631 186 ▶ sub database_type {
Subroutine database_type: called CC=1 SCAR=0.0
Pod documented
632 186 my $self = shift;
633 186 my $dbh = $self->dbh;
634 # warn $dbh->get_info($GetInfoType{SQL_DRIVER_NAME});
635 186 my $type = lc($dbh->get_info($GetInfoType{SQL_DBMS_NAME}));
636 186 return $type;
637 }
638
639 =item C<< initialize_version >>
640  
641 Insert data into the attean_version table.
642  
643 =cut
644  
645 0 ▶ sub initialize_version {
Subroutine initialize_version: not called CC=1 SCAR=6.9
Pod documented
646 0 my $self = shift;
647 0 my $dbh = $self->dbh;
648 0 $dbh->do('DELETE FROM attean_version');
649 0 my $sql = 'INSERT INTO attean_version (attean_version, model_version, store_version) VALUES (?, ?, ?);';
650 0 $dbh->do($sql, undef, $Attean::VERSION, $CURRENT_MODEL_VERSION, $AtteanX::Store::DBI::VERSION);
651 }
652  
653 =item C<< create_schema_file >>
654  
655 Returns the path to the file containing the database DDL for quadstore creation
656 for the current database type if available, undef otherwise.
657  
658 =cut
659  
660 21 ▶ sub create_schema_file {
Subroutine create_schema_file: called CC=5 SCAR=16.4
Pod documented
661 21 my $self = shift;
662 21 my $type = $self->database_type;
663 21 my @options;
664 21 ▶ push(@options, $ENV{ATTEAN_SHAREDIR}) if ($ENV{ATTEAN_SHAREDIR});
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"ATTEAN_SHAREDIR"} 0 21 21
665 21 ▶ push(@options, $ENV{ATTEANX_STORE_DBI_SHAREDIR}) if ($ENV{ATTEANX_STORE_DBI_SHAREDIR});
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"ATTEANX_STORE_DBI_SHAREDIR"} 0 21 21
666 21 eval {
667 21 my $path = dist_dir('AtteanX-Store-DBI');
668 21 push(@options, $path);
669 };
670 21 push(@options, 'share');
671 21 foreach my $dir (@options) {
672 21 my $file = sprintf('%s-create.sql', $type);
673 21 my $abs = File::Spec->catfile($dir, 'database-schema', $file);
674 21 ▶ if (-r $abs) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $abs) 21 0 21
675 21 return $abs;
676 }
677 }
678 0 return;
679 }
680  
681 =item C<< drop_schema_file >>
682  
683 Returns the path to the file containing the database DDL for quadstore deletion
684 for the current database type if available, undef otherwise.
685  
686 =cut
687  
688 0 ▶ sub drop_schema_file {
Subroutine drop_schema_file: not called CC=4 SCAR=30.0
Pod documented
689 0 my $self = shift;
690 0 my $type = $self->database_type;
691 0 ▶ my $dir = $ENV{ATTEAN_SHAREDIR} || eval { dist_dir('AtteanX-Store-DBI') } || 'share';
Condition0%0/5
$ENV{'ATTEAN_SHAREDIR'} || eval { do { dist_dir('AtteanX-Store-DBI') } } || 'share'
l!l
00
$ENV{"ATTEAN_SHAREDIR"} or eval { do { dist_dir("AtteanX-Store-DBI") } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$ENV{'ATTEAN_SHAREDIR'} || eval { do { dist_dir('AtteanX-Store-DBI') } } || 'share'
$ENV{"ATTEAN_SHAREDIR"} eval { do { dist_dir("AtteanX-Store-DBI") } }
Truth table0%0/3
A or B
A= $ENV{"ATTEAN_SHAREDIR"}B= eval { do { dist_dir("AtteanX-Store-DBI") } }
ABresult
1X1
011
000
692 0 my $file = File::Spec->catfile($dir, 'database-schema', sprintf('%s-drop.sql', $type));
693 0 ▶ if (-r $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-r $file) 0 0 0
694 0 return $file;
695 }
696 0 return;
697 }
698
699 =item C<< available_database_types >>
700  
701 Returns the names of the database types for which the system has schemas
702 available to create and drop quadstore tables.
703  
704 =cut
705  
706 0 ▶ sub available_database_types {
Subroutine available_database_types: not called CC=3 SCAR=20.6
Pod documented
707 0 my $self = shift;
708 0 ▶ my $dir = $ENV{ATTEAN_SHAREDIR} || eval { dist_dir('AtteanX-Store-DBI') } || 'share';
Condition0%0/5
$ENV{'ATTEAN_SHAREDIR'} || eval { do { dist_dir('AtteanX-Store-DBI') } } || 'share'
l!l
00
$ENV{"ATTEAN_SHAREDIR"} or eval { do { dist_dir("AtteanX-Store-DBI") } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$ENV{'ATTEAN_SHAREDIR'} || eval { do { dist_dir('AtteanX-Store-DBI') } } || 'share'
$ENV{"ATTEAN_SHAREDIR"} eval { do { dist_dir("AtteanX-Store-DBI") } }
Truth table0%0/3
A or B
A= $ENV{"ATTEAN_SHAREDIR"}B= eval { do { dist_dir("AtteanX-Store-DBI") } }
ABresult
1X1
011
000
709 0 my $pat = File::Spec->catfile($dir, 'database-schema', '*-create.sql');
710 0 ▶ my @files = glob($pat);
Subroutine BEGIN: called CC=1 SCAR=0.2
711 0 my @types = map { /(\w+)-create.sql/ } @files;
712 0 return @types;
713 }
714
715 =item C<< dbi_connect_args ( $type, %args ) >>
716  
717 =item C<< dbi_connect_args ( %args ) >>
718  
719 Returns a quad C<< $dsn, $user, $password, \%connect_args >> suitable for
720 passing to C<< DBI->connect >> to obtain a database handle to be used in
721 constructing a C<< AtteanX::Store::DBI >> quadstore.
722  
723 C<< %args >> must contain a value for the C<< database >> key. It may also
724 contain values for the optional keys: C<< user >>, C<< password >>,
725 C<< host >>, and C<< port >>.
726  
727 If invoked as a class method, the C<< $type >> parameter is required, and must
728 be one of the database types returned by C<< available_database_types >>.
729  
730 If invoked as an object method, the C<< $type >> parameter must not be
731 included; this information will be obtained directly from the
732 C<< AtteanX::Store::DBI >> object.
733  
734 =cut
735  
736 21 ▶ sub dbi_connect_args {
Subroutine dbi_connect_args: called CC=10 SCAR=32.5
Pod documented
737 21 my $self = shift;
738 21 my $type;
739 my %args;
740 21 ▶ if (blessed($self)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($self)) { } 0 21 21
741 0 $type = $self->database_type;
742 } else {
743 21 ▶ if (scalar(@_) % 2 == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar(@_) % 2 == 0) { } 0 21 21
744 0 %args = @_;
745 0 $type = $args{type};
746 } else {
747 21 $type = shift;
748 21 %args = @_;
749 }
750 }
751 21 my $database = $args{database};
752 21 my $user = $args{user};
753 21 my $password = $args{password};
754 21 my $host = $args{host};
755 21 my $port = $args{port};
756 21 my $dsn;
757 my %connect_args;
758 21 $connect_args{RaiseError} = 1;
759 21 ▶ if ($type eq 'mysql') {
Branch: 3 branches
BranchTrueFalseTotal
if ($type eq 'mysql') { } 0 21 21
elsif ($type eq 'postgresql') { } 0 21 21
elsif ($type eq 'sqlite') { } 21 0 21
760 0 $dsn = "DBI:mysql:database=${database}";
761 0 ▶ if (defined($host)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $host) 0 0 0
762 0 $dsn .= ";host=$host";
763 }
764 0 ▶ if (defined($port)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $port) 0 0 0
765 0 $dsn .= ";port=$port";
766 }
767 0 $connect_args{mysql_enable_utf8mb4} = 1;
768 } elsif ($type eq 'postgresql') {
769 0 $dsn = "DBI:Pg:dbname=${database}";
770 0 ▶ if (defined($host)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $host) 0 0 0
771 0 $dsn .= ";host=$host";
772 }
773 0 ▶ if (defined($port)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $port) 0 0 0
774 0 $dsn .= ";port=$port";
775 }
776 } elsif ($type eq 'sqlite') {
777 21 $dsn = "DBI:SQLite:dbname=${database}";
778 21 $connect_args{sqlite_unicode} = 1;
779 }
780
781 21 $connect_args{PrintError} = 1;
782 21 return ($dsn, $user, $password, \%connect_args);
783 }
784  
785 =item C<< plans_for_algebra( $algebra, $model, $active_graphs, $default_graphs ) >>
786  
787 For BGP algebras, returns a DBI-specific L<Attean::API::Plan> object, otherwise
788 returns undef.
789  
790 =cut
791  
792 36 ▶ sub plans_for_algebra {
Subroutine plans_for_algebra: called CC=44 SCAR=46.2
Pod documented
793 36 my $self = shift;
794 36 my $algebra = shift;
795 36 my $model = shift;
796 36 my $active_graphs = shift;
797 36 my $default_graphs = shift;
798 36 ▶ return unless ($algebra);
Branch: 1 branch
BranchTrueFalseTotal
unless $algebra 0 36 36
799
800 36 my %args = @_;
801 36 my $counter = $args{dbi_filter_counter}++;
802
803 36 ▶ if ($algebra->isa('Attean::Algebra::Filter')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($algebra->isa('Attean::Algebra::Filter')) { } 9 27 36
elsif ($algebra->isa('Attean::Algebra::BGP') and scalar @{$algebra->triples;} > 0) { } 9 36 45
804 9 my $e = $algebra->expression;
805 9 ▶ if ($e->isa('Attean::FunctionExpression')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($e->isa("Attean::FunctionExpression")) 9 0 9
806 9 ▶ if ($e->operator =~ m/IS(IRI|LITERAL|BLANK)/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($e->operator =~ /IS(IRI|LITERAL|BLANK)/iu) { } 4 5 9
elsif ($e->operator eq 'STRSTARTS' or $e->operator eq 'CONTAINS') { } 5 0 5
807 4 my $type = lc($1);
808 4 my ($operand) = @{ $e->children };
809 4 ▶ if ($operand->isa('Attean::ValueExpression') and $operand->value->does('Attean::API::Variable')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($operand->isa("Attean::ValueExpression") and $operand->value->does("Attean::API::Variable")) 4 0 4
Condition33%1/3
$operand->isa("Attean::ValueExpression") and $operand->value->does("Attean::API::Variable")
!ll&&!rl&&r
004
MC/DC0%0/2
$operand->isa("Attean::ValueExpression") and $operand->value->does("Attean::API::Variable")
$operand->isa("Attean::ValueExpression") $operand->value->does("Attean::API::Variable")
Truth table33%1/3
A and B
A= $operand->isa("Attean::ValueExpression")B= $operand->value->does("Attean::API::Variable")
ABresult
0X0
100
111
810 4 my $var = $operand->value;
811 4 ▶ if (my ($plan) = $self->plans_for_algebra($algebra->child, $model, $active_graphs, $default_graphs, %args)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($plan) = $self->plans_for_algebra($algebra->child, $model, $active_graphs, $default_graphs, %args)) 4 0 4
812 4 ▶ if ($plan->isa('AtteanX::Store::DBI::Plan')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plan->isa("AtteanX::Store::DBI::Plan")) 4 0 4
813 4 ▶ if (exists $plan->variables->{ $var->value }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $plan->variables->{$var->value}) 4 0 4
814 4 my ($table, $col) = @{ $plan->variables->{ $var->value } };
815 4 my $ref = join('.', map { $self->dbh->quote_identifier($_) } ($table, $col));
816 4 my $typecol = $self->dbh->quote_identifier('type');
817 4 push(@{ $plan->where }, "$ref IN (SELECT term_id FROM term WHERE ${typecol} = ?)");
818 4 push(@{ $plan->bindings }, $type);
819 4 return $plan;
820 }
821 }
822 }
823 }
824 ▶ } elsif ($e->operator eq 'STRSTARTS' or $e->operator eq 'CONTAINS') {
Condition33%1/3
$e->operator eq "STRSTARTS" or $e->operator eq "CONTAINS"
l!l&&r!l&&!r
500
MC/DC0%0/2
$e->operator eq "STRSTARTS" or $e->operator eq "CONTAINS"
$e->operator eq "STRSTARTS" $e->operator eq "CONTAINS"
Truth table33%1/3
A or B
A= $e->operator eq "STRSTARTS"B= $e->operator eq "CONTAINS"
ABresult
1X1
011
000
825 5 my ($varexpr, $pat) = @{ $e->children };
826 5 ▶ if ($varexpr->isa('Attean::ValueExpression') and $varexpr->value->does('Attean::API::Variable') and $pat->isa('Attean::ValueExpression') and $pat->value->does('Attean::API::Literal')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($varexpr->isa("Attean::ValueExpression") and $varexpr->value->does("Attean::API::Variable") and $pat->isa("Attean::ValueExpression") and $pat->value->does("Attean::API::Literal")) 4 1 5
Condition66%6/9
$varexpr->isa("Attean::ValueExpression") and $varexpr->value->does("Attean::API::Variable") and $pat->isa("Attean::ValueExpression") and $pat->value->does("Attean::API::Literal")
!ll&&!rl&&r
104
$varexpr->isa("Attean::ValueExpression") and $varexpr->value->does("Attean::API::Variable") and $pat->isa("Attean::ValueExpression")
!ll&&!rl&&r
104
$varexpr->isa("Attean::ValueExpression") and $varexpr->value->does("Attean::API::Variable")
!ll&&!rl&&r
104
MC/DC25%1/4
$varexpr->isa("Attean::ValueExpression") and $varexpr->value->does("Attean::API::Variable") and $pat->isa("Attean::ValueExpression") and $pat->value->does("Attean::API::Literal")
$varexpr->isa("Attean::ValueExpression") $varexpr->value->does("Attean::API::Variable") $pat->isa("Attean::ValueExpression") $pat->value->does("Attean::API::Literal")
Truth table40%2/5
A and B and C and D
A= $varexpr->isa("Attean::ValueExpression")B= $varexpr->value->does("Attean::API::Variable")C= $pat->isa("Attean::ValueExpression")D= $pat->value->does("Attean::API::Literal")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
827 4 ▶ if (my ($plan) = $self->plans_for_algebra($algebra->child, $model, $active_graphs, $default_graphs, %args)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($plan) = $self->plans_for_algebra($algebra->child, $model, $active_graphs, $default_graphs, %args)) 4 0 4
828 4 ▶ if ($plan->isa('AtteanX::Store::DBI::Plan')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plan->isa("AtteanX::Store::DBI::Plan")) 4 0 4
829 4 my $var = $varexpr->value;
830 4 my $varname = $var->value;
831 4 ▶ if (exists $plan->variables->{ $var->value }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $plan->variables->{$var->value}) 4 0 4
832 4 my ($table, $col) = @{ $plan->variables->{ $var->value } };
833 4 my $literal = $pat->value;
834 4 my $ref = join('.', map { $self->dbh->quote_identifier($_) } ($table, $col));
835 4 my $typecol = $self->dbh->quote_identifier('type');
836 4 my $termtable = "tf$counter";
837 4 push(@{ $plan->tables }, ['term', $termtable]);
838  
839 4 my $db = $self->database_type;
840 4 ▶ return unless ($db eq 'mysql' or $db eq 'postgresql' or $db eq 'sqlite');
Branch: 1 branch
BranchTrueFalseTotal
unless $db eq "mysql" or $db eq "postgresql" or $db eq "sqlite" 0 4 4
Condition33%2/6
$db eq "mysql" or $db eq "postgresql" or $db eq "sqlite"
l!l&&r!l&&!r
040
$db eq "mysql" or $db eq "postgresql"
l!l&&r!l&&!r
004
MC/DC0%0/3
$db eq "mysql" or $db eq "postgresql" or $db eq "sqlite"
$db eq "mysql" $db eq "postgresql" $db eq "sqlite"
Truth table25%1/4
A or B or C
A= $db eq "mysql"B= $db eq "postgresql"C= $db eq "sqlite"
ABCresult
1XX1
01X1
0011
0000
841
842 4 push(@{ $plan->where }, "$ref = $termtable.term_id");
843
844 4 push(@{ $plan->where }, "$termtable.$typecol = ?"); # TODO: Remove this (and the bindings below) if $varexpr is STR(?var) instead of just ?var.
845
846 4 ▶ my $op = ($e->operator eq 'STRSTARTS') ? '=' : '>=';
Branch: 1 branch
BranchTrueFalseTotal
$e->operator eq 'STRSTARTS' ? : 4 0 4
847 4 ▶ if ($db eq 'mysql') {
Branch: 3 branches
BranchTrueFalseTotal
if ($db eq 'mysql') { } 0 4 4
elsif ($db eq 'postgresql') { } 0 4 4
elsif ($db eq 'sqlite') { } 4 0 4
848 0 push(@{ $plan->where }, "LOCATE(?, $termtable.value) ${op} ?");
849 0 push(@{ $plan->bindings }, 'literal');
850 0 push(@{ $plan->bindings }, $literal->value);
851 0 push(@{ $plan->bindings }, 1);
852 } elsif ($db eq 'postgresql') {
853 0 push(@{ $plan->where }, "STRPOS($termtable.value, ?) ${op} ?");
854 0 push(@{ $plan->bindings }, 'literal');
855 0 push(@{ $plan->bindings }, $literal->value);
856 0 push(@{ $plan->bindings }, 1);
857 } elsif ($db eq 'sqlite') {
858 4 push(@{ $plan->where }, "INSTR($termtable.value, ?) ${op} 1");
859 4 push(@{ $plan->bindings }, 'literal');
860 4 push(@{ $plan->bindings }, $literal->value);
861 }
862
863 4 ▶ if (my $lang = $literal->lang_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $lang = $literal->lang_dir) { } 2 2 4
864 2 push(@{ $plan->where }, "$termtable.language = ?");
865 2 push(@{ $plan->bindings }, $lang);
866 } else {
867 2 my $xs = Attean::IRI->new( value => 'http://www.w3.org/2001/XMLSchema#string' );
868 2 my $la = Attean::IRI->new( value => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString' );
869 2 my $xid = $self->_get_term_id($xs);
870 2 my $lid = $self->_get_term_id($la);
871 2 push(@{ $plan->where }, "$termtable.datatype_id IN (?, ?)");
872 2 push(@{ $plan->bindings }, $xid, $lid);
873 }
874 4 return $plan;
875 }
876 }
877 }
878 }
879 }
880 }
881 9 ▶ } elsif ($algebra->isa('Attean::Algebra::BGP') and scalar(@{ $algebra->triples }) > 0) {
Condition66%2/3
$algebra->isa("Attean::Algebra::BGP") and scalar @{$algebra->triples;} > 0
!ll&&!rl&&r
1809
MC/DC50%1/2
$algebra->isa("Attean::Algebra::BGP") and scalar @{$algebra->triples;} > 0
$algebra->isa("Attean::Algebra::BGP") scalar @{$algebra->triples;} > 0
Truth table66%2/3
A and B
A= $algebra->isa("Attean::Algebra::BGP")B= scalar @{$algebra->triples;} > 0
ABresult
0X0
100
111
882 9 my @vars = $algebra->in_scope_variables;
883
884 9 my @triples = @{ $algebra->triples };
885 9 my @select;
886 my @where_joins;
887 9 my %seen_vars;
888 9 my %source_table_for_var;
889 9 my %blanks;
890 9 my $tcounter = 0;
891 9 my $bcounter = 0;
892 9 my @tables;
893
894 my %rename_mapping;
895 36 ▶ my $rename_proj = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
896 36 my $name = shift;
897 36 ▶ if ($name =~ /[-._]|\W/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /[-._]|\W/u) 9 27 36
898 9 my $old = $name;
899 9 $name =~ s/_/__/g;
900 9 $name =~ s/([-.]|\W)/_d/g;
901 0 $name =~ s/([-.]|\W)/'_x' . sprintf('%02x', ord($1))/e;
902 9 $rename_mapping{$old} = $name;
903 }
904
905 36 return $name;
906 9 };
907
908 9 ▶ Carp::confess Dumper($active_graphs) unless (ref($active_graphs) eq 'ARRAY');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $active_graphs eq "ARRAY" 0 9 9
909
910 9 my @graph_ids = map { $self->_get_term_id($_) } @{ $active_graphs };
911 9 ▶ if (any { not defined($_) } @graph_ids) {
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
if (&any(sub { not defined $_; } , @graph_ids)) 0 9 9
912 0 return;
913 }
914
915 9 my @bind;
916 9 my $graph = Attean::Variable->new(value => '___g');
917 9 $seen_vars{ $graph->value }++;
918 9 my @where;
919 9 ▶ if (scalar(@graph_ids)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @graph_ids) { } 9 0 9
920 9 my $graph_values = sprintf('(%s)', join(', ', ('?') x scalar(@graph_ids)));
921 9 push(@bind, @graph_ids);
922 9 push(@where, "t0.graph IN $graph_values");
923 } else {
924 0 push(@where, "0");
925 }
926
927 9 foreach my $t (@triples) {
928 9 my $table = 't' . $tcounter++;
929 9 push(@tables, ['quad', $table]);
930  
931 9 my @vars;
932 9 my $q = $t->as_quadpattern($graph);
933 9 my @nodes = $q->values;
934 9 foreach my $i (0 .. $#nodes) {
935 36 my $node = $nodes[$i];
936 36 my $name = $pos_names[$i];
937 36 ▶ if ($node->does('Attean::API::Variable')) {
Branch: 3 branches
BranchTrueFalseTotal
if ($node->does('Attean::API::Variable')) { } 36 0 36
elsif ($node->does('Attean::API::TriplePattern') and not $node->is_ground) { } 0 0 0
elsif ($node->does('Attean::API::Blank')) { } 0 0 0
938  
939 36 my $var = $node;
940 36 push(@vars, [$var, $name]);
941 ▶ } elsif ($node->does('Attean::API::TriplePattern') and not $node->is_ground) {
Condition0%0/3
$node->does("Attean::API::TriplePattern") and not $node->is_ground
!ll&&!rl&&r
000
MC/DC0%0/2
$node->does("Attean::API::TriplePattern") and not $node->is_ground
$node->does("Attean::API::TriplePattern") not $node->is_ground
Truth table0%0/3
A and not(B)
A= $node->does("Attean::API::TriplePattern")B= not $node->is_ground
ABresult
0X0
100
111
942 0 return; # cannot plan this efficiently
943 } elsif ($node->does('Attean::API::Blank')) {
944 0 my $id = $node->value;
945 0 ▶ unless (exists $blanks{$id}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $blanks{$id}) 0 0 0
946 0 my $bname = sprintf('.%s_%d', 'blank', $bcounter++);
947 0 $blanks{$id} = Attean::Variable->new(value => $bname);
948 }
949 0 my $var = $blanks{$id};
950 0 push(@vars, [$var, $name]);
951 0 $seen_vars{ $var->value }++;
952 } else {
953 0 my $id = $self->_get_term_id($node);
954 0 ▶ return unless defined($id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 0 0 0
955 0 push(@where, sprintf('%s.%s = ?', $table, $name));
956 0 push(@bind, $id);
957 }
958 }
959
960 9 foreach my $vdata (@vars) {
961 36 my ($var, $name) = @$vdata;
962 36 my $var_name = $rename_proj->( $var->value );
963 36 ▶ push(@select, [$table, $name, $var_name]) unless ($seen_vars{$var->value}++);
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_vars{$var->value}++ 27 9 36
964 36 ▶ if (my $tt = $source_table_for_var{ $var->value }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tt = $source_table_for_var{$var->value}) { } 0 36 36
965 0 push(@where_joins, ['=', $tt, [$table, $name]]);
966 } else {
967 36 $source_table_for_var{ $var->value } = [$table, $name];
968 }
969 }
970 }
971
972 9 foreach my $w (@where_joins) {
973 0 my ($op, $a, $b) = @$w;
974 0 my ($as, $bs) = map { sprintf('%s.%s', @$_) } ($a, $b);
975 0 push(@where, join(' ', $as, $op, $bs));
976 }
977  
978 9 return AtteanX::Store::DBI::Plan->new(
979 store => $self,
980 select => \@select,
981 where => \@where,
982 tables => \@tables,
983 in_scope_variables => [@vars],
984 rename_mapping => \%rename_mapping,
985 bindings => \@bind,
986 variables => \%source_table_for_var,
987 );
988 }
989  
990 19 return;
991 }
992  
993 =item C<< cost_for_plan( $plan ) >>
994  
995 Returns the estimated cost for a DBI-specific query plan, undef otherwise.
996  
997 =cut
998  
999 sub cost_for_plan {
1000 my $self = shift;
1001 my $plan = shift;
1002 if ($plan->isa('AtteanX::Store::DBI::Plan')) {
1003 return 1; # TODO: actually estimate cost here
1004 }
1005 return;
1006 }
1007  
1008 0 ▶sub _dump_database {
Subroutine _dump_database: not called CC=1 SCAR=6.9
1009 0 my $self = shift;
1010 0 $self->_dump_dictionary;
1011 0 $self->_dump_quads;
1012 }
1013  
1014 0 ▶sub _dump_dictionary {
Subroutine _dump_dictionary: not called CC=2 SCAR=14.9
1015 0 my $self = shift;
1016 0 my $dbh = $self->dbh;
1017 3 ▶ use Text::Table;
Subroutine BEGIN: called CC=1 SCAR=0.0
1018 0 my @headers = qw(term_id type datatype_id value language);
1019 0 my $table = Text::Table->new(@headers);
1020 0 my @rows;
1021 0 my $sql = 'SELECT term_id, type, datatype_id, value, language FROM term';
1022 0 my $sth = $dbh->prepare($sql);
1023 0 $sth->execute();
1024 0 ▶ while (my $row = $sth->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_arrayref) 0 0 0
1025 0 push(@rows, [@$row]);
1026 }
1027 0 $table->load(@rows);
1028 0 my @rule = qw(- +);
1029 0 warn "[[[ DICTIONARY ]]]\n";
1030 warn join('',
1031 $table->rule(@rule),
1032 $table->title,
1033 $table->rule(@rule),
1034 0 map({ $table->body($_) } 0 .. @rows),
1035 $table->rule(@rule)
1036 );
1037 }
1038  
1039 0 ▶sub _dump_quads {
Subroutine _dump_quads: not called CC=2 SCAR=14.9
1040 0 my $self = shift;
1041 0 my $dbh = $self->dbh;
1042 3 ▶ use Text::Table;
Subroutine BEGIN: called CC=1 SCAR=0.0
1043 0 my @headers = qw(subject predicate object graph);
1044 0 my $table = Text::Table->new(@headers);
1045 0 my @rows;
1046 0 my $sql = 'SELECT subject, predicate, object, graph FROM quad';
1047 0 my $sth = $dbh->prepare($sql);
1048 0 $sth->execute();
1049 0 ▶ while (my $row = $sth->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_arrayref) 0 0 0
1050 0 push(@rows, [@$row]);
1051 }
1052 0 $table->load(@rows);
1053 0 my @rule = qw(- +);
1054 0 warn "[[[ QUADS ]]]\n";
1055 warn join('',
1056 $table->rule(@rule),
1057 $table->title,
1058 $table->rule(@rule),
1059 0 map({ $table->body($_) } 0 .. @rows),
1060 $table->rule(@rule)
1061 );
1062 }
1063  
1064 }
1065  
1066 3 package AtteanX::Store::DBI::Plan 0.012 {
1067 3 ▶ use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
1068 3 ▶ use Type::Tiny::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
1069 3 ▶ use Types::Standard qw(HashRef ArrayRef InstanceOf Str);
Subroutine BEGIN: called CC=1 SCAR=0.0
1070 3 ▶ use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
1071
1072 3 has store => (is => 'ro', isa => InstanceOf['AtteanX::Store::DBI'], required => 1);
1073 0 ▶ has rename_mapping => (is => 'ro', isa => HashRef[Str], default => sub { +{} });
Subroutine __ANON__: not called CC=1 SCAR=1.2
1074 3 has variables => (is => 'ro', isa => HashRef, required => 1);
1075 3 has bindings => (is => 'ro', isa => ArrayRef, required => 1);
1076 3 has select => (is => 'ro', isa => ArrayRef, required => 1);
1077 3 has where => (is => 'ro', isa => ArrayRef, required => 1);
1078 3 has tables => (is => 'ro', isa => ArrayRef[ArrayRef[Str]], required => 1);
1079
1080 3 with 'Attean::API::BindingSubstitutionPlan', 'Attean::API::NullaryQueryTree';
1081
1082 0 ▶ sub plan_as_string {
Subroutine plan_as_string: not called CC=1 SCAR=6.9
Pod undocumented
1083 0 my $self = shift;
1084 0 my ($sql, @bind) = $self->sql();
1085 0 return sprintf('DBI BGP { %s ← (%s) }', $sql, join(', ', @bind));
1086 }
1087
1088 10 ▶ sub sql {
Subroutine sql: called CC=7 SCAR=21.0
Pod undocumented
1089 10 my $self = shift;
1090 10 my $bind = shift;
1091 10 my $store = $self->store;
1092 10 my $dbh = $store->dbh;
1093 10 my @bind = @{ $self->bindings };
1094 10 my @where = @{ $self->where };
1095 10 ▶ if ($bind) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bind) 3 7 10
1096 3 foreach my $var ($bind->variables) {
1097 0 my $id = $store->_get_term_id($bind->value($var));
1098 0 ▶ return unless defined($id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 0 0 0
1099 0 ▶ if (my $cdata = $self->variables->{ $var }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cdata = $self->variables->{$var}) 0 0 0
1100 0 my ($table, $col) = @$cdata;
1101 0 push(@where, sprintf("%s.%s = ?", $table, $col));
1102 0 push(@bind, $id);
1103 }
1104 }
1105 }
1106
1107 10 my @select = map { sprintf("%s.%s AS %s", map { $dbh->quote_identifier( $_ ) } @$_) } @{ $self->select };
1108 10 ▶ unless (scalar(@select)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @select) 0 10 10
1109 0 push(@select, '1');
1110 }
1111
1112
1113 10 my @sql;
1114 10 push(@sql, 'SELECT');
1115 10 push(@sql, join(', ', @select));
1116  
1117 10 push(@sql, 'FROM');
1118 10 push(@sql, join(', ', map { join(' ', @$_) } @{ $self->tables }));
1119  
1120 10 ▶ if (scalar(@where)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @where) 10 0 10
1121 10 push(@sql, 'WHERE');
1122 10 push(@sql, join(' AND ', map { "($_)" } @where));
1123 }
1124
1125 10 my $sql = join(" ", @sql);
1126 10 return ($sql, @bind);
1127 }
1128
1129 3 ▶ sub substitute_impl {
Subroutine substitute_impl: called CC=1 SCAR=0.0
Pod undocumented
1130 3 my $self = shift;
1131 3 my $model = shift;
1132 3 my ($sql, @bind) = $self->sql(@_);
1133 3 my $store = $self->store;
1134 3 my $dbh = $store->dbh;
1135  
1136 # warn "TODO: generatee SQL for BGP: $sql\n";
1137 # warn "======================================================================\n";
1138 # warn "$sql\n";
1139 # warn "======================================================================\n";
1140  
1141 3 my $vars = $self->in_scope_variables;
1142 3 my $sth = $dbh->prepare($sql);
1143 3 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
1144 # warn "Generating impl by executing SQL";
1145 3 my $rv = $sth->execute(@bind);
1146 3 ▶ unless ($rv) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rv) 0 3 3
1147 0 warn '*** SQL error: ' . $sth->errstr;
1148 0 die;
1149 }
1150 10 ▶ my $sub = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
1151 # warn '=== Iterator invoked';
1152 # use Data::Dumper;
1153 # warn Dumper($sql, \@bind);
1154 10 ▶ if (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) { } 7 3 10
1155 # warn '@@@ Iterator got row';
1156 # warn Dumper($row);
1157
1158 7 my %bindings;
1159 7 foreach my $k (@$vars) {
1160 21 ▶ my $key = $self->rename_mapping->{$k} // $k;
Condition33%1/3
$self->rename_mapping->{$k} // $k
l!l&&r!l&&!r
0210
MC/DC0%0/2
$self->rename_mapping->{$k} // $k
$self->rename_mapping->{$k} $k
Truth table33%1/3
A // B
A= $self->rename_mapping->{$k}B= $k
ABresult
1X1
011
000
1161 21 my $term = $store->_get_term($row->{$key});
1162 21 $bindings{$k} = $term;
1163 }
1164 7 my $r = Attean::Result->new( bindings => \%bindings );
1165 7 return $r;
1166 } else {
1167 # warn '^^^ Reached end-of-iterator'
1168 }
1169 3 return;
1170 3 };
1171 3 return Attean::CodeIterator->new( generator => $sub, item_type => 'Attean::API::Result', variables => $vars );
1172 3 };
1173 }
1174
1175 }
1176  
1177 3 1;
1178  
1179 __END__
↑ Summary Test/AtteanX/Store/DBI.pm »