RDF/Trine/Store/DBI.pm

filter: Statementstmt 76.7% 641 / 835 Branchbran 73.1% 215 / 294 Conditioncond 43.1% 25 / 58 MC/DCmcdc 36.3% 12 / 33 Subroutinesub 80.9% 72 / 89 Podpod 100% 21 / 21 totaltotal 74.1% 986 / 1330 CC 188 SCAR 29.6
CC
188
Cov
74%
_sql_for_expr
210.0
_sql_for_equality_expr
30.0
_logical_or_operands
20.0
CRAP 19.3
« RDF/Trine/Store/Dydra.pm ↑ Summary RDF/Trine/Parser/NTriples.pm »
1 =head1 NAME
2  
3 RDF::Trine::Store::DBI - Persistent RDF storage based on DBI
4  
5 =head1 VERSION
6  
7 This document describes RDF::Trine::Store::DBI version 1.019
8  
9 =head1 SYNOPSIS
10  
11 use RDF::Trine::Store::DBI;
12
13 my $user = 'me';
14 my $pass = 'secret';
15 my $modelname = 'mymodel';
16  
17 # First, construct a DBI connection to your database
18 my $dsn = "DBI:mysql:database=perlrdf";
19 my $dbh = DBI->connect( $dsn, $user, $pass );
20
21 # Second, create a new Store object with the database connection
22 # and specifying (by name) which model in the Store you want to use
23 my $store = RDF::Trine::Store::DBI->new( $modelname, $dbh );
24
25 # Finally, wrap the Store objec into a Model, and use it to access your data
26 my $model = RDF::Trine::Model->new($store);
27 print $model->size . " RDF statements in store\n";
28  
29 =head1 DESCRIPTION
30  
31 RDF::Trine::Store::DBI provides a persistent triple-store using the L<DBI|DBI>
32 module.
33  
34 =cut
35  
36 package RDF::Trine::Store::DBI;
37  
38 68 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 68 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 68 ▶no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
41 68 ▶use base qw(RDF::Trine::Store);
Subroutine BEGIN: called CC=1 SCAR=0.0
42  
43 68 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 68 ▶use DBIx::Connector;
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 68 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 68 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 68 ▶use Scalar::Util qw(blessed reftype refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
49 68 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 68 ▶use Digest::MD5 ('md5');
Subroutine BEGIN: called CC=1 SCAR=0.0
51 68 ▶use Math::BigInt;
Subroutine BEGIN: called CC=1 SCAR=0.0
52 68 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
53 68 ▶use RDF::Trine::Node;
Subroutine BEGIN: called CC=1 SCAR=0.0
54 68 ▶use RDF::Trine::Statement;
Subroutine BEGIN: called CC=1 SCAR=0.0
55 68 ▶use RDF::Trine::Statement::Quad;
Subroutine BEGIN: called CC=1 SCAR=0.0
56 68 ▶use RDF::Trine::Iterator;
Subroutine BEGIN: called CC=1 SCAR=0.0
57 68 ▶use Log::Log4perl;
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 68 ▶use RDF::Trine::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 68 ▶use RDF::Trine::Store::DBI::mysql;
Subroutine BEGIN: called CC=1 SCAR=0.0
61 68 ▶use RDF::Trine::Store::DBI::SQLite;
Subroutine BEGIN: called CC=1 SCAR=0.0
62 68 ▶use RDF::Trine::Store::DBI::Pg;
Subroutine BEGIN: called CC=1 SCAR=0.0
63  
64 ######################################################################
65  
66 68 our $VERSION;
67 68 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
68 68 $VERSION = "1.019";
69 68 my $class = __PACKAGE__;
70 68 $RDF::Trine::Store::STORE_CLASSES{ $class } = $VERSION;
71 }
72  
73 ######################################################################
74  
75 =head1 METHODS
76  
77 Beyond the methods documented below, this class inherits methods from the
78 L<RDF::Trine::Store> class.
79  
80 =over 4
81  
82 =item C<new ( $model_name, $dbh )>
83  
84 =item C<new ( $model_name, $dsn, $user, $pass )>
85  
86 Returns a new storage object using the supplied arguments to construct a DBI
87 object for the underlying database.
88  
89 =item C<new_with_config ( $hashref )>
90  
91 Returns a new storage object configured with a hashref with certain
92 keys as arguments.
93  
94 The C<storetype> key must be C<DBI> for this backend.
95  
96 These keys should also be used:
97  
98 =over
99  
100 =item C<name>
101  
102 The name of the model.
103  
104 =item C<dsn>
105  
106 The DBI Data Source Name for the underlying database.
107  
108 =item C<username>
109  
110 The username of the database user.
111  
112 =item C<password>
113  
114 The password of the database user.
115  
116 =back
117  
118 =item C<new_with_object ( $dbi_db )>
119  
120 Initialize the store with a L<DBI::db> object.
121  
122 =cut
123  
124 11 ▶sub new {
Subroutine new: called CC=14 SCAR=28.9
Pod documented
125 11 my $class = shift;
126 11 my ($dbh, $conn);
127
128 11 my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
129
130 11 ▶ my $name = shift || 'model';
Condition100%2/2
shift() || 'model'
l!l
92
MC/DC100%1/1
shift() || 'model'
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
131 11 my %args;
132 11 ▶ if (scalar(@_) == 0) {
Branch: 3 branches
BranchTrueFalseTotal
if (scalar @_ == 0) { } 9 2 11
elsif (builtin::blessed($_[0]) and $_[0]->isa('DBI::db')) { } 1 1 2
elsif (builtin::blessed($_[0]) and $_[0]->isa('DBIx::Connector')) { } 0 1 1
133 9 $l->trace("trying to construct a temporary model");
134 9 my $dsn = "dbi:SQLite:dbname=:memory:";
135 9 $conn = DBIx::Connector->new( $dsn, '', '' );
136 9 $class = 'RDF::Trine::Store::DBI::SQLite';
137 ▶ } elsif (blessed($_[0]) and $_[0]->isa('DBI::db')) {
Condition66%2/3
builtin::blessed($_[0]) and $_[0]->isa("DBI::db")
!ll&&!rl&&r
101
MC/DC50%1/2
builtin::blessed($_[0]) and $_[0]->isa("DBI::db")
builtin::blessed($_[0]) $_[0]->isa("DBI::db")
Truth table66%2/3
A and B
A= builtin::blessed($_[0])B= $_[0]->isa("DBI::db")
ABresult
0X0
100
111
138 1 $l->trace("got a DBD handle");
139 1 $dbh = shift;
140 1 my $name = $dbh->get_info(17);
141 1 ▶ if ($name eq 'MySQL') {
Branch: 3 branches
BranchTrueFalseTotal
if ($name eq 'MySQL') { } 0 1 1
elsif ($name eq 'PostgreSQL') { } 0 1 1
elsif ($name eq 'SQLite') { } 1 0 1
142 0 $class = 'RDF::Trine::Store::DBI::mysql';
143 } elsif ($name eq 'PostgreSQL') {
144 0 $class = 'RDF::Trine::Store::DBI::Pg';
145 } elsif ($name eq 'SQLite') {
146 1 $class = 'RDF::Trine::Store::DBI::SQLite';
147 }
148 ▶ } elsif (blessed($_[0]) and $_[0]->isa('DBIx::Connector')) {
Condition33%1/3
builtin::blessed($_[0]) and $_[0]->isa("DBIx::Connector")
!ll&&!rl&&r
100
MC/DC0%0/2
builtin::blessed($_[0]) and $_[0]->isa("DBIx::Connector")
builtin::blessed($_[0]) $_[0]->isa("DBIx::Connector")
Truth table33%1/3
A and B
A= builtin::blessed($_[0])B= $_[0]->isa("DBIx::Connector")
ABresult
0X0
100
111
149 0 $conn = shift;
150 } else {
151 1 my $dsn = shift;
152 1 my $user = shift;
153 1 my $pass = shift;
154 1 ▶ if ($dsn =~ /^DBI:mysql:/i) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dsn =~ /^DBI:mysql:/i) { } 0 1 1
elsif ($dsn =~ /^DBI:Pg:/i) { } 0 1 1
elsif ($dsn =~ /^DBI:SQLite:/i) { } 1 0 1
155 0 $class = 'RDF::Trine::Store::DBI::mysql';
156 } elsif ($dsn =~ /^DBI:Pg:/i) {
157 0 $class = 'RDF::Trine::Store::DBI::Pg';
158 } elsif ($dsn =~ /^DBI:SQLite:/i) {
159 1 $class = 'RDF::Trine::Store::DBI::SQLite';
160 1 $user = '';
161 1 $pass = '';
162 }
163 1 $l->trace("Connecting to $dsn ($user, $pass)");
164 1 $conn = DBIx::Connector->new( $dsn, $user, $pass );
165 1 ▶ unless ($conn) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($conn) 0 1 1
166 0 throw RDF::Trine::Error::DatabaseError -text => "Couldn't connect to database: " . DBI->errstr;
167 }
168 }
169
170 11 my $self = bless( {
171 model_name => $name,
172 dbh => $dbh,
173 conn => $conn,
174 statements_table_prefix => 'Statements',
175 %args
176 }, $class );
177 11 $self->init();
178 11 return $self;
179 }
180  
181 0 ▶sub _new_with_string {
Subroutine _new_with_string: not called CC=1 SCAR=6.9
182 0 my $class = shift;
183 0 my $config = shift;
184 0 my ($model, $dsn, $user, $pass) = split(';', $config);
185 0 return $class->new( $model, $dsn, $user, $pass );
186 }
187  
188 0 ▶sub _new_with_config {
Subroutine _new_with_config: not called CC=1 SCAR=6.9
189 0 my $class = shift;
190 0 my $config = shift;
191 return $class->new( $config->{name},
192 $config->{dsn},
193 $config->{username},
194 0 $config->{password} );
195 }
196  
197 0 ▶sub _new_with_object {
Subroutine _new_with_object: not called CC=3 SCAR=24.8
198 0 my $class = shift;
199 0 my $obj = shift;
200 0 ▶ return unless (blessed($obj) and $obj->isa('DBI::db'));
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($obj) and $obj->isa("DBI::db") 0 0 0
Condition0%0/3
builtin::blessed($obj) and $obj->isa("DBI::db")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($obj) and $obj->isa("DBI::db")
builtin::blessed($obj) $obj->isa("DBI::db")
Truth table0%0/3
A and B
A= builtin::blessed($obj)B= $obj->isa("DBI::db")
ABresult
0X0
100
111
201 0 return $class->new( $obj );
202 }
203  
204 =item C<< nuke >>
205  
206 Permanently removes the store and its data. Note that because of this module's
207 use of the Redland schema, removing a store with this method will only delete
208 the Statements table and remove the model's entry in the Models table. The node
209 entries in the Literals, Bnodes, and Resources tables will still exist.
210  
211 =cut
212  
213 0 ▶sub nuke {
Subroutine nuke: not called CC=3 SCAR=24.8
Pod documented
214 0 my $self = shift;
215 0 my $dbh = $self->dbh;
216 0 my $name = $self->model_name;
217 0 my $id = $self->_mysql_hash( $name );
218 0 my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
219
220 0 ▶ $dbh->do( "DROP TABLE Statements${id};" ) || do { $l->trace( $dbh->errstr ); return };
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do("DROP TABLE Statements$id;") or do { $l->trace($dbh->errstr); return } 0 0 0
221 0 ▶ $dbh->do( "DELETE FROM Models WHERE ID = ${id}") || do { $l->trace( $dbh->errstr ); $dbh->rollback; return };
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do("DELETE FROM Models WHERE ID = $id") or do { $l->trace($dbh->errstr); $dbh->rollback; return } 0 0 0
222 }
223  
224 =item C<< supports ( [ $feature ] ) >>
225  
226 If C<< $feature >> is specified, returns true if the feature is supported by the
227 store, false otherwise. If C<< $feature >> is not specified, returns a list of
228 supported features.
229  
230 =cut
231  
232 0 ▶sub supports {
Subroutine supports: not called CC=1 SCAR=6.9
Pod documented
233 0 return;
234 }
235  
236 =item C<< temporary_store >>
237  
238 =cut
239  
240 2 ▶sub temporary_store {
Subroutine temporary_store: called CC=1 SCAR=0.0
Pod documented
241 2 my $class = shift;
242 2 my $name = 'model_' . sprintf( '%x%x%x%x', map { int(rand(16)) } (1..4) );
243 2 my $self = $class->new( $name, @_ );
244 2 $self->{ remove_store } = 1;
245 2 $self->init();
246 2 return $self;
247 }
248  
249 =item C<< clear_restrictions >>
250  
251 Clear's the restrictions put on the binding of node types to the different
252 statement positions. By default, the subject position is restricted to resources
253 and blank nodes, and the predicate position to only resources. Calling this
254 method will allow any node type in any statement position.
255  
256 =cut
257  
258 0 ▶sub clear_restrictions {
Subroutine clear_restrictions: not called CC=2 SCAR=17.9
Pod documented
259 0 my $self = shift;
260 0 foreach my $pos (qw(subject predicate object context)) {
261 0 $self->{restrictions}{$pos} = [];
262 }
263 0 return;
264 }
265  
266 =item C<< get_statements ($subject, $predicate, $object [, $context] ) >>
267  
268 Returns a stream object of all statements matching the specified subject,
269 predicate and objects. Any of the arguments may be undef to match any value.
270  
271 =cut
272  
273 81 ▶sub get_statements {
Subroutine get_statements: called CC=10 SCAR=23.0
Pod documented
274 81 my $self = shift;
275 81 my @nodes = @_[0..3];
276 81 my $bound = 0;
277 81 my %bound;
278
279 81 my $use_quad = 0;
280 81 ▶ if (scalar(@_) >= 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ >= 4) 63 18 81
281 63 $use_quad = 1;
282 # warn "count statements with quad" if ($::debug);
283 63 my $g = $nodes[3];
284 63 ▶ if (blessed($g) and not($g->is_variable)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($g) and not $g->is_variable) 4 59 63
Condition100%3/3
builtin::blessed($g) and not $g->is_variable
!ll&&!rl&&r
5724
MC/DC100%2/2
builtin::blessed($g) and not $g->is_variable
builtin::blessed($g) not $g->is_variable
Truth table100%3/3
A and not(B)
A= builtin::blessed($g)B= not $g->is_variable
ABresult
0X0
100
111
285 4 $bound++;
286 4 $bound{ 3 } = $g;
287 }
288 }
289
290 81 my ($subj, $pred, $obj, $context) = @nodes;
291
292 81 my $var = 0;
293 81 my $dbh = $self->dbh;
294 my $st = ($use_quad)
295 252 ▶ ? RDF::Trine::Statement::Quad->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj,$context) )
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 83 169 252
296 81 ▶ : RDF::Trine::Statement->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj) );
Branch: 2 branches
BranchTrueFalseTotal
$use_quad ? : 63 18 81
defined $_ ? : 44 10 54
297
298 81 my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
299
300 81 my @vars = $st->referenced_variables;
301
302 81 ▶ my $semantics = ($use_quad ? 'quad' : 'triple');
Branch: 1 branch
BranchTrueFalseTotal
$use_quad ? : 63 18 81
303 81 local($self->{context_variable_count}) = 0;
304 81 ▶ local($self->{join_context_nodes}) = 1 if (blessed($context) and $context->is_variable);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($context) and $context->is_variable 2 79 81
Condition100%3/3
builtin::blessed($context) and $context->is_variable
!ll&&!rl&&r
7542
MC/DC100%2/2
builtin::blessed($context) and $context->is_variable
builtin::blessed($context) $context->is_variable
Truth table100%3/3
A and B
A= builtin::blessed($context)B= $context->is_variable
ABresult
0X0
100
111
305 81 my $sql = $self->_sql_for_pattern( $st, $context, semantics => $semantics, unique => 1 );
306 81 my $sth = $dbh->prepare( $sql );
307
308 81 $sth->execute();
309
310 663 ▶ my $sub = sub {
Subroutine __ANON__: called CC=10 SCAR=23.1
311 663 NEXTROW:
312 my $row = $sth->fetchrow_hashref;
313 663 ▶ return unless (defined $row);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 72 591 663
314 591 my @triple;
315 591 my $temp_var_count = 1;
316 591 ▶ my @nodes = ($st->nodes)[ $use_quad ? (0..3) : (0..2) ];
Branch: 1 branch
BranchTrueFalseTotal
$use_quad ? : 504 87 591
317 591 foreach my $node (@nodes) {
318 2277 ▶ if ($node->is_variable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->is_variable) { } 1933 344 2277
319 1933 my $nodename = $node->name;
320 1933 my $uri = $self->_column_name( $nodename, 'URI' );
321 1933 my $name = $self->_column_name( $nodename, 'Name' );
322 1933 my $value = $self->_column_name( $nodename, 'Value' );
323 1933 my $node = $self->_column_name( $nodename, 'Node' );
324 1933 ▶ if ($row->{ $node } == 0) {
Branch: 4 branches
BranchTrueFalseTotal
if ($row->{$node} == 0) { } 158 1775 1933
elsif (defined(my $u = $row->{$uri})) { } 1704 71 1775
elsif (defined(my $n = $row->{$name})) { } 29 42 71
elsif (defined(my $v = $row->{$value})) { } 42 0 42
325 158 push( @triple, RDF::Trine::Node::Nil->new() );
326 } elsif (defined( my $u = $row->{ $uri })) {
327 1704 $u = decode('utf8', $u);
328 1704 push( @triple, RDF::Trine::Node::Resource->new( $u ) );
329 } elsif (defined( my $n = $row->{ $name })) {
330 29 push( @triple, RDF::Trine::Node::Blank->new( $n ) );
331 } elsif (defined( my $v = $row->{ $value })) {
332 42 my @cols = map { $self->_column_name( $nodename, $_ ) } qw(Value Language Datatype);
333 42 $cols[0] = decode('utf8', $cols[0]);
334 42 $cols[2] = decode('utf8', $cols[2]);
335 42 push( @triple, RDF::Trine::Node::Literal->new( @{ $row }{ @cols } ) );
336 } else {
337 0 warn "node isn't nil or a resource, blank, or literal?" . Dumper($row);
338 0 goto NEXTROW;
339 }
340 } else {
341 344 push(@triple, $node);
342 }
343 }
344
345 591 ▶ my $st = (@triple == 3)
Branch: 1 branch
BranchTrueFalseTotal
@triple == 3 ? : 87 504 591
346 ? RDF::Trine::Statement->new( @triple )
347 : RDF::Trine::Statement::Quad->new( @triple );
348 591 return $st;
349 81 };
350
351 81 return RDF::Trine::Iterator::Graph->new( $sub )
352 }
353  
354 8526 ▶sub _column_name {
Subroutine _column_name: called CC=1 SCAR=0.0
355 8526 my $self = shift;
356 8526 my @args = @_;
357 8526 my $col = join('_', @args);
358 8526 return $col;
359 }
360  
361 =item C<< get_pattern ( $bgp [, $context] ) >>
362  
363 Returns a stream object of all bindings matching the specified graph pattern.
364  
365 =cut
366  
367 39 ▶sub get_pattern {
Subroutine get_pattern: called CC=7 SCAR=19.5
Pod documented
368 39 my $self = shift;
369 39 my $pattern = shift;
370 39 my $context = shift;
371 39 my %args = @_;
372
373 39 my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
374 39 $l->trace("get_pattern called for: " . $pattern->sse);
375
376 39 ▶ if (my $o = $args{ orderby }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $o = $args{"orderby"}) 19 20 39
377 19 my @ordering = @$o;
378 19 ▶ while (my ($col, $dir) = splice( @ordering, 0, 2, () )) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@ordering, 0, 2, ())) 30 16 46
379 68 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
380 30 ▶ unless ($dir =~ /^(ASC|DESC)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dir =~ /^(ASC|DESC)$/) 3 27 30
381 3 throw RDF::Trine::Error::MethodInvocationError -text => "The sort direction for key $col must be either 'ASC' or 'DESC' in get_pattern call";
382 }
383 }
384 }
385
386 36 my $dbh = $self->dbh;
387 36 my @vars = $pattern->referenced_variables;
388 36 my %vars = map { $_ => 1 } @vars;
389
390 36 my $sql = $self->_sql_for_pattern( $pattern, $context, %args );
391 36 $l->debug("get_pattern sql: $sql\n");
392
393 36 my $sth = $dbh->prepare( $sql );
394 36 $sth->execute();
395
396 110 ▶ my $sub = sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
397 110 my $row = $sth->fetchrow_hashref;
398 110 ▶ return unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 32 78 110
399
400 78 my %bindings;
401 78 foreach my $nodename (@vars) {
402 164 my $uri = $self->_column_name( $nodename, 'URI' );
403 164 my $name = $self->_column_name( $nodename, 'Name' );
404 164 my $value = $self->_column_name( $nodename, 'Value' );
405 164 ▶ if (defined( my $u = $row->{ $uri })) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined(my $u = $row->{$uri})) { } 80 84 164
elsif (defined(my $n = $row->{$name})) { } 20 64 84
elsif (defined(my $v = $row->{$value})) { } 48 16 64
406 80 $u = decode('utf8', $u);
407 80 $bindings{ $nodename } = RDF::Trine::Node::Resource->new( $u );
408 } elsif (defined( my $n = $row->{ $name })) {
409 20 $bindings{ $nodename } = RDF::Trine::Node::Blank->new( $n );
410 } elsif (defined( my $v = $row->{ $value })) {
411 48 my @cols = map { $self->_column_name( $nodename, $_ ) } qw(Value Language Datatype);
412 48 my ($val,$lang,$dt) = @{ $row }{ @cols };
413 48 $val = decode('utf8', $val);
414 48 $dt = decode('utf8', $dt);
415 48 $bindings{ $nodename } = RDF::Trine::Node::Literal->new( $val, $lang, $dt );
416 } else {
417 16 $bindings{ $nodename } = undef;
418 }
419 }
420 78 return RDF::Trine::VariableBindings->new( \%bindings );
421 36 };
422
423 36 my @args;
424 36 ▶ if (my $o = $args{ orderby }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $o = $args{"orderby"}) 16 20 36
425 16 my @ordering = @$o;
426 16 my @realordering;
427 16 ▶ while (my ($col, $dir) = splice( @ordering, 0, 2, () )) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@ordering, 0, 2, ())) 27 16 43
428 27 ▶ if (exists $vars{ $col }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $vars{$col}) 23 4 27
429 23 push(@realordering, $col, $dir);
430 }
431 }
432 16 @args = ( sorted_by => \@realordering );
433 }
434 36 return RDF::Trine::Iterator::Bindings->new( $sub, \@vars, @args )
435 }
436  
437  
438 =item C<< get_contexts >>
439  
440 Returns an RDF::Trine::Iterator over the RDF::Trine::Node objects comprising
441 the set of contexts of the stored quads.
442  
443 =cut
444  
445 2 ▶sub get_contexts {
Subroutine get_contexts: called CC=1 SCAR=0.4
Pod documented
446 2 my $self = shift;
447 2 my $dbh = $self->dbh;
448 2 my $stable = $self->statements_table;
449 2 my $sql = "SELECT DISTINCT Context, r.URI AS URI, b.Name AS Name, l.Value AS Value, l.Language AS Language, l.Datatype AS Datatype FROM ${stable} s LEFT JOIN Resources r ON (r.ID = s.Context) LEFT JOIN Literals l ON (l.ID = s.Context) LEFT JOIN Bnodes b ON (b.ID = s.Context) ORDER BY URI, Name, Value;";
450 2 my $sth = $dbh->prepare( $sql );
451 2 $sth->execute();
452 8 ▶ my $sub = sub {
Subroutine __ANON__: called CC=7 SCAR=23.8
453 8 ▶ while (my $row = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_hashref) 8 2 10
454 8 ▶ return unless defined($row);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 0 8 8
455 8 my $uri = $self->_column_name( 'URI' );
456 8 my $name = $self->_column_name( 'Name' );
457 8 my $value = $self->_column_name( 'Value' );
458 8 my $ctx = $self->_column_name( 'Context' );
459 8 ▶ if ($row->{ $ctx } == 0) {
Branch: 4 branches
BranchTrueFalseTotal
if ($row->{$ctx} == 0) { } 2 6 8
elsif ($row->{$uri}) { } 6 0 6
elsif ($row->{$name}) { } 0 0 0
elsif (defined $row->{$value}) { } 0 0 0
460 2 next;
461 # return RDF::Trine::Node::Nil->new();
462 } elsif ($row->{ $uri }) {
463 6 return RDF::Trine::Node::Resource->new( $row->{ $uri } );
464 } elsif ($row->{ $name }) {
465 0 return RDF::Trine::Node::Blank->new( $row->{ $name } );
466 } elsif (defined $row->{ $value }) {
467 0 my @cols = map { $self->_column_name( $_ ) } qw(Value Language Datatype);
468 0 return RDF::Trine::Node::Literal->new( @{ $row }{ @cols } );
469 } else {
470 0 return;
471 }
472 }
473 2 return;
474 2 };
475 2 return RDF::Trine::Iterator->new( $sub );
476 }
477  
478 =item C<< add_statement ( $statement [, $context] ) >>
479  
480 Adds the specified C<$statement> to the underlying model.
481  
482 =cut
483  
484 297 ▶sub add_statement {
Subroutine add_statement: called CC=5 SCAR=16.1
Pod documented
485 297 my $self = shift;
486 297 my $stmt = shift;
487 297 my $context = shift;
488 297 my $dbh = $self->dbh;
489 # Carp::confess unless (blessed($stmt));
490 297 my $stable = $self->statements_table;
491 297 my @nodes = $stmt->nodes;
492 297 my @values = map { $self->_add_node( $_ ) } @nodes;
493
494 297 ▶ if ($stmt->isa('RDF::Trine::Statement::Quad')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt->isa('RDF::Trine::Statement::Quad')) { } 200 97 297
495 200 ▶ if (blessed($context)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($context)) 2 198 200
496 2 throw RDF::Trine::Error::MethodInvocationError -text => "add_statement cannot be called with both a quad and a context";
497 }
498 198 $context = $stmt->context;
499 } else {
500 97 ▶ push @values, ($context ? $self->_add_node($context) : 0);
Branch: 1 branch
BranchTrueFalseTotal
$context ? : 8 89 97
501 }
502 295 my $sql = "SELECT 1 FROM ${stable} WHERE Subject = ? AND Predicate = ? AND Object = ? AND Context = ?";
503 295 my $sth = $dbh->prepare( $sql );
504 295 $sth->execute( @values );
505 295 ▶ unless ($sth->fetch) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth->fetch) 283 12 295
506 283 my $sql = sprintf( "INSERT INTO ${stable} (Subject, Predicate, Object, Context) VALUES (?,?,?,?)" );
507 283 my $sth = $dbh->prepare( $sql );
508 283 $sth->execute(@values);
509 }
510 }
511  
512 =item C<< remove_statement ( $statement [, $context]) >>
513  
514 Removes the specified C<$statement> from the underlying model.
515  
516 =cut
517  
518 246 ▶sub remove_statement {
Subroutine remove_statement: called CC=5 SCAR=16.1
Pod documented
519 246 my $self = shift;
520 246 my $stmt = shift;
521 246 my $context = shift;
522 246 my $dbh = $self->dbh;
523 246 my $stable = $self->statements_table;
524
525 246 ▶ unless (blessed($stmt)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($stmt)) 0 246 246
526 0 throw RDF::Trine::Error::MethodInvocationError -text => "no statement passed to remove_statement";
527 }
528
529 246 ▶ if ($stmt->isa( 'RDF::Trine::Statement::Quad' )) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stmt->isa('RDF::Trine::Statement::Quad')) { } 178 68 246
530 178 ▶ if (blessed($context)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($context)) 2 176 178
531 2 throw RDF::Trine::Error::MethodInvocationError -text => "remove_statement cannot be called with both a quad and a context";
532 }
533 } else {
534 68 my @nodes = $stmt->nodes;
535 68 ▶ if (blessed($context)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($context)) { } 8 60 68
536 8 $stmt = RDF::Trine::Statement::Quad->new( @nodes[0..2], $context );
537 } else {
538 60 my $nil = RDF::Trine::Node::Nil->new();
539 60 $stmt = RDF::Trine::Statement::Quad->new( @nodes[0..2], $nil );
540 }
541 }
542
543 244 my @nodes = $stmt->nodes;
544 244 my $sth = $dbh->prepare("DELETE FROM ${stable} WHERE Subject = ? AND Predicate = ? AND Object = ? AND Context = ?");
545 244 my @values = map { $self->_mysql_node_hash( $_ ) } (@nodes);
546 244 $sth->execute( @values );
547 }
548  
549 =item C<< remove_statements ( $subject, $predicate, $object [, $context]) >>
550  
551 Removes the specified C<$statement> from the underlying model.
552  
553 =cut
554  
555 12 ▶sub remove_statements {
Subroutine remove_statements: called CC=4 SCAR=13.9
Pod documented
556 12 my $self = shift;
557 12 my $subj = shift;
558 12 my $pred = shift;
559 12 my $obj = shift;
560 12 my $context = shift;
561 12 my $dbh = $self->dbh;
562 12 my $stable = $self->statements_table;
563
564 12 my (@where, @bind);
565 12 my @keys = qw(Subject Predicate Object Context);
566 12 foreach my $node ($subj, $pred, $obj, $context) {
567 48 my $key = shift(@keys);
568 48 ▶ if (defined($node)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $node) 14 34 48
569 14 push(@bind, $node);
570 14 push(@where, "${key} = ?");
571 }
572 }
573
574 12 my $where = join(" AND ", @where);
575 12 ▶ my $sth = $dbh->prepare( join(' ', "DELETE FROM ${stable}", ($where ? "WHERE ${where}" : ())) );
Branch: 1 branch
BranchTrueFalseTotal
$where ? : 12 0 12
576 12 my @values = map { $self->_mysql_node_hash( $_ ) } (@bind);
577 12 $sth->execute( @values );
578 }
579  
580 1099 ▶sub _add_node {
Subroutine _add_node: called CC=8 SCAR=20.8
581 1099 my $self = shift;
582 1099 my $node = shift;
583 1099 my $hash = $self->_mysql_node_hash( $node );
584 1099 my $dbh = $self->dbh;
585
586 1099 my @cols;
587 my $table;
588 1099 my %values;
589 1099 ▶ return $hash if ($node->is_nil);
Branch: 1 branch
BranchTrueFalseTotal
if $node->is_nil 10 1089 1099
590 1089 ▶ if ($node->is_blank) {
Branch: 3 branches
BranchTrueFalseTotal
if ($node->is_blank) { } 18 1071 1089
elsif ($node->is_resource) { } 1039 32 1071
elsif ($node->isa('RDF::Trine::Node::Literal')) { } 32 0 32
591 18 $table = "Bnodes";
592 18 @cols = qw(ID Name);
593 18 @values{ @cols } = ($hash, $node->blank_identifier);
594 } elsif ($node->is_resource) {
595 1039 $table = "Resources";
596 1039 @cols = qw(ID URI);
597 1039 @values{ @cols } = ($hash, encode('utf8', $node->uri_value));
598 } elsif ($node->isa('RDF::Trine::Node::Literal')) {
599 32 $table = "Literals";
600 32 @cols = qw(ID Value);
601 32 @values{ @cols } = ($hash, encode('utf8', $node->literal_value));
602 32 ▶ if ($node->has_language) {
Branch: 2 branches
BranchTrueFalseTotal
if ($node->has_language) { } 10 22 32
elsif ($node->has_datatype) { } 8 14 22
603 10 push(@cols, 'Language');
604 10 $values{ 'Language' } = $node->literal_value_language;
605 } elsif ($node->has_datatype) {
606 8 push(@cols, 'Datatype');
607 8 $values{ 'Datatype' } = encode('utf8', $node->literal_datatype);
608 }
609 }
610
611 1089 my $ssql = "SELECT 1 FROM ${table} WHERE " . join(' AND ', map { join(' = ', $_, '?') } @cols);
612 1089 my $sth = $dbh->prepare( $ssql );
613 1089 my @values = map {"$_"} @values{ @cols };
614 1089 $sth->execute( @values );
615 1089 ▶ unless ($sth->fetch) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sth->fetch) 73 1016 1089
616 73 my $sql = "INSERT INTO ${table} (" . join(', ', @cols) . ") VALUES (" . join(',',('?')x scalar(@cols)) . ")";
617 73 my $sth = $dbh->prepare( $sql );
618 73 $sth->execute( @values );
619 }
620 1089 return $hash;
621 }
622  
623 =item C<< count_statements ($subject, $predicate, $object) >>
624  
625 Returns a count of all the statements matching the specified subject,
626 predicate and objects. Any of the arguments may be undef to match any value.
627  
628 =cut
629  
630 189 ▶sub count_statements {
Subroutine count_statements: called CC=9 SCAR=22.0
Pod documented
631 189 my $self = shift;
632 189 my @nodes = @_[0..3];
633 189 my $bound = 0;
634 189 my %bound;
635
636 189 my $use_quad = 0;
637 189 ▶ if (scalar(@_) >= 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ >= 4) 149 40 189
638 149 $use_quad = 1;
639 # warn "count statements with quad" if ($::debug);
640 149 my $g = $nodes[3];
641 149 ▶ if (blessed($g) and not($g->is_variable)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($g) and not $g->is_variable) 24 125 149
Condition100%3/3
builtin::blessed($g) and not $g->is_variable
!ll&&!rl&&r
123224
MC/DC100%2/2
builtin::blessed($g) and not $g->is_variable
builtin::blessed($g) not $g->is_variable
Truth table100%3/3
A and not(B)
A= builtin::blessed($g)B= not $g->is_variable
ABresult
0X0
100
111
642 24 $bound++;
643 24 $bound{ 3 } = $g;
644 }
645 }
646
647 189 my ($subj, $pred, $obj, $context) = @nodes;
648
649 189 my $dbh = $self->dbh;
650 189 my $var = 0;
651 my $st = ($use_quad)
652 596 ▶ ? RDF::Trine::Statement::Quad->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj,$context) )
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 104 492 596
653 189 ▶ : RDF::Trine::Statement->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj) );
Branch: 2 branches
BranchTrueFalseTotal
$use_quad ? : 149 40 189
defined $_ ? : 13 107 120
654 189 my @vars = $st->referenced_variables;
655
656 189 ▶ my $semantics = ($use_quad ? 'quad' : 'triple');
Branch: 1 branch
BranchTrueFalseTotal
$use_quad ? : 149 40 189
657 189 ▶ my $countkey = ($use_quad) ? 'count' : 'count-distinct';
Branch: 1 branch
BranchTrueFalseTotal
$use_quad ? : 149 40 189
658 189 my $sql = $self->_sql_for_pattern( $st, $context, $countkey => 1, semantics => $semantics );
659 # $sql =~ s/SELECT\b(.*?)\bFROM/SELECT COUNT(*) AS c FROM/smo;
660 189 my $count;
661 189 my $sth = $dbh->prepare( $sql );
662 189 $sth->execute();
663 189 $sth->bind_columns( \$count );
664 189 $sth->fetch;
665 189 return $count;
666 }
667  
668 =item C<add_uri ( $uri, $named, $format )>
669  
670 Addsd the contents of the specified C<$uri> to the model.
671 If C<$named> is true, the data is added to the model using C<$uri> as the
672 named context.
673  
674 =cut
675  
676 =item C<add_string ( $data, $base_uri, $named, $format )>
677  
678 Addsd the contents of C<$data> to the model. If C<$named> is true,
679 the data is added to the model using C<$base_uri> as the named context.
680  
681 =cut
682  
683 =item C<< add_statement ( $statement ) >>
684  
685 Adds the specified C<$statement> to the underlying model.
686  
687 =cut
688  
689 =item C<< remove_statement ( $statement ) >>
690  
691 Removes the specified C<$statement> from the underlying model.
692  
693 =cut
694  
695 =item C<< variable_columns ( $var ) >>
696  
697 Given a variable name, returns the set of column aliases that store the values
698 for the column (values for Literals, URIs, and Blank Nodes).
699  
700 =cut
701  
702 23 ▶sub variable_columns {
Subroutine variable_columns: called CC=4 SCAR=13.9
Pod documented
703 23 my $self = shift;
704 23 my $var = shift;
705 23 my $context = shift;
706
707 ### ORDERING of these is important to enforce the correct sorting of results
708 ### based on the SPARQL spec. Bnodes < IRIs < Literals, but since NULLs sort
709 ### higher than other values, the list needs to be reversed.
710 23 my $r = $context->{restrict}{$var};
711
712 23 my @cols;
713 23 ▶ push(@cols, 'Value') unless ($r->{literal});
Branch: 1 branch
BranchTrueFalseTotal
unless $r->{"literal"} 12 11 23
714 23 ▶ push(@cols, 'URI') unless ($r->{resource});
Branch: 1 branch
BranchTrueFalseTotal
unless $r->{"resource"} 23 0 23
715 23 ▶ push(@cols, 'Name') unless ($r->{blank});
Branch: 1 branch
BranchTrueFalseTotal
unless $r->{"blank"} 19 4 23
716 23 return map { "${var}_$_" } @cols;
717 }
718  
719 =item C<< add_variable_values_joins >>
720  
721 Modifies the query by adding LEFT JOINs to the tables in the database that
722 contain the node values (for literals, resources, and blank nodes).
723  
724 =cut
725  
726 68 my %NODE_TYPE_TABLES = (
727 resource => ['Resources', 'ljr', 'URI'],
728 literal => ['Literals', 'ljl', qw(Value Language Datatype)],
729 blank => ['Bnodes', 'ljb', qw(Name)]
730 );
731 310 ▶sub add_variable_values_joins {
Subroutine add_variable_values_joins: called CC=16 SCAR=27.8
Pod documented
732 310 my $self = shift;
733 310 my $context = shift;
734 310 my $varhash = shift;
735
736 310 my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
737
738 310 my @vars = keys %$varhash;
739 310 my %select_vars = map { $_ => 1 } @vars;
740 310 my %variable_value_cols;
741
742 310 my $vars = $context->{vars};
743 310 my $from = $context->{from_tables};
744 310 my $where = $context->{where_clauses};
745 310 my $stable = $self->statements_table;
746
747 310 my @cols;
748 310 my $uniq_count = 0;
749 310 my (%seen_vars, %seen_joins);
750 310 foreach my $var (grep { not $seen_vars{ $_ }++ } (sort (@vars, keys %$vars))) {
751 889 my $col = $vars->{ $var };
752 889 ▶ unless ($col) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($col) 0 889 889
753 0 throw RDF::Trine::Error::CompilationError -text => "*** Nothing is known about the variable ?${var}";
754 }
755
756 889 my $col_table = (split(/[.]/, $col))[0];
757 889 my ($count) = ($col_table =~ /\w(\d+)/);
758
759 889 $l->info("var: $var\t\tcol: $col\t\tcount: $count\t\tunique count: $uniq_count");
760
761 889 ▶ push(@cols, "${col} AS ${var}_Node") if ($select_vars{ $var });
Branch: 1 branch
BranchTrueFalseTotal
if $select_vars{$var} 889 0 889
762 889 my $restricted = 0;
763 889 my @used_ljoins;
764 889 foreach my $type (reverse sort keys %NODE_TYPE_TABLES) {
765 2667 my ($table, $alias, @join_cols) = @{ $NODE_TYPE_TABLES{ $type } };
766 2667 ▶ if ($context->{restrict}{$var}{$type}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($context->{'restrict'}{$var}{$type}) { } 666 2001 2667
767 666 $restricted = 1;
768 666 next;
769 } else {
770 2001 push(@used_ljoins, "${alias}${uniq_count}.$join_cols[0]");
771 }
772 2001 foreach my $jc (@join_cols) {
773 2897 my $column_real_name = "${alias}${uniq_count}.${jc}";
774 2897 my $column_alias_name = "${var}_${jc}";
775 2897 push(@cols, "${column_real_name} AS ${column_alias_name}");
776 2897 push( @{ $variable_value_cols{ $var } }, $column_real_name);
777
778 2897 foreach my $i (0 .. $#{ $where }) {
779 3183 ▶ if ($where->[$i] =~ /\b$column_alias_name\b/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($where->[$i] =~ /\b$column_alias_name\b/) 0 3183 3183
780 0 $where->[$i] =~ s/\b${column_alias_name}\b/${column_real_name}/g;
781 }
782 }
783
784 }
785 }
786
787 889 foreach my $i (0 .. $#{ $from }) {
788 929 my $f = $from->[ $i ];
789 929 ▶ next if ($from->[ $i ] =~ m/^[()]$/);
Branch: 1 branch
BranchTrueFalseTotal
if $from->[$i] =~ /^[()]$/ 0 929 929
790 929 my ($alias) = ($f =~ m/${stable} (\w\d+)/); #split(/ /, $f))[1];
791
792 929 ▶ if ($alias eq $col_table) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alias eq $col_table) 889 40 929
793 # my (@tables, @where);
794 889 foreach my $type (reverse sort keys %NODE_TYPE_TABLES) {
795 2667 ▶ next if ($context->{restrict}{$var}{$type});
Branch: 1 branch
BranchTrueFalseTotal
if $context->{"restrict"}{$var}{$type} 666 2001 2667
796 2001 my ($vtable, $vname) = @{ $NODE_TYPE_TABLES{ $type } };
797 2001 my $valias = join('', $vname, $uniq_count);
798 2001 ▶ next if ($seen_joins{ $valias }++);
Branch: 1 branch
BranchTrueFalseTotal
if $seen_joins{$valias}++ 0 2001 2001
799
800 # push(@tables, "${vtable} ${valias}");
801 # push(@where, "${col} = ${valias}.ID");
802 2001 $f .= " LEFT JOIN ${vtable} ${valias} ON (${col} = ${valias}.ID)";
803 }
804
805 # my $join = sprintf("LEFT JOIN (%s) ON (%s)", join(', ', @tables), join(' AND ', @where));
806 # $from->[ $i ] = join(' ', $f, $join);
807 889 $from->[ $i ] = $f;
808 889 next;
809 }
810 }
811
812 889 ▶ if ($restricted) {
Branch: 1 branch
BranchTrueFalseTotal
if ($restricted) 441 448 889
813 # if we're restricting the left-joins to only certain types of nodes,
814 # we need to insure that the rows we're getting back actually have data
815 # in the left-joined columns. otherwise, we might end up with data for
816 # a URI, but only left-join with Bnodes (for example), and end up with
817 # NULL values where we aren't expecting them.
818 441 _add_where( $context, '(' . join(' OR ', map {"$_ IS NOT NULL"} @used_ljoins) . ')' );
819 }
820
821 889 $uniq_count++;
822 }
823
824 310 return (\%variable_value_cols, @cols);
825 }
826  
827 310 ▶sub _sql_for_pattern {
Subroutine _sql_for_pattern: called CC=7 SCAR=20.5
828 310 my $self = shift;
829 310 my $pat = shift;
830 310 my $ctx_node = shift;
831 310 my %args = @_;
832
833 310 my @disjunction;
834 310 my @patterns = $pat;
835 310 my $variables;
836 310 ▶ while (my $p = shift(@patterns)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $p = shift @patterns) 310 310 620
837 310 ▶ if ($p->isa('RDF::Query::Algebra::Union')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->isa('RDF::Query::Algebra::Union')) { } 0 310 310
838 0 push(@patterns, $p->patterns);
839 } else {
840 310 my $pvars = join('#', sort $p->referenced_variables);
841 310 ▶ if (@disjunction) {
Branch: 1 branch
BranchTrueFalseTotal
if (@disjunction) { } 0 310 310
842 # if we've already got some UNION patterns, make sure the new
843 # pattern has the same referenced variables (otherwise the
844 # columns of the result are going to come out all screwy
845 0 ▶ if ($pvars ne $variables) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pvars ne $variables) 0 0 0
846 0 throw RDF::Trine::Error::CompilationError -text => 'All patterns in a UNION must reference the same variables.';
847 }
848 } else {
849 310 $variables = $pvars;
850 }
851 310 push(@disjunction, $p);
852 }
853 }
854
855 310 my @sql;
856 310 foreach my $pattern (@disjunction) {
857 310 my $type = $pattern->type;
858 310 my $method = "_sql_for_" . lc($type);
859 310 my $context = $self->_new_context;
860
861 # warn "*** sql compilation method $method";
862 310 ▶ if ($self->can($method)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->can($method)) { } 310 0 310
863 310 $self->$method( $pattern, $ctx_node, $context, %args );
864 310 push(@sql, $self->_sql_from_context( $context, %args ));
865 } else {
866 0 throw RDF::Trine::Error::CompilationError ( -text => "Don't know how to turn a $type into SQL" );
867 }
868 }
869 310 return join(' UNION ', @sql);
870 }
871  
872 310 ▶sub _new_context {
Subroutine _new_context: called CC=1 SCAR=0.0
873 310 my $self = shift;
874 310 my $context = {
875 next_alias => 0,
876 level => 0,
877 statement_table => $self->statements_table,
878 };
879 310 return $context;
880 }
881  
882 68 ▶use constant INDENT => "\t";
Subroutine BEGIN: called CC=1 SCAR=0.0
883 310 ▶sub _sql_from_context {
Subroutine _sql_from_context: called CC=19 SCAR=29.5
884 310 my $self = shift;
885 310 my $context = shift;
886 310 my %args = @_;
887 310 my $vars = $context->{vars};
888 310 ▶ my $from = $context->{from_tables} || [];
Condition50%1/2
$context->{'from_tables'} || []
l!l
3100
MC/DC0%0/1
$context->{'from_tables'} || []
$context->{'from_tables'}
Truth table50%1/2
A
A= $context->{'from_tables'}
Aresult
11
00
889 310 ▶ my $where = $context->{where_clauses} || [];
Condition100%2/2
$context->{'where_clauses'} || []
l!l
177133
MC/DC100%1/1
$context->{'where_clauses'} || []
$context->{'where_clauses'}
Truth table100%2/2
A
A= $context->{'where_clauses'}
Aresult
11
00
890 310 ▶ my $unique = $args{'unique'} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$args{'unique'} ? : 81 229 310
891
892 310 my ($varcols, @cols) = $self->add_variable_values_joins( $context, $vars );
893 310 ▶ unless (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@cols) 4 306 310
894 4 push(@cols, 1);
895 }
896
897 310 my $from_clause;
898 310 foreach my $f (@$from) {
899 331 ▶ $from_clause .= ",\n" . INDENT if ($from_clause and $from_clause =~ m/[^(]$/ and $f !~ m/^([)]|LEFT JOIN)/);
Branch: 1 branch
BranchTrueFalseTotal
if $from_clause and $from_clause =~ /[^(]$/ and not $f =~ /^([)]|LEFT JOIN)/ 21 310 331
Condition66%4/6
$from_clause and $from_clause =~ /[^(]$/ and not $f =~ /^([)]|LEFT JOIN)/
!ll&&!rl&&r
310021
$from_clause and $from_clause =~ /[^(]$/
!ll&&!rl&&r
310021
MC/DC33%1/3
$from_clause and $from_clause =~ /[^(]$/ and not $f =~ /^([)]|LEFT JOIN)/
$from_clause $from_clause =~ /[^(]$/ not $f =~ /^([)]|LEFT JOIN)/
Truth table50%2/4
A and B and not(C)
A= $from_clauseB= $from_clause =~ /[^(]$/C= not $f =~ /^([)]|LEFT JOIN)/
ABCresult
0XX0
10X0
1100
1111
900 331 $from_clause .= $f;
901 }
902
903 310 ▶ my $where_clause = @$where ? "WHERE\n"
Branch: 1 branch
BranchTrueFalseTotal
@$where ? : 177 133 310
904 . INDENT . join(" AND\n" . INDENT, @$where) : '';
905
906 310 ▶ if ($args{ count }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"count"}) 149 161 310
907 149 @cols = ('COUNT(*)');
908 }
909 310 ▶ if ($args{ 'count-distinct' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"count-distinct"}) 40 270 310
910 40 $unique = 1;
911 }
912 310 ▶ if ($args{ 'count' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"count"}) 149 161 310
913 149 @cols = 'COUNT(*)';
914 }
915
916 310 ▶ my @sql = (
Branch: 1 branch
BranchTrueFalseTotal
$unique ? : 121 189 310
917 "SELECT" . ($unique ? ' DISTINCT' : ''),
918 INDENT . join(",\n" . INDENT, @cols),
919 "FROM",
920 INDENT . $from_clause,
921 $where_clause,
922 );
923
924 310 ▶ if (my $o = $args{ orderby }) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $o = $args{"orderby"}) 16 294 310
925 16 my @ordering = @$o;
926 16 my @sort;
927 16 ▶ while (my ($col, $dir) = splice( @ordering, 0, 2, () )) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@ordering, 0, 2, ())) 27 16 43
928 27 ▶ if (exists $vars->{ $col }) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $vars->{$col}) 23 4 27
929 23 push(@sort, map { "$_ $dir" } $self->variable_columns( $col, $context ));
930 }
931 }
932 16 ▶ if (@sort) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sort) 12 4 16
933 12 push(@sql, "ORDER BY " . join(', ', @sort));
934 }
935 }
936 # push(@sql, $self->order_by_clause( $varcols, $level ) );
937 # push(@sql, $self->limit_clause( $options ) );
938
939 310 my $sql = join("\n", grep {length} @sql);
940
941 310 ▶ if ($args{ 'count-distinct' }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"count-distinct"}) 40 270 310
942 40 $sql = "SELECT COUNT(*) FROM ($sql) AS counttable";
943 }
944
945 # warn $sql;
946 310 return $sql;
947 }
948  
949 331 ▶sub _get_level { return $_[0]{level}; }
Subroutine _get_level: called CC=1 SCAR=0.0
950 331 ▶sub _next_alias { return $_[0]{next_alias}++; }
Subroutine _next_alias: called CC=1 SCAR=0.0
951 331 ▶sub _statements_table { return $_[0]{statement_table}; };
Subroutine _statements_table: called CC=1 SCAR=0.0
952 331 ▶sub _add_from { push( @{ $_[0]{from_tables} }, $_[1] ); }
Subroutine _add_from: called CC=1 SCAR=0.0
953 771 ▶sub _add_where { push( @{ $_[0]{where_clauses} }, $_[1] ); }
Subroutine _add_where: called CC=1 SCAR=0.0
954 907 ▶sub _get_var { return $_[0]{vars}{ $_[1] }; }
Subroutine _get_var: called CC=1 SCAR=0.0
955 889 ▶sub _add_var { $_[0]{vars}{ $_[1] } = $_[2]; }
Subroutine _add_var: called CC=1 SCAR=0.0
956 907 ▶sub _add_restriction {
Subroutine _add_restriction: called CC=2 SCAR=6.9
957 907 my $context = shift;
958 907 my $var = shift;
959 907 my @rests = @_;
960 907 foreach my $r (@rests) {
961 683 $context->{restrict}{ $var->name }{ $r }++
962 }
963 }
964  
965 0 ▶sub _sql_for_filter {
Subroutine _sql_for_filter: not called CC=1 SCAR=6.9
966 0 my $self = shift;
967 0 my $filter = shift;
968 0 my $ctx_node = shift;
969 0 my $context = shift;
970
971 0 my $expr = $filter->expr;
972 0 my $pattern = $filter->pattern;
973 0 my $type = $pattern->type;
974 0 my $method = "_sql_for_" . lc($type);
975 0 $self->$method( $pattern, $ctx_node, $context );
976 0 $self->_sql_for_expr( $expr, $ctx_node, $context, @_ );
977 }
978  
979 0 ▶sub _sql_for_expr {
Subroutine _sql_for_expr: not called CC=14 SCAR=53.5
980 0 my $self = shift;
981 0 my $expr = shift;
982 0 my $ctx_node = shift;
983 0 my $context = shift;
984
985 ### None of these should affect the context directly, since the expression
986 ### might be a child of another expression (e.g. "isliteral(?node) || isresource(?node)")
987
988 0 ▶ if ($expr->isa('RDF::Query::Expression::Function')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($expr->isa('RDF::Query::Expression::Function')) { } 0 0 0
elsif ($expr->isa('RDF::Query::Expression::Binary')) { } 0 0 0
989 0 my $func = $expr->uri->uri_value;
990 0 my @args = $expr->arguments;
991 0 ▶ if ($func eq 'sparql:isliteral' and blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) {
Branch: 4 branches
BranchTrueFalseTotal
if ($func eq 'sparql:isliteral' and builtin::blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) { } 0 0 0
elsif ($func =~ qr/^sparql:is[iu]ri$/ and builtin::blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) { } 0 0 0
elsif ($func =~ qr/^sparql:isblank$/ and builtin::blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) { } 0 0 0
elsif ($func eq 'sparql:logical-or') { } 0 0 0
Condition0%0/6
$func eq "sparql:isliteral" and builtin::blessed($args[0]) and $args[0]->isa("RDF::Trine::Node::Variable")
!ll&&!rl&&r
000
$func eq "sparql:isliteral" and builtin::blessed($args[0])
!ll&&!rl&&r
000
MC/DC0%0/3
$func eq "sparql:isliteral" and builtin::blessed($args[0]) and $args[0]->isa("RDF::Trine::Node::Variable")
$func eq "sparql:isliteral" builtin::blessed($args[0]) $args[0]->isa("RDF::Trine::Node::Variable")
Truth table0%0/4
A and B and C
A= $func eq "sparql:isliteral"B= builtin::blessed($args[0])C= $args[0]->isa("RDF::Trine::Node::Variable")
ABCresult
0XX0
10X0
1100
1111
992 0 my $node = $args[0];
993 0 _add_restriction( $context, $node, qw(blank resource) );
994 ▶ } elsif ($func =~ qr/^sparql:is[iu]ri$/ and blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) {
Condition0%0/6
$func =~ qr/^sparql:is[iu]ri$/ and builtin::blessed($args[0]) and $args[0]->isa("RDF::Trine::Node::Variable")
!ll&&!rl&&r
000
$func =~ qr/^sparql:is[iu]ri$/ and builtin::blessed($args[0])
!ll&&!rl&&r
000
MC/DC0%0/3
$func =~ qr/^sparql:is[iu]ri$/ and builtin::blessed($args[0]) and $args[0]->isa("RDF::Trine::Node::Variable")
$func =~ qr/^sparql:is[iu]ri$/ builtin::blessed($args[0]) $args[0]->isa("RDF::Trine::Node::Variable")
Truth table0%0/4
A and B and C
A= $func =~ qr/^sparql:is[iu]ri$/B= builtin::blessed($args[0])C= $args[0]->isa("RDF::Trine::Node::Variable")
ABCresult
0XX0
10X0
1100
1111
995 0 my $node = $args[0];
996 0 _add_restriction( $context, $node, qw(blank literal) );
997 ▶ } elsif ($func =~ qr/^sparql:isblank$/ and blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) {
Condition0%0/6
$func =~ qr/^sparql:isblank$/ and builtin::blessed($args[0]) and $args[0]->isa("RDF::Trine::Node::Variable")
!ll&&!rl&&r
000
$func =~ qr/^sparql:isblank$/ and builtin::blessed($args[0])
!ll&&!rl&&r
000
MC/DC0%0/3
$func =~ qr/^sparql:isblank$/ and builtin::blessed($args[0]) and $args[0]->isa("RDF::Trine::Node::Variable")
$func =~ qr/^sparql:isblank$/ builtin::blessed($args[0]) $args[0]->isa("RDF::Trine::Node::Variable")
Truth table0%0/4
A and B and C
A= $func =~ qr/^sparql:isblank$/B= builtin::blessed($args[0])C= $args[0]->isa("RDF::Trine::Node::Variable")
ABCresult
0XX0
10X0
1100
1111
998 0 my $node = $args[0];
999 0 _add_restriction( $context, $node, qw(literal resource) );
1000 } elsif ($func eq 'sparql:logical-or') {
1001 0 $self->_sql_for_or_expr( $expr, $ctx_node, $context, @_ );
1002 } else {
1003 0 throw RDF::Trine::Error::CompilationError -text => "Unknown function data: " . Dumper($expr);
1004 }
1005 } elsif ($expr->isa('RDF::Query::Expression::Binary')) {
1006 0 ▶ if ($expr->op eq '==') {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr->op eq '==') { } 0 0 0
1007 0 $self->_sql_for_equality_expr( $expr, $ctx_node, $context, @_ );
1008 } else {
1009 0 throw RDF::Trine::Error::CompilationError -text => "Unknown expr data: " . Dumper($expr);
1010 }
1011
1012 } else {
1013 0 throw RDF::Trine::Error::CompilationError -text => "Unknown expr data: " . Dumper($expr);
1014 }
1015 0 return;
1016 }
1017  
1018 0 ▶sub _sql_for_or_expr {
Subroutine _sql_for_or_expr: not called CC=2 SCAR=17.9
1019 0 my $self = shift;
1020 0 my $expr = shift;
1021 0 my $ctx_node = shift;
1022 0 my $context = shift;
1023 0 my @args = $self->_logical_or_operands( $expr );
1024
1025 0 my @disj;
1026 0 foreach my $e (@args) {
1027 0 my $tmp_ctx = $self->_new_context;
1028 0 $self->_sql_for_expr( $e, $ctx_node, $tmp_ctx, @_ );
1029 0 my ($var, $val) = %{ $tmp_ctx->{vars} };
1030 0 my $existing_col = _get_var( $context, $var );
1031 0 push(@disj, "${existing_col} = $val");
1032 }
1033 0 my $disj = '(' . join(' OR ', @disj) . ')';
1034 0 _add_where( $context, $disj );
1035 }
1036  
1037 0 ▶sub _logical_or_operands {
Subroutine _logical_or_operands: not called CC=4 SCAR=30.0
1038 0 my $self = shift;
1039 0 my $expr = shift;
1040 0 my @args = $expr->operands;
1041 0 my @ops;
1042 0 foreach my $e (@args) {
1043 0 ▶ if ($e->isa('RDF::Query::Expression::Function') and $e->uri->uri_value eq 'sparql:logical-or') {
Branch: 1 branch
BranchTrueFalseTotal
if ($e->isa('RDF::Query::Expression::Function') and $e->uri->uri_value eq 'sparql:logical-or') { } 0 0 0
Condition0%0/3
$e->isa("RDF::Query::Expression::Function") and $e->uri->uri_value eq "sparql:logical-or"
!ll&&!rl&&r
000
MC/DC0%0/2
$e->isa("RDF::Query::Expression::Function") and $e->uri->uri_value eq "sparql:logical-or"
$e->isa("RDF::Query::Expression::Function") $e->uri->uri_value eq "sparql:logical-or"
Truth table0%0/3
A and B
A= $e->isa("RDF::Query::Expression::Function")B= $e->uri->uri_value eq "sparql:logical-or"
ABresult
0X0
100
111
1044 0 push(@ops, $self->_logical_or_operands( $e ));
1045 } else {
1046 0 push(@ops, $e);
1047 }
1048 }
1049 0 return @ops;
1050 }
1051  
1052 0 ▶sub _sql_for_equality_expr {
Subroutine _sql_for_equality_expr: not called CC=5 SCAR=34.0
1053 0 my $self = shift;
1054 0 my $expr = shift;
1055 0 my $ctx_node = shift;
1056 0 my $context = shift;
1057
1058 0 my @args = $expr->operands;
1059 # make sorted[0] be the variable
1060 0 my @sorted = sort { $b->isa('RDF::Trine::Node::Variable') } @args;
1061 0 ▶ unless ($sorted[0]->isa('RDF::Trine::Node::Variable')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sorted[0]->isa("RDF::Trine::Node::Variable")) 0 0 0
1062 0 throw RDF::Trine::Error::CompilationError -text => "No variable in equality test";
1063 }
1064 0 ▶ unless ($sorted[1]->isa('RDF::Trine::Node') and not($sorted[1]->isa('RDF::Trine::Node::Variable'))) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sorted[1]->isa("RDF::Trine::Node") and not $sorted[1]->isa("RDF::Trine::Node::Variable")) 0 0 0
Condition0%0/3
$sorted[1]->isa("RDF::Trine::Node") and not $sorted[1]->isa("RDF::Trine::Node::Variable")
!ll&&!rl&&r
000
MC/DC0%0/2
$sorted[1]->isa("RDF::Trine::Node") and not $sorted[1]->isa("RDF::Trine::Node::Variable")
$sorted[1]->isa("RDF::Trine::Node") not $sorted[1]->isa("RDF::Trine::Node::Variable")
Truth table0%0/3
A and not(B)
A= $sorted[1]->isa("RDF::Trine::Node")B= not $sorted[1]->isa("RDF::Trine::Node::Variable")
ABresult
0X0
100
111
1065 0 throw RDF::Trine::Error::CompilationError -text => "No RDFNode in equality test";
1066 }
1067
1068 0 my $name = $sorted[0]->name;
1069 0 my $id = $self->_mysql_node_hash( $sorted[1] );
1070 # $self->_add_sql_node_clause( $id, $sorted[0], $context );
1071 0 ▶ if (my $existing_col = _get_var( $context, $name )) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $existing_col = _get_var($context, $name)) { } 0 0 0
1072 0 _add_where( $context, "${existing_col} = $id" );
1073 } else {
1074 0 _add_var( $context, $name, $id );
1075 }
1076 }
1077  
1078 119 ▶sub _sql_for_triple { &_sql_for_statement; }
Subroutine _sql_for_triple: called CC=1 SCAR=0.0
1079 212 ▶sub _sql_for_quad { &_sql_for_statement; }
Subroutine _sql_for_quad: called CC=1 SCAR=0.0
1080 {
1081 68 my %default_restrictions = (
1082 subject => ['literal'],
1083 predicate => [qw(literal blank)],
1084 object => [],
1085 context => [],
1086 );
1087 331 ▶sub _sql_for_statement {
Subroutine _sql_for_statement: called CC=10 SCAR=23.1
1088 331 my $self = shift;
1089 331 my $triple = shift;
1090 331 my $ctx = shift;
1091 331 my $context = shift;
1092 331 my %args = @_;
1093
1094 my %restrictions = defined $self->{restrictions}
1095 0 ▶ ? %{ $self->{restrictions} }
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'restrictions'} ? : 0 331 331
1096 : %default_restrictions;
1097  
1098 331 my $quad = $triple->isa('RDF::Trine::Statement::Quad');
1099 68 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
1100 331 ▶ if ($args{semantics} eq 'triple') {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"semantics"} eq "triple") 58 273 331
1101 58 $quad = 0;
1102 }
1103 331 ▶ my @posmap = ($quad)
Branch: 1 branch
BranchTrueFalseTotal
$quad ? : 224 107 331
1104 ? qw(subject predicate object context)
1105 : qw(subject predicate object);
1106 331 my $table = "s" . _next_alias($context);
1107 331 my $stable = _statements_table($context);
1108 331 my $level = _get_level( $context );
1109 331 _add_from( $context, "${stable} ${table}" );
1110 331 foreach my $method (@posmap) {
1111 1217 my $node = $triple->$method();
1112 1217 ▶ next unless defined($node);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node 0 1217 1217
1113 1217 my $pos = $method;
1114 1217 my $col = "${table}.${pos}";
1115 1217 ▶ if ($node->isa('RDF::Trine::Node::Variable')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->isa("RDF::Trine::Node::Variable")) 907 310 1217
1116 907 _add_restriction( $context, $node, @{ $restrictions{ $method } } );
1117 }
1118 1217 $self->_add_sql_node_clause( $col, $node, $context );
1119 }
1120
1121 331 ▶ unless ($quad) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($quad) 107 224 331
1122 107 ▶ if (defined($ctx)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $ctx) { } 2 105 107
elsif ($self->{'join_context_nodes'}) { } 0 105 105
1123 2 $self->_add_sql_node_clause( "${table}.Context", $ctx, $context );
1124 } elsif ($self->{join_context_nodes}) {
1125 0 $self->_add_sql_node_clause( "${table}.Context", RDF::Trine::Node::Variable->new( 'sql_ctx_' . ++$self->{ context_variable_count } ), $context );
1126 }
1127 }
1128 }}
1129  
1130 68 ▶sub _add_sql_node_clause {
Subroutine _add_sql_node_clause: called CC=7 SCAR=19.5
1131 1219 my $self = shift;
1132 1219 my $col = shift;
1133 1219 my $node = shift;
1134 1219 my $context = shift;
1135 1219 ▶ if ($node->isa('RDF::Trine::Node::Variable')) {
Branch: 5 branches
BranchTrueFalseTotal
if ($node->isa('RDF::Trine::Node::Variable')) { } 907 312 1219
elsif ($node->isa('RDF::Trine::Node::Resource')) { } 249 63 312
elsif ($node->isa('RDF::Trine::Node::Blank')) { } 18 45 63
elsif ($node->isa('RDF::Trine::Node::Literal')) { } 33 12 45
elsif ($node->is_nil) { } 12 0 12
1136 907 my $name = $node->name;
1137 907 ▶ if (my $existing_col = _get_var( $context, $name )) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $existing_col = _get_var($context, $name)) { } 18 889 907
1138 18 _add_where( $context, "$col = ${existing_col}" );
1139 } else {
1140 889 _add_var( $context, $name, $col );
1141 }
1142 } elsif ($node->isa('RDF::Trine::Node::Resource')) {
1143 249 my $uri = $node->uri_value;
1144 249 my $id = $self->_mysql_node_hash( $node );
1145 249 $id =~ s/\D//;
1146 249 _add_where( $context, "${col} = $id" );
1147 } elsif ($node->isa('RDF::Trine::Node::Blank')) {
1148 18 my $id = $self->_mysql_node_hash( $node );
1149 18 $id =~ s/\D//;
1150 18 _add_where( $context, "${col} = $id" );
1151 # my $id = $node->blank_identifier;
1152 # my $b = "b$level";
1153 # _add_from( $context, "Bnodes $b" );
1154 # _add_where( $context, "${col} = ${b}.ID" );
1155 # _add_where( $context, "${b}.Name = '$id'" );
1156 } elsif ($node->isa('RDF::Trine::Node::Literal')) {
1157 33 my $id = $self->_mysql_node_hash( $node );
1158 33 $id =~ s/\D//;
1159 33 _add_where( $context, "${col} = $id" );
1160 } elsif ($node->is_nil) {
1161 12 _add_where( $context, "${col} = 0" );
1162 } else {
1163 0 throw RDF::Trine::Error::CompilationError( -text => "Unknown node type: " . Dumper($node) );
1164 }
1165 }
1166  
1167 25 ▶sub _sql_for_bgp {
Subroutine _sql_for_bgp: called CC=2 SCAR=6.9
1168 25 my $self = shift;
1169 25 my $bgp = shift;
1170 25 my $ctx = shift;
1171 25 my $context = shift;
1172
1173 25 foreach my $triple ($bgp->triples) {
1174 46 $self->_sql_for_triple( $triple, $ctx, $context, @_ );
1175 }
1176 }
1177  
1178 0 ▶sub _sql_for_ggp {
Subroutine _sql_for_ggp: not called CC=3 SCAR=24.8
1179 0 my $self = shift;
1180 0 my $ggp = shift;
1181 0 my $ctx = shift;
1182 0 my $context = shift;
1183
1184 0 my @patterns = $ggp->patterns;
1185 0 ▶ throw RDF::Trine::Error::CompilationError -text => "Can't compile an empty GroupGraphPattern to SQL" unless (scalar(@patterns));;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @patterns 0 0 0
1186
1187 0 foreach my $p (@patterns) {
1188 0 my $type = $p->type;
1189 0 my $method = "_sql_for_" . lc($type);
1190 0 $self->$method( $p, $ctx, $context, @_ );
1191 }
1192 }
1193  
1194 =item C<< _mysql_hash ( $data ) >>
1195  
1196 Returns a hash value for the supplied C<$data> string. This value is computed
1197 using the same algorithm that Redland's mysql storage backend uses.
1198  
1199 =cut
1200  
1201 sub _mysql_hash;
1202 0 ▶sub _mysql_hash_pp {
Subroutine _mysql_hash_pp: not called CC=3 SCAR=24.8
1203 0 ▶ if (ref($_[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0]) 0 0 0
1204 0 my $self = shift;
1205 }
1206 0 my $data = encode('utf8', shift);
1207 0 my @data = unpack('C*', md5( $data ));
1208 0 my $sum = Math::BigInt->new('0');
1209 0 foreach my $count (0 .. 7) {
1210 0 my $data = Math::BigInt->new( $data[ $count ] ); #shift(@data);
1211 0 my $part = $data << (8 * $count);
1212 # warn "+ $part\n";
1213 0 $sum += $part;
1214 }
1215 # warn "= $sum\n";
1216 0 $sum =~ s/\D//; # get rid of the extraneous '+' that pops up under perl 5.6
1217 0 return $sum;
1218 }
1219  
1220 68 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.3
1221 ## no critic
1222 0 ▶ eval "use RDF::Trine::XS;";
Subroutine BEGIN: called CC=1 SCAR=1.2
1223 68 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1224 68 ▶ *{ '_mysql_hash' } = (RDF::Trine::XS->can('hash'))
Branch: 1 branch
BranchTrueFalseTotal
'RDF::Trine::XS'->can('hash') ? : 0 68 68
1225 ? \&RDF::Trine::XS::hash
1226 : \&_mysql_hash_pp;
1227 ## use critic
1228 }
1229  
1230 =item C<< _mysql_node_hash ( $node ) >>
1231  
1232 Returns a hash value (computed by C<_mysql_hash> for the supplied C<$node>.
1233 The hash value is based on the string value of the node and the node type.
1234  
1235 =cut
1236  
1237 2389 ▶sub _mysql_node_hash {
Subroutine _mysql_node_hash: called CC=9 SCAR=22.2
1238 2389 my $self = shift;
1239 2389 my $node = shift;
1240
1241 # my @node = @$node;
1242 # my ($type, $value) = splice(@node, 0, 2, ());
1243 2389 ▶ return 0 unless (blessed($node));
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($node) 0 2389 2389
1244 2389 ▶ return 0 if ($node->is_nil);
Branch: 1 branch
BranchTrueFalseTotal
if $node->is_nil 72 2317 2389
1245
1246 2317 my $data;
1247 2317 ▶ if ($node->isa('RDF::Trine::Node::Resource')) {
Branch: 3 branches
BranchTrueFalseTotal
if ($node->isa('RDF::Trine::Node::Resource')) { } 2194 123 2317
elsif ($node->isa('RDF::Trine::Node::Blank')) { } 44 79 123
elsif ($node->isa('RDF::Trine::Node::Literal')) { } 79 0 79
1248 2194 my $value = $node->uri_value;
1249 2194 $data = 'R' . $value;
1250 } elsif ($node->isa('RDF::Trine::Node::Blank')) {
1251 44 my $value = $node->blank_identifier;
1252 44 $data = 'B' . $value;
1253 } elsif ($node->isa('RDF::Trine::Node::Literal')) {
1254 79 my $value = $node->literal_value;
1255 79 ▶ unless (defined($value)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 0 79 79
1256 0 $value = '';
1257 }
1258 79 ▶ my $lang = $node->literal_value_language || '';
Condition100%2/2
$node->literal_value_language || ''
l!l
2851
MC/DC100%1/1
$node->literal_value_language || ''
$node->literal_value_language
Truth table100%2/2
A
A= $node->literal_value_language
Aresult
11
00
1259 79 ▶ my $dt = $node->literal_datatype || '';
Condition100%2/2
$node->literal_datatype || ''
l!l
1861
MC/DC100%1/1
$node->literal_datatype || ''
$node->literal_datatype
Truth table100%2/2
A
A= $node->literal_datatype
Aresult
11
00
1260 68 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
1261 79 $data = sprintf("L%s<%s>%s", $value, $lang, $dt);
1262 # warn "($data)";
1263 } else {
1264 0 return;
1265 }
1266 2317 my $hash;
1267 2317 $hash = $self->_mysql_hash( $data );
1268 2317 return $hash;
1269 }
1270  
1271 =item C<< statements_table >>
1272  
1273 Returns the name of the Statements table.
1274  
1275 =cut
1276  
1277 1177 ▶sub statements_table {
Subroutine statements_table: called CC=1 SCAR=0.0
Pod documented
1278 1177 my $self = shift;
1279 1177 my $model = $self->model_name;
1280 1177 my $id = $self->_mysql_hash( $model );
1281 1177 my $prefix = $self->{statements_table_prefix};
1282 1177 return join('', $prefix, $id);
1283 }
1284  
1285 =item C<< statements_prefix >>
1286  
1287 Returns the prefix for the underlying Statements database table.
1288  
1289 =cut
1290  
1291 0 ▶sub statements_prefix {
Subroutine statements_prefix: not called CC=1 SCAR=6.9
Pod documented
1292 0 my $self = shift;
1293 0 return $self->{ statements_table_prefix };
1294 }
1295  
1296 =item C<< set_statements_prefix ( $prefix ) >>
1297  
1298 Sets the prefix for the underlying Statements database table.
1299  
1300 =cut
1301  
1302 0 ▶sub set_statements_prefix {
Subroutine set_statements_prefix: not called CC=1 SCAR=6.9
Pod documented
1303 0 my $self = shift;
1304 0 my $prefix = shift;
1305 0 $self->{ statements_table_prefix } = $prefix;
1306 }
1307  
1308 =item C<< model_name >>
1309  
1310 Returns the name of the underlying model.
1311  
1312 =cut
1313  
1314 1211 ▶sub model_name {
Subroutine model_name: called CC=1 SCAR=0.0
Pod documented
1315 1211 my $self = shift;
1316 # Carp::confess unless (blessed($self));
1317 1211 return $self->{model_name};
1318 }
1319  
1320 =item C<< make_private_predicate_view ( $prefix, @preds ) >>
1321  
1322 =cut
1323  
1324 0 ▶sub make_private_predicate_view {
Subroutine make_private_predicate_view: not called CC=1 SCAR=6.9
Pod documented
1325 0 my $self = shift;
1326 0 my $prefix = shift;
1327 0 my @preds = @_;
1328
1329 0 my $oldtable = $self->statements_table;
1330 0 my $oldpre = $self->statements_prefix;
1331 0 my $model = $self->model_name;
1332 0 my $id = $self->_mysql_hash( $model );
1333
1334 0 my $stable = join('', $prefix, $oldpre, $id);
1335 0 my $predlist = join(', ', map { $self->_mysql_node_hash( $_ ) } (@preds));
1336 0 my $sql = "CREATE VIEW ${stable} AS SELECT * FROM ${oldtable} WHERE Predicate NOT IN (${predlist})";
1337
1338 0 my $dbh = $self->dbh;
1339 0 $dbh->do( $sql );
1340
1341 0 return $stable;
1342 }
1343  
1344 =item C<< dbh >>
1345  
1346 Returns the underlying DBI database handle.
1347  
1348 =cut
1349  
1350 2221 ▶sub dbh {
Subroutine dbh: called CC=2 SCAR=6.9
Pod documented
1351 2221 my $self = shift;
1352 2221 ▶ if (my $conn = $self->{conn}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn = $self->{'conn'}) { } 2113 108 2221
1353 2113 return $conn->dbh;
1354 } else {
1355 108 my $dbh = $self->{dbh};
1356 108 return $dbh;
1357 }
1358 }
1359  
1360 0 ▶sub _debug {
Subroutine _debug: not called CC=2 SCAR=17.9
1361 0 my $self = shift;
1362 0 my $dbh = $self->{dbh};
1363 0 my $name = $self->model_name;
1364 0 my $id = $self->_mysql_hash( $name );
1365 0 my $table = 'Statements' . $id;
1366 0 my $sth = $dbh->prepare( "SELECT * FROM $table" );
1367 0 $sth->execute;
1368 0 my $count = 1;
1369 0 ▶ while (my $h = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $h = $sth->fetchrow_hashref) 0 0 0
1370 0 my ($s,$p,$o,$g) = @{ $h }{ qw(Subject Predicate Object Context) };
1371 0 warn sprintf("[%5d] subj=%-20d pred=%-20d obj=%-20d context=%-20d\n", $count++, $s, $p, $o, $g );
1372 }
1373 }
1374  
1375 =item C<< init >>
1376  
1377 Creates the necessary tables in the underlying database.
1378  
1379 =cut
1380  
1381 17 ▶sub init {
Subroutine init: called CC=9 SCAR=27.8
Pod documented
1382 17 my $self = shift;
1383 17 my $dbh = $self->dbh;
1384 17 my $name = $self->model_name;
1385 17 my $id = $self->_mysql_hash( $name );
1386 17 my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
1387 17 local($dbh->{AutoCommit}) = 0;
1388
1389 17 ▶ unless ($self->_table_exists("Literals")) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_table_exists("Literals")) 11 6 17
1390 0 ▶ $dbh->do( <<"END" ) || do { $l->trace( $dbh->errstr ); $dbh->rollback; return };
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do("\t\t\tCREATE TABLE Literals (\n\t\t\t\tID NUMERIC(20) PRIMARY KEY,\n\t\t\t\tValue text NOT NULL,\n\t\t\t\tLanguage text NOT NULL DEFAULT '',\n\t\t\t\tDatatype text NOT NULL DEFAULT ''\n\t\t\t);\n") or do { $l->trace($dbh->errstr); $dbh->rollback; return } 11 0 11
1391 CREATE TABLE Literals (
1392 ID NUMERIC(20) PRIMARY KEY,
1393 Value text NOT NULL,
1394 Language text NOT NULL DEFAULT '',
1395 Datatype text NOT NULL DEFAULT ''
1396 );
1397 END
1398 0 ▶ $dbh->do( <<"END" ) || do { $l->trace( $dbh->errstr ); $dbh->rollback; return };
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do("\t\t\tCREATE TABLE Resources (\n\t\t\t\tID NUMERIC(20) PRIMARY KEY,\n\t\t\t\tURI text NOT NULL\n\t\t\t);\n") or do { $l->trace($dbh->errstr); $dbh->rollback; return } 11 0 11
1399 CREATE TABLE Resources (
1400 ID NUMERIC(20) PRIMARY KEY,
1401 URI text NOT NULL
1402 );
1403 END
1404 0 ▶ $dbh->do( <<"END" ) || do { $l->trace( $dbh->errstr ); $dbh->rollback; return };
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do("\t\t\tCREATE TABLE Bnodes (\n\t\t\t\tID NUMERIC(20) PRIMARY KEY,\n\t\t\t\tName text NOT NULL\n\t\t\t);\n") or do { $l->trace($dbh->errstr); $dbh->rollback; return } 11 0 11
1405 CREATE TABLE Bnodes (
1406 ID NUMERIC(20) PRIMARY KEY,
1407 Name text NOT NULL
1408 );
1409 END
1410 0 ▶ $dbh->do( <<"END" ) || do { $l->trace( $dbh->errstr ); $dbh->rollback; return };
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do("\t\t\tCREATE TABLE Models (\n\t\t\t\tID NUMERIC(20) PRIMARY KEY,\n\t\t\t\tName text NOT NULL\n\t\t\t);\n") or do { $l->trace($dbh->errstr); $dbh->rollback; return } 11 0 11
1411 CREATE TABLE Models (
1412 ID NUMERIC(20) PRIMARY KEY,
1413 Name text NOT NULL
1414 );
1415 END
1416
1417 11 ▶ $dbh->commit or warn $dbh->errstr;
Branch: 1 branch
BranchTrueFalseTotal
$dbh->commit or warn $dbh->errstr 11 0 11
1418 }
1419
1420 17 ▶ unless ($self->_table_exists("Statements${id}")) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_table_exists("Statements$id")) 11 6 17
1421 0 ▶ $dbh->do( <<"END" ) || do { $l->trace( $dbh->errstr ); return };
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do("\t\t\tCREATE TABLE Statements$id (\n\t\t\t\tSubject NUMERIC(20) NOT NULL,\n\t\t\t\tPredicate NUMERIC(20) NOT NULL,\n\t\t\t\tObject NUMERIC(20) NOT NULL,\n\t\t\t\tContext NUMERIC(20) NOT NULL DEFAULT 0,\n\t\t\t\tPRIMARY KEY (Subject, Predicate, Object, Context)\n\t\t\t);\n") or do { $l->trace($dbh->errstr); return } 11 0 11
1422 CREATE TABLE Statements${id} (
1423 Subject NUMERIC(20) NOT NULL,
1424 Predicate NUMERIC(20) NOT NULL,
1425 Object NUMERIC(20) NOT NULL,
1426 Context NUMERIC(20) NOT NULL DEFAULT 0,
1427 PRIMARY KEY (Subject, Predicate, Object, Context)
1428 );
1429 END
1430 # $dbh->do( "DELETE FROM Models WHERE ID = ${id}") || do { $l->trace( $dbh->errstr ); $dbh->rollback; return };
1431 11 $dbh->do( "INSERT INTO Models (ID, Name) VALUES (${id}, ?)", undef, $name );
1432 }
1433
1434 }
1435  
1436 51 ▶sub _table_exists {
Subroutine _table_exists: called CC=2 SCAR=6.9
1437 51 my $self = shift;
1438 51 my $name = shift;
1439 51 my $dbh = $self->dbh;
1440 51 my $type = 'TABLE';
1441 51 my $sth = $dbh->table_info(undef, undef, $name, 'TABLE');
1442 51 my $row = $sth->fetchrow_hashref;
1443 51 ▶ return ref($row) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $row ? : 29 22 51
1444 }
1445  
1446 10 ▶sub _cleanup {
Subroutine _cleanup: called CC=3 SCAR=11.0
1447 10 my $self = shift;
1448 10 ▶ if (my $dbh = $self->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dbh = $self->dbh) 10 0 10
1449 10 my $name = $self->{model_name};
1450 10 my $id = $self->_mysql_hash( $name );
1451 10 ▶ if ($self->{ remove_store }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"remove_store"}) 2 8 10
1452 2 $dbh->do( "DROP TABLE `Statements${id}`;" );
1453 2 $dbh->do( "DELETE FROM Models WHERE Name = ?", undef, $name );
1454 }
1455 }
1456 }
1457  
1458 7 ▶sub _begin_bulk_ops {
Subroutine _begin_bulk_ops: called CC=1 SCAR=0.0
1459 7 my $self = shift;
1460 7 my $dbh = $self->dbh;
1461 7 $dbh->{AutoCommit} = 0;
1462 }
1463  
1464 157 ▶sub _end_bulk_ops {
Subroutine _end_bulk_ops: called CC=2 SCAR=6.9
1465 157 my $self = shift;
1466 157 my $dbh = $self->dbh;
1467 157 ▶ unless ($dbh->{AutoCommit}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbh->{"AutoCommit"}) 7 150 157
1468 7 $dbh->commit;
1469 }
1470 157 $dbh->{AutoCommit} = 1;
1471 }
1472  
1473 10 ▶sub DESTROY {
Subroutine DESTROY: called CC=2 SCAR=7.4
1474 10 my $self = shift;
1475 10 our $IGNORE_CLEANUP;
1476 10 ▶ if ($IGNORE_CLEANUP) {
Branch: 1 branch
BranchTrueFalseTotal
if ($RDF::Trine::Store::DBI::IGNORE_CLEANUP) { } 0 10 10
1477 0 $self->dbh->{InactiveDestroy} = 1;
1478 } else {
1479 10 $self->_cleanup;
1480 }
1481 }
1482  
1483 68 1; # Magic true value required at end of module
1484 __END__
« RDF/Trine/Store/Dydra.pm ↑ Summary RDF/Trine/Parser/NTriples.pm »