/
DBI.pm
1500 lines (1240 loc) · 39.8 KB
/
DBI.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=head1 NAME
RDF::Trine::Store::DBI - Persistent RDF storage based on DBI
=head1 VERSION
This document describes RDF::Trine::Store::DBI version 0.134
=head1 SYNOPSIS
use RDF::Trine::Store::DBI;
=head1 DESCRIPTION
RDF::Trine::Store::DBI provides a persistent triple-store using the L<DBI|DBI>
module.
=cut
package RDF::Trine::Store::DBI;
use strict;
use warnings;
no warnings 'redefine';
use base qw(RDF::Trine::Store);
use DBI;
use Carp;
use DBI;
use Scalar::Util qw(blessed reftype refaddr);
use Encode;
use Digest::MD5 ('md5');
use Math::BigInt;
use Data::Dumper;
use RDF::Trine::Node;
use RDF::Trine::Statement;
use RDF::Trine::Statement::Quad;
use RDF::Trine::Iterator;
use Log::Log4perl;
use RDF::Trine::Error;
use RDF::Trine::Store::DBI::mysql;
use RDF::Trine::Store::DBI::SQLite;
use RDF::Trine::Store::DBI::Pg;
######################################################################
our $VERSION;
BEGIN {
$VERSION = "0.134";
my $class = __PACKAGE__;
$RDF::Trine::Store::STORE_CLASSES{ $class } = $VERSION;
}
######################################################################
=head1 METHODS
Beyond the methods documented below, this class inherits methods from the
L<RDF::Trine::Store> class.
=over 4
=item C<new ( $model_name, $dbh )>
=item C<new ( $model_name, $dsn, $user, $pass )>
Returns a new storage object using the supplied arguments to construct a DBI
object for the underlying database.
=item C<new_with_config ( $hashref )>
Returns a new storage object configured with a hashref with certain
keys as arguments.
The C<storetype> key must be C<DBI> for this backend.
These keys should also be used:
=over
=item C<name>
The name of the model.
=item C<dsn>
The DBI Data Source Name for the underlying database.
=item C<username>
The username of the database user.
=item C<password>
The password of the database user.
=back
=item C<new_with_object ( $dbi_db )>
Initialize the store with a L<DBI::db> object.
=cut
sub new {
my $class = shift;
my $dbh;
my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
my $name = shift || 'model';
my %args;
if (scalar(@_) == 0) {
$l->trace("trying to construct a temporary model");
my $dsn = "dbi:SQLite:dbname=:memory:";
$dbh = DBI->connect( $dsn, '', '' );
$class = 'RDF::Trine::Store::DBI::SQLite';
} elsif (blessed($_[0]) and $_[0]->isa('DBI::db')) {
$l->trace("got a DBD handle");
$dbh = shift;
my $name = $dbh->get_info(17);
if ($name eq 'MySQL') {
$class = 'RDF::Trine::Store::DBI::mysql';
} elsif ($name eq 'PostgreSQL') {
$class = 'RDF::Trine::Store::DBI::Pg';
} elsif ($name eq 'SQLite') {
$class = 'RDF::Trine::Store::DBI::SQLite';
}
} else {
my $dsn = shift;
my $user = shift;
my $pass = shift;
if ($dsn =~ /^DBI:mysql:/) {
$class = 'RDF::Trine::Store::DBI::mysql';
} elsif ($dsn =~ /^DBI:Pg:/) {
$class = 'RDF::Trine::Store::DBI::Pg';
} elsif ($dsn =~ /^DBI:SQLite:/) {
$class = 'RDF::Trine::Store::DBI::SQLite';
$user = '';
$pass = '';
}
$l->trace("Connecting to $dsn ($user, $pass)");
$dbh = DBI->connect( $dsn, $user, $pass );
unless ($dbh) {
throw RDF::Trine::Error::DatabaseError -text => "Couldn't connect to database: " . DBI->errstr;
}
}
my $self = bless( {
model_name => $name,
dbh => $dbh,
statements_table_prefix => 'Statements',
%args
}, $class );
$self->init();
return $self;
}
sub _new_with_string {
my $class = shift;
my $config = shift;
my ($model, $dsn, $user, $pass) = split(';', $config);
return $class->new( $model, $dsn, $user, $pass );
}
sub _new_with_config {
my $class = shift;
my $config = shift;
return $class->new( $config->{name},
$config->{dsn},
$config->{username},
$config->{password} );
}
sub _new_with_object {
my $class = shift;
my $obj = shift;
return unless (blessed($obj) and $obj->isa('DBI::db'));
return $class->new( $obj );
}
=item C<< supports ( [ $feature ] ) >>
If C<< $feature >> is specified, returns true if the feature is supported by the
store, false otherwise. If C<< $feature >> is not specified, returns a list of
supported features.
=cut
sub supports {
return;
}
=item C<< temporary_store >>
=cut
sub temporary_store {
my $class = shift;
my $name = 'model_' . sprintf( '%x%x%x%x', map { int(rand(16)) } (1..4) );
my $self = $class->new( $name, @_ );
$self->{ remove_store } = 1;
$self->init();
return $self;
}
=item C<< clear_restrictions >>
Clear's the restrictions put on the binding of node types to the different
statement positions. By default, the subject position is restricted to resources
and blank nodes, and the predicate position to only resources. Calling this
method will allow any node type in any statement position.
=cut
sub clear_restrictions {
my $self = shift;
foreach my $pos (qw(subject predicate object context)) {
$self->{restrictions}{$pos} = [];
}
return;
}
=item C<< get_statements ($subject, $predicate, $object [, $context] ) >>
Returns a stream object of all statements matching the specified subject,
predicate and objects. Any of the arguments may be undef to match any value.
=cut
sub get_statements {
my $self = shift;
my @nodes = @_[0..3];
my $bound = 0;
my %bound;
my $use_quad = 0;
if (scalar(@_) >= 4) {
$use_quad = 1;
# warn "count statements with quad" if ($::debug);
my $g = $nodes[3];
if (blessed($g) and not($g->is_variable)) {
$bound++;
$bound{ 3 } = $g;
}
}
my ($subj, $pred, $obj, $context) = @nodes;
my $var = 0;
my $dbh = $self->dbh;
my $st = ($use_quad)
? RDF::Trine::Statement::Quad->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj,$context) )
: RDF::Trine::Statement->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj) );
my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
my @vars = $st->referenced_variables;
my $semantics = ($use_quad ? 'quad' : 'triple');
local($self->{context_variable_count}) = 0;
local($self->{join_context_nodes}) = 1 if (blessed($context) and $context->is_variable);
my $sql = $self->_sql_for_pattern( $st, $context, semantics => $semantics, unique => 1 );
my $sth = $dbh->prepare( $sql );
$sth->execute();
my $sub = sub {
NEXTROW:
my $row = $sth->fetchrow_hashref;
return undef unless (defined $row);
my @triple;
my $temp_var_count = 1;
my @nodes = ($st->nodes)[ $use_quad ? (0..3) : (0..2) ];
foreach my $node (@nodes) {
if ($node->is_variable) {
my $nodename = $node->name;
my $uri = $self->_column_name( $nodename, 'URI' );
my $name = $self->_column_name( $nodename, 'Name' );
my $value = $self->_column_name( $nodename, 'Value' );
my $node = $self->_column_name( $nodename, 'Node' );
if ($row->{ $node } == 0) {
push( @triple, RDF::Trine::Node::Nil->new() );
} elsif (defined( my $u = $row->{ $uri })) {
$u = decode('utf8', $u);
push( @triple, RDF::Trine::Node::Resource->new( $u ) );
} elsif (defined( my $n = $row->{ $name })) {
push( @triple, RDF::Trine::Node::Blank->new( $n ) );
} elsif (defined( my $v = $row->{ $value })) {
my @cols = map { $self->_column_name( $nodename, $_ ) } qw(Value Language Datatype);
$cols[0] = decode('utf8', $cols[0]);
$cols[2] = decode('utf8', $cols[2]);
push( @triple, RDF::Trine::Node::Literal->new( @{ $row }{ @cols } ) );
} else {
warn "node isn't nil or a resource, blank, or literal?" . Dumper($row);
goto NEXTROW;
}
} else {
push(@triple, $node);
}
}
my $st = (@triple == 3)
? RDF::Trine::Statement->new( @triple )
: RDF::Trine::Statement::Quad->new( @triple );
return $st;
};
return RDF::Trine::Iterator::Graph->new( $sub )
}
sub _column_name {
my $self = shift;
my @args = @_;
my $col = join('_', @args);
return $col;
}
=item C<< get_pattern ( $bgp [, $context] ) >>
Returns a stream object of all bindings matching the specified graph pattern.
=cut
sub get_pattern {
my $self = shift;
my $pattern = shift;
my $context = shift;
my %args = @_;
my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
$l->trace("get_pattern called for: " . $pattern->sse);
if (my $o = $args{ orderby }) {
my @ordering = @$o;
while (my ($col, $dir) = splice( @ordering, 0, 2, () )) {
no warnings 'uninitialized';
unless ($dir =~ /^(ASC|DESC)$/) {
throw RDF::Trine::Error::MethodInvocationError -text => "The sort direction for key $col must be either 'ASC' or 'DESC' in get_pattern call";
}
}
}
my $dbh = $self->dbh;
my @vars = $pattern->referenced_variables;
my %vars = map { $_ => 1 } @vars;
my $sql = $self->_sql_for_pattern( $pattern, $context, %args );
$l->debug("get_pattern sql: $sql\n");
my $sth = $dbh->prepare( $sql );
$sth->execute();
my $sub = sub {
my $row = $sth->fetchrow_hashref;
return unless $row;
my %bindings;
foreach my $nodename (@vars) {
my $uri = $self->_column_name( $nodename, 'URI' );
my $name = $self->_column_name( $nodename, 'Name' );
my $value = $self->_column_name( $nodename, 'Value' );
if (defined( my $u = $row->{ $uri })) {
$u = decode('utf8', $u);
$bindings{ $nodename } = RDF::Trine::Node::Resource->new( $u );
} elsif (defined( my $n = $row->{ $name })) {
$bindings{ $nodename } = RDF::Trine::Node::Blank->new( $n );
} elsif (defined( my $v = $row->{ $value })) {
my @cols = map { $self->_column_name( $nodename, $_ ) } qw(Value Language Datatype);
my ($val,$lang,$dt) = @{ $row }{ @cols };
$val = decode('utf8', $val);
$dt = decode('utf8', $dt);
$bindings{ $nodename } = RDF::Trine::Node::Literal->new( $val, $lang, $dt );
} else {
$bindings{ $nodename } = undef;
}
}
return RDF::Trine::VariableBindings->new( \%bindings );
};
my @args;
if (my $o = $args{ orderby }) {
my @ordering = @$o;
my @realordering;
while (my ($col, $dir) = splice( @ordering, 0, 2, () )) {
if (exists $vars{ $col }) {
push(@realordering, $col, $dir);
}
}
@args = ( sorted_by => \@realordering );
}
return RDF::Trine::Iterator::Bindings->new( $sub, \@vars, @args )
}
=item C<< get_contexts >>
Returns an RDF::Trine::Iterator over the RDF::Trine::Node objects comprising
the set of contexts of the stored quads.
=cut
sub get_contexts {
my $self = shift;
my $dbh = $self->dbh;
my $stable = $self->statements_table;
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;";
my $sth = $dbh->prepare( $sql );
$sth->execute();
my $sub = sub {
while (my $row = $sth->fetchrow_hashref) {
return unless defined($row);
my $uri = $self->_column_name( 'URI' );
my $name = $self->_column_name( 'Name' );
my $value = $self->_column_name( 'Value' );
my $ctx = $self->_column_name( 'Context' );
if ($row->{ $ctx } == 0) {
next;
# return RDF::Trine::Node::Nil->new();
} elsif ($row->{ $uri }) {
return RDF::Trine::Node::Resource->new( $row->{ $uri } );
} elsif ($row->{ $name }) {
return RDF::Trine::Node::Blank->new( $row->{ $name } );
} elsif (defined $row->{ $value }) {
my @cols = map { $self->_column_name( $_ ) } qw(Value Language Datatype);
return RDF::Trine::Node::Literal->new( @{ $row }{ @cols } );
} else {
return;
}
}
return;
};
return RDF::Trine::Iterator->new( $sub );
}
=item C<< add_statement ( $statement [, $context] ) >>
Adds the specified C<$statement> to the underlying model.
=cut
sub add_statement {
my $self = shift;
my $stmt = shift;
my $context = shift;
my $dbh = $self->dbh;
# Carp::confess unless (blessed($stmt));
my $stable = $self->statements_table;
my @nodes = $stmt->nodes;
foreach my $n (@nodes) {
$self->_add_node( $n );
}
my @values = map { $self->_mysql_node_hash( $_ ) } @nodes;
if ($stmt->isa('RDF::Trine::Statement::Quad')) {
if (blessed($context)) {
throw RDF::Trine::Error::MethodInvocationError -text => "add_statement cannot be called with both a quad and a context";
}
$context = $stmt->context;
} else {
my $cid = do {
if ($context) {
$self->_add_node( $context );
$self->_mysql_node_hash( $context );
} else {
0
}
};
push(@values, $cid);
}
my $sql = "SELECT 1 FROM ${stable} WHERE Subject = ? AND Predicate = ? AND Object = ? AND Context = ?";
my $sth = $dbh->prepare( $sql );
$sth->execute( @values );
unless ($sth->fetch) {
my $sql = sprintf( "INSERT INTO ${stable} (Subject, Predicate, Object, Context) VALUES (?,?,?,?)" );
my $sth = $dbh->prepare( $sql );
$sth->execute(@values);
}
}
=item C<< remove_statement ( $statement [, $context]) >>
Removes the specified C<$statement> from the underlying model.
=cut
sub remove_statement {
my $self = shift;
my $stmt = shift;
my $context = shift;
my $dbh = $self->dbh;
my $stable = $self->statements_table;
unless (blessed($stmt)) {
throw RDF::Trine::Error::MethodInvocationError -text => "no statement passed to remove_statement";
}
if ($stmt->isa( 'RDF::Trine::Statement::Quad' )) {
if (blessed($context)) {
throw RDF::Trine::Error::MethodInvocationError -text => "remove_statement cannot be called with both a quad and a context";
}
} else {
my @nodes = $stmt->nodes;
if (blessed($context)) {
$stmt = RDF::Trine::Statement::Quad->new( @nodes[0..2], $context );
} else {
my $nil = RDF::Trine::Node::Nil->new();
$stmt = RDF::Trine::Statement::Quad->new( @nodes[0..2], $nil );
}
}
my @nodes = $stmt->nodes;
my $sth = $dbh->prepare("DELETE FROM ${stable} WHERE Subject = ? AND Predicate = ? AND Object = ? AND Context = ?");
my @values = map { $self->_mysql_node_hash( $_ ) } (@nodes);
$sth->execute( @values );
}
=item C<< remove_statements ( $subject, $predicate, $object [, $context]) >>
Removes the specified C<$statement> from the underlying model.
=cut
sub remove_statements {
my $self = shift;
my $subj = shift;
my $pred = shift;
my $obj = shift;
my $context = shift;
my $dbh = $self->dbh;
my $stable = $self->statements_table;
my (@where, @bind);
my @keys = qw(Subject Predicate Object Context);
foreach my $node ($subj, $pred, $obj, $context) {
my $key = shift(@keys);
if (defined($node)) {
push(@bind, $node);
push(@where, "${key} = ?");
}
}
my $where = join(" AND ", @where);
my $sth = $dbh->prepare( join(' ', "DELETE FROM ${stable}", ($where ? "WHERE ${where}" : ())) );
my @values = map { $self->_mysql_node_hash( $_ ) } (@bind);
$sth->execute( @values );
}
sub _add_node {
my $self = shift;
my $node = shift;
my $hash = $self->_mysql_node_hash( $node );
my $dbh = $self->dbh;
my @cols;
my $table;
my %values;
return 1 if ($node->is_nil);
if ($node->is_blank) {
$table = "Bnodes";
@cols = qw(ID Name);
@values{ @cols } = ($hash, $node->blank_identifier);
} elsif ($node->is_resource) {
$table = "Resources";
@cols = qw(ID URI);
@values{ @cols } = ($hash, encode('utf8', $node->uri_value));
} elsif ($node->isa('RDF::Trine::Node::Literal')) {
$table = "Literals";
@cols = qw(ID Value);
@values{ @cols } = ($hash, encode('utf8', $node->literal_value));
if ($node->has_language) {
push(@cols, 'Language');
$values{ 'Language' } = $node->literal_value_language;
} elsif ($node->has_datatype) {
push(@cols, 'Datatype');
$values{ 'Datatype' } = encode('utf8', $node->literal_datatype);
}
}
my $ssql = "SELECT 1 FROM ${table} WHERE " . join(' AND ', map { join(' = ', $_, '?') } @cols);
my $sth = $dbh->prepare( $ssql );
my @values = map {"$_"} @values{ @cols };
$sth->execute( @values );
unless ($sth->fetch) {
my $sql = "INSERT INTO ${table} (" . join(', ', @cols) . ") VALUES (" . join(',',('?')x scalar(@cols)) . ")";
my $sth = $dbh->prepare( $sql );
$sth->execute( @values );
}
}
=item C<< count_statements ($subject, $predicate, $object) >>
Returns a count of all the statements matching the specified subject,
predicate and objects. Any of the arguments may be undef to match any value.
=cut
sub count_statements {
my $self = shift;
my @nodes = @_[0..3];
my $bound = 0;
my %bound;
my $use_quad = 0;
if (scalar(@_) >= 4) {
$use_quad = 1;
# warn "count statements with quad" if ($::debug);
my $g = $nodes[3];
if (blessed($g) and not($g->is_variable)) {
$bound++;
$bound{ 3 } = $g;
}
}
my ($subj, $pred, $obj, $context) = @nodes;
my $dbh = $self->dbh;
my $var = 0;
my $st = ($use_quad)
? RDF::Trine::Statement::Quad->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj,$context) )
: RDF::Trine::Statement->new( map { defined($_) ? $_ : RDF::Trine::Node::Variable->new( 'n' . $var++ ) } ($subj, $pred, $obj) );
my @vars = $st->referenced_variables;
my $semantics = ($use_quad ? 'quad' : 'triple');
my $countkey = ($use_quad) ? 'count' : 'count-distinct';
my $sql = $self->_sql_for_pattern( $st, $context, $countkey => 1, semantics => $semantics );
# $sql =~ s/SELECT\b(.*?)\bFROM/SELECT COUNT(*) AS c FROM/smo;
my $count;
my $sth = $dbh->prepare( $sql );
$sth->execute();
$sth->bind_columns( \$count );
$sth->fetch;
return $count;
}
=item C<add_uri ( $uri, $named, $format )>
Addsd the contents of the specified C<$uri> to the model.
If C<$named> is true, the data is added to the model using C<$uri> as the
named context.
=cut
=item C<add_string ( $data, $base_uri, $named, $format )>
Addsd the contents of C<$data> to the model. If C<$named> is true,
the data is added to the model using C<$base_uri> as the named context.
=cut
=item C<< add_statement ( $statement ) >>
Adds the specified C<$statement> to the underlying model.
=cut
=item C<< remove_statement ( $statement ) >>
Removes the specified C<$statement> from the underlying model.
=cut
=item C<< variable_columns ( $var ) >>
Given a variable name, returns the set of column aliases that store the values
for the column (values for Literals, URIs, and Blank Nodes).
=cut
sub variable_columns {
my $self = shift;
my $var = shift;
my $context = shift;
### ORDERING of these is important to enforce the correct sorting of results
### based on the SPARQL spec. Bnodes < IRIs < Literals, but since NULLs sort
### higher than other values, the list needs to be reversed.
my $r = $context->{restrict}{$var};
my @cols;
push(@cols, 'Value') unless ($r->{literal});
push(@cols, 'URI') unless ($r->{resource});
push(@cols, 'Name') unless ($r->{blank});
return map { "${var}_$_" } @cols;
}
=item C<< add_variable_values_joins >>
Modifies the query by adding LEFT JOINs to the tables in the database that
contain the node values (for literals, resources, and blank nodes).
=cut
my %NODE_TYPE_TABLES = (
resource => ['Resources', 'ljr', 'URI'],
literal => ['Literals', 'ljl', qw(Value Language Datatype)],
blank => ['Bnodes', 'ljb', qw(Name)]
);
sub add_variable_values_joins {
my $self = shift;
my $context = shift;
my $varhash = shift;
my $l = Log::Log4perl->get_logger("rdf.trine.store.dbi");
my @vars = keys %$varhash;
my %select_vars = map { $_ => 1 } @vars;
my %variable_value_cols;
my $vars = $context->{vars};
my $from = $context->{from_tables};
my $where = $context->{where_clauses};
my $stable = $self->statements_table;
my @cols;
my $uniq_count = 0;
my (%seen_vars, %seen_joins);
foreach my $var (grep { not $seen_vars{ $_ }++ } (sort (@vars, keys %$vars))) {
my $col = $vars->{ $var };
unless ($col) {
throw RDF::Trine::Error::CompilationError -text => "*** Nothing is known about the variable ?${var}";
}
my $col_table = (split(/[.]/, $col))[0];
my ($count) = ($col_table =~ /\w(\d+)/);
$l->info("var: $var\t\tcol: $col\t\tcount: $count\t\tunique count: $uniq_count");
push(@cols, "${col} AS ${var}_Node") if ($select_vars{ $var });
my $restricted = 0;
my @used_ljoins;
foreach my $type (reverse sort keys %NODE_TYPE_TABLES) {
my ($table, $alias, @join_cols) = @{ $NODE_TYPE_TABLES{ $type } };
if ($context->{restrict}{$var}{$type}) {
$restricted = 1;
next;
} else {
push(@used_ljoins, "${alias}${uniq_count}.$join_cols[0]");
}
foreach my $jc (@join_cols) {
my $column_real_name = "${alias}${uniq_count}.${jc}";
my $column_alias_name = "${var}_${jc}";
push(@cols, "${column_real_name} AS ${column_alias_name}");
push( @{ $variable_value_cols{ $var } }, $column_real_name);
foreach my $i (0 .. $#{ $where }) {
if ($where->[$i] =~ /\b$column_alias_name\b/) {
$where->[$i] =~ s/\b${column_alias_name}\b/${column_real_name}/g;
}
}
}
}
foreach my $i (0 .. $#{ $from }) {
my $f = $from->[ $i ];
next if ($from->[ $i ] =~ m/^[()]$/);
my ($alias) = ($f =~ m/${stable} (\w\d+)/); #split(/ /, $f))[1];
if ($alias eq $col_table) {
# my (@tables, @where);
foreach my $type (reverse sort keys %NODE_TYPE_TABLES) {
next if ($context->{restrict}{$var}{$type});
my ($vtable, $vname) = @{ $NODE_TYPE_TABLES{ $type } };
my $valias = join('', $vname, $uniq_count);
next if ($seen_joins{ $valias }++);
# push(@tables, "${vtable} ${valias}");
# push(@where, "${col} = ${valias}.ID");
$f .= " LEFT JOIN ${vtable} ${valias} ON (${col} = ${valias}.ID)";
}
# my $join = sprintf("LEFT JOIN (%s) ON (%s)", join(', ', @tables), join(' AND ', @where));
# $from->[ $i ] = join(' ', $f, $join);
$from->[ $i ] = $f;
next;
}
}
if ($restricted) {
# if we're restricting the left-joins to only certain types of nodes,
# we need to insure that the rows we're getting back actually have data
# in the left-joined columns. otherwise, we might end up with data for
# a URI, but only left-join with Bnodes (for example), and end up with
# NULL values where we aren't expecting them.
_add_where( $context, '(' . join(' OR ', map {"$_ IS NOT NULL"} @used_ljoins) . ')' );
}
$uniq_count++;
}
return (\%variable_value_cols, @cols);
}
sub _sql_for_pattern {
my $self = shift;
my $pat = shift;
my $ctx_node = shift;
my %args = @_;
my @disjunction;
my @patterns = $pat;
my $variables;
while (my $p = shift(@patterns)) {
if ($p->isa('RDF::Query::Algebra::Union')) {
push(@patterns, $p->patterns);
} else {
my $pvars = join('#', sort $p->referenced_variables);
if (@disjunction) {
# if we've already got some UNION patterns, make sure the new
# pattern has the same referenced variables (otherwise the
# columns of the result are going to come out all screwy
if ($pvars ne $variables) {
throw RDF::Trine::Error::CompilationError -text => 'All patterns in a UNION must reference the same variables.';
}
} else {
$variables = $pvars;
}
push(@disjunction, $p);
}
}
my @sql;
foreach my $pattern (@disjunction) {
my $type = $pattern->type;
my $method = "_sql_for_" . lc($type);
my $context = $self->_new_context;
# warn "*** sql compilation method $method";
if ($self->can($method)) {
$self->$method( $pattern, $ctx_node, $context, %args );
push(@sql, $self->_sql_from_context( $context, %args ));
} else {
throw RDF::Trine::Error::CompilationError ( -text => "Don't know how to turn a $type into SQL" );
}
}
return join(' UNION ', @sql);
}
sub _new_context {
my $self = shift;
my $context = {
next_alias => 0,
level => 0,
statement_table => $self->statements_table,
};
return $context;
}
use constant INDENT => "\t";
sub _sql_from_context {
my $self = shift;
my $context = shift;
my %args = @_;
my $vars = $context->{vars};
my $from = $context->{from_tables} || [];
my $where = $context->{where_clauses} || [];
my $unique = $args{'unique'} ? 1 : 0;
my ($varcols, @cols) = $self->add_variable_values_joins( $context, $vars );
unless (@cols) {
push(@cols, 1);
}
my $from_clause;
foreach my $f (@$from) {
$from_clause .= ",\n" . INDENT if ($from_clause and $from_clause =~ m/[^(]$/ and $f !~ m/^([)]|LEFT JOIN)/);
$from_clause .= $f;
}
my $where_clause = @$where ? "WHERE\n"
. INDENT . join(" AND\n" . INDENT, @$where) : '';
if ($args{ count }) {
@cols = ('COUNT(*)');
}
if ($args{ 'count-distinct' }) {
$unique = 1;
}
if ($args{ 'count' }) {
@cols = 'COUNT(*)';
}
my @sql = (
"SELECT" . ($unique ? ' DISTINCT' : ''),
INDENT . join(",\n" . INDENT, @cols),
"FROM",
INDENT . $from_clause,
$where_clause,
);
if (my $o = $args{ orderby }) {
my @ordering = @$o;
my @sort;
while (my ($col, $dir) = splice( @ordering, 0, 2, () )) {
if (exists $vars->{ $col }) {
push(@sort, map { "$_ $dir" } $self->variable_columns( $col, $context ));
}
}
if (@sort) {
push(@sql, "ORDER BY " . join(', ', @sort));
}
}
# push(@sql, $self->order_by_clause( $varcols, $level ) );
# push(@sql, $self->limit_clause( $options ) );
my $sql = join("\n", grep {length} @sql);
if ($args{ 'count-distinct' }) {
$sql = "SELECT COUNT(*) FROM ($sql) AS counttable";
}
# warn $sql;
return $sql;
}
sub _get_level { return $_[0]{level}; }
sub _next_alias { return $_[0]{next_alias}++; }
sub _statements_table { return $_[0]{statement_table}; };
sub _add_from { push( @{ $_[0]{from_tables} }, $_[1] ); }
sub _add_where { push( @{ $_[0]{where_clauses} }, $_[1] ); }
sub _get_var { return $_[0]{vars}{ $_[1] }; }
sub _add_var { $_[0]{vars}{ $_[1] } = $_[2]; }
sub _add_restriction {
my $context = shift;
my $var = shift;
my @rests = @_;
foreach my $r (@rests) {
$context->{restrict}{ $var->name }{ $r }++
}
}
sub _sql_for_filter {
my $self = shift;
my $filter = shift;
my $ctx_node = shift;
my $context = shift;
my $expr = $filter->expr;
my $pattern = $filter->pattern;
my $type = $pattern->type;
my $method = "_sql_for_" . lc($type);
$self->$method( $pattern, $ctx_node, $context );
$self->_sql_for_expr( $expr, $ctx_node, $context, @_ );
}
sub _sql_for_expr {
my $self = shift;
my $expr = shift;
my $ctx_node = shift;
my $context = shift;
### None of these should affect the context directly, since the expression
### might be a child of another expression (e.g. "isliteral(?node) || isresource(?node)")
if ($expr->isa('RDF::Query::Expression::Function')) {
my $func = $expr->uri->uri_value;
my @args = $expr->arguments;
if ($func eq 'sparql:isliteral' and blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) {
my $node = $args[0];
_add_restriction( $context, $node, qw(blank resource) );
} elsif ($func =~ qr/^sparql:is[iu]ri$/ and blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) {
my $node = $args[0];
_add_restriction( $context, $node, qw(blank literal) );
} elsif ($func =~ qr/^sparql:isblank$/ and blessed($args[0]) and $args[0]->isa('RDF::Trine::Node::Variable')) {
my $node = $args[0];
_add_restriction( $context, $node, qw(literal resource) );
} elsif ($func eq 'sparql:logical-or') {
$self->_sql_for_or_expr( $expr, $ctx_node, $context, @_ );
} else {
throw RDF::Trine::Error::CompilationError -text => "Unknown function data: " . Dumper($expr);
}
} elsif ($expr->isa('RDF::Query::Expression::Binary')) {
if ($expr->op eq '==') {
$self->_sql_for_equality_expr( $expr, $ctx_node, $context, @_ );
} else {
throw RDF::Trine::Error::CompilationError -text => "Unknown expr data: " . Dumper($expr);
}
} else {
throw RDF::Trine::Error::CompilationError -text => "Unknown expr data: " . Dumper($expr);
}
return;
}
sub _sql_for_or_expr {
my $self = shift;
my $expr = shift;
my $ctx_node = shift;
my $context = shift;
my @args = $self->_logical_or_operands( $expr );
my @disj;
foreach my $e (@args) {
my $tmp_ctx = $self->_new_context;
$self->_sql_for_expr( $e, $ctx_node, $tmp_ctx, @_ );
my ($var, $val) = %{ $tmp_ctx->{vars} };
my $existing_col = _get_var( $context, $var );
push(@disj, "${existing_col} = $val");