Class: RdfContext::AbstractSQLStore

Inherits:
AbstractStore show all
Includes:
TermUtils
Defined in:
lib/rdf_context/store/abstract_sql_store.rb

Overview

SQL-92 formula-aware implementation of an RDF Store. It stores it's triples in the following partitions:

  • Asserted non rdf:type statements

  • Asserted literal statements

  • Asserted rdf:type statements (in a table which models Class membership). The motivation for this partition is primarily query speed and scalability as most graphs will always have more rdf:type statements than others

  • All Quoted statements

In addition it persists namespace mappings in a seperate table

Based on Python RdfLib AbstractSQLStore

Direct Known Subclasses

ActiveRecordStore, SQLite3Store

Constant Summary

COUNT_SELECT =
0
CONTEXT_SELECT =
1
TRIPLE_SELECT =
2
TRIPLE_SELECT_NO_ORDER =
3
ASSERTED_NON_TYPE_PARTITION =
3
ASSERTED_TYPE_PARTITION =
4
QUOTED_PARTITION =
5
ASSERTED_LITERAL_PARTITION =
6
FULL_TRIPLE_PARTITIONS =
[QUOTED_PARTITION,ASSERTED_LITERAL_PARTITION]
INTERNED_PREFIX =
'kb_'
STRONGLY_TYPED_TERMS =
false

Constants included from TermUtils

TermUtils::CONTEXT, TermUtils::GRAPH_TERM_DICT, TermUtils::OBJECT, TermUtils::PREDICATE, TermUtils::REVERSE_TERM_COMBINATIONS, TermUtils::SUBJECT, TermUtils::TERM_COMBINATIONS, TermUtils::TERM_INSTANTIATION_DICT

Instance Attribute Summary

Attributes inherited from AbstractStore

#identifier

Instance Method Summary (collapse)

Methods included from TermUtils

#constructGraph, #normalizeGraph, #statement2TermCombination, #term2Letter, #type2TermCombination

Methods inherited from AbstractStore

#bnodes, #inspect, #item, #objects, #open, #predicates, #subjects

Constructor Details

- (AbstractSQLStore) initialize(identifier = nil, configuration = {})

Create a new AbstractSQLStore Store, should be subclassed @param configuration Specific to type of storage

Parameters:

  • identifier (URIRef) (defaults to: nil)

Raises:



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 39

def initialize(identifier = nil, configuration = {})
  @literalCache = {}
  @otherCache = {}
  @bnodeCache = {}
  @uriCache = {}
  
  @autocommit_default = true
  
  raise StoreException.new("Identifier must be nil or a URIRef") if identifier && !identifier.is_a?(URIRef)
  @identifier = identifier || URIRef.new("file:/#{Dir.getwd}")
  
  @internedId = INTERNED_PREFIX + Digest::SHA1.hexdigest(@identifier.to_s)[0..9] # Only first 10 bytes of digeset
  
  @db = configuration.empty? ? nil : open(configuration)
end

Instance Method Details

- (Object) _normalizeSQLCmd(cmd) (protected)

Normalize a SQL command before executing it. Commence unicode black magic



663
664
665
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 663

def _normalizeSQLCmd(cmd)
  cmd # XXX
end

- (Triple) add(triple, context = nil, quoted = false)

Add a triple to the store Add to default context, if context is nil

Parameters:

  • triple (Triple)
  • context (Graph) (defaults to: nil)

    (nil)

  • quoted (Boolean) (defaults to: false)

    (false) A quoted triple, for Formulae

Returns:



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 90

def add(triple, context = nil, quoted = false)
  context ||= @identifier
  executeSQL("SET AUTOCOMMIT=0") if @autocommit_default
  
  if quoted || triple.predicate != RDF_TYPE
    # Quoted statement or non rdf:type predicate
    # Check if object is a literal
    if triple.object.is_a?(Literal)
      addCmd, *params = self.buildLiteralTripleSQLCommand(triple, context)
    else
      addCmd, *params = self.buildTripleSQLCommand(triple, context, quoted)
    end
  elsif triple.predicate == RDF_TYPE
    addCmd, *params = self.buildTypeSQLCommand(triple.subject, triple.object, context)
  end
  
  executeSQL(addCmd, params)
end

- (Object) asserted_table (protected)



635
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 635

def asserted_table; "#{@internedId}_asserted_statements"; end

- (Object) asserted_type_table (protected)



636
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 636

def asserted_type_table; "#{@internedId}_type_statements"; end

- (Namespace) bind(namespace)

Namespace persistence interface implementation

Bind namespace to store, returns bound namespace

Parameters:

  • namespace (Nameespace)

    the namespace to bind

Returns:

  • (Namespace)

    The newly bound or pre-existing namespace.



554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 554

def bind(namespace)
  # Remove existing bindings for the same URI
  executeSQL("DELETE FROM #{namespace_binds} WHERE prefix=?", namespace.prefix.to_s)
  executeSQL("INSERT INTO #{namespace_binds} VALUES (?, ?)", namespace.prefix.to_s, namespace.uri.to_s)
  # May throw exception, should be handled in driver-specific class

  @namespaceCache ||= {}
  @namespaceUriCache ||= {}
  @nsbinding = nil
  @uri_binding = nil
  @namespaceCache[namespace.prefix] = namespace
  @namespaceUriCache[namespace.uri.to_s] = namespace.prefix
  namespace
end

- (Object) buildClause(tableName, triple, context = nil, typeTable = false) (protected)

Builds WHERE clauses for the supplied terms and, context



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
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 736

def buildClause(tableName,triple,context=nil,typeTable=false)
  parameters=[]
  if typeTable
    rdf_type_memberClause = rdf_type_klassClause = rdf_type_contextClause = nil

    # Subject clause
    clauseParts = self.buildTypeMemberClause(self.normalizeTerm(triple.subject),tableName)
    if clauseParts
      rdf_type_memberClause = clauseParts.shift
      parameters += clauseParts
    end

    # Object clause
    clauseParts = self.buildTypeClassClause(self.normalizeTerm(triple.object),tableName)
    if clauseParts
      rdf_type_klassClause = clauseParts.shift
      parameters += clauseParts
    end

    # Context clause
    clauseParts = self.buildContextClause(context,tableName)
    if clauseParts
      rdf_type_contextClause = clauseParts.shift
      parameters += clauseParts
    end

    clauses = [rdf_type_memberClause,rdf_type_klassClause,rdf_type_contextClause].compact
  else
    subjClause = predClause = objClause = contextClause = litDTypeClause = litLanguageClause = nil

    # Subject clause
    clauseParts = self.buildSubjClause(self.normalizeTerm(triple.subject),tableName)
    if clauseParts
      subjClause = clauseParts.shift
      parameters += clauseParts
    end

    # Predicate clause
    clauseParts = self.buildPredClause(self.normalizeTerm(triple.predicate),tableName)
    if clauseParts
      predClause = clauseParts.shift
      parameters += clauseParts
    end

    # Object clause
    clauseParts = self.buildObjClause(self.normalizeTerm(triple.object),tableName)
    if clauseParts
      objClause = clauseParts.shift
      parameters += clauseParts
    end

    # Context clause
    clauseParts = self.buildContextClause(context,tableName)
    if clauseParts
      contextClause = clauseParts.shift
      parameters += clauseParts
    end

    # Datatype clause
    clauseParts = self.buildLitDTypeClause(triple.object,tableName)
    if clauseParts
      litDTypeClause = clauseParts.shift
      parameters += clauseParts
    end

    # Language clause
    clauseParts = self.buildLitLanguageClause(triple.object,tableName)
    if clauseParts
      litLanguageClause = clauseParts.shift
      parameters += clauseParts
    end
    
    clauses = [subjClause,predClause,objClause,contextClause,litDTypeClause,litLanguageClause].compact
  end

  clauseString = clauses.join(' and ')
  clauseString = "WHERE #{clauseString}" unless clauseString.empty?
  
  [clauseString] + parameters
end

- (Object) buildContextClause(context, tableName) (protected)



829
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 829

def buildContextClause(context,tableName); end

- (Object) buildLitDTypeClause(obj, tableName) (protected)



817
818
819
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 817

def buildLitDTypeClause(obj,tableName)
  ["#{tableName}.objDatatype='#{obj.encoding.value}'"] if obj.is_a?(Literal) && obj.encoding
end

- (Object) buildLiteralTripleSQLCommand(triple, context) (protected)

Builds an insert command for literal triples (statements where the object is a Literal) Returns string and list of parameters



693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 693

def buildLiteralTripleSQLCommand(triple,context)
  triplePattern = statement2TermCombination(triple,context)
  [
    "INSERT INTO #{literal_table} VALUES (?, ?, ?, ?, ?,?,?)",
    normalizeTerm(triple.subject),
    normalizeTerm(triple.predicate),
    normalizeTerm(triple.object),
    normalizeTerm(context),
    triplePattern,
    (triple.object.is_a?(Literal) && triple.object.lang ? triple.object.lang.to_s : nil),
    (triple.object.is_a?(Literal) && triple.object.encoding ? triple.object.encoding.value.to_s : nil),
  ]
end

- (Object) buildLitLanguageClause(obj, tableName) (protected)



821
822
823
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 821

def buildLitLanguageClause(obj,tableName)
  ["#{tableName}.objLanguage='#{obj.lang}'"] if obj.is_a?(Literal) && obj.lang
end

- (Object) buildObjClause(obj, tableName) (protected)



828
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 828

def buildObjClause(obj,tableName); end

- (Object) buildPredClause(predicate, tableName) (protected)



827
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 827

def buildPredClause(predicate,tableName); end

- (Object) buildSubjClause(subject, tableName) (protected)

Stubs for Clause Functions that are overridden by specific implementations (MySQL vs SQLite for instance)



826
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 826

def buildSubjClause(subject,tableName); end

- (Object) buildTripleSQLCommand(triple, context, quoted) (protected)

Builds an insert command for regular triple table



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
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 708

def buildTripleSQLCommand(triple,context,quoted)
  stmt_table = quoted ? quoted_table : asserted_table
  triplePattern = statement2TermCombination(triple,context)

  if quoted
    [
      "INSERT INTO #{stmt_table} VALUES (?, ?, ?, ?, ?,?,?)",
      normalizeTerm(triple.subject),
      normalizeTerm(triple.predicate),
      normalizeTerm(triple.object),
      normalizeTerm(context),
      triplePattern,
      (triple.object.is_a?(Literal) && triple.object.lang ? triple.object.lang.to_s : nil),
      (triple.object.is_a?(Literal) && triple.object.encoding ? triple.object.encoding.value.to_s : nil),
    ]
  else
    [
      "INSERT INTO #{stmt_table} VALUES (?, ?, ?, ?, ?)",
      normalizeTerm(triple.subject),
      normalizeTerm(triple.predicate),
      normalizeTerm(triple.object),
      normalizeTerm(context),
      triplePattern
    ]
  end
end

- (Object) buildTypeClassClause(obj, tableName) (protected)



831
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 831

def buildTypeClassClause(obj,tableName); end

- (Object) buildTypeMemberClause(subject, tableName) (protected)



830
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 830

def buildTypeMemberClause(subject,tableName); end

- (Object) buildTypeSQLCommand(member, klass, context) (protected)

Builds an insert command for a type table Returns string and list of parameters



681
682
683
684
685
686
687
688
689
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 681

def buildTypeSQLCommand(member,klass,context)
  [
    "INSERT INTO #{asserted_type_table} VALUES (?, ?, ?, ?)",
    normalizeTerm(member),
    normalizeTerm(klass),
    normalizeTerm(context),
    type2TermCombination(member, klass, context)
  ]
end

- close(commit_pending_transactions = false)

This method returns an undefined value.

Close the store

Parameters:

  • commit_pending_transactions (Boolean) (defaults to: false)

    (false)



70
71
72
73
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 70

def close(commit_pending_transactions = false)
  @db.commit if commit_pending_transactions && @db.transaction_active?
  @db.close
end

- (Object) commit

Transactional interfaces



629
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 629

def commit; @db.commit; end

- (Boolean) contains?(triple, context = nil)

Check to see if this store contains the specified triple

Parameters:

  • triple (Triple)
  • context (Graph) (defaults to: nil)

    (nil)

Returns:

  • (Boolean)


303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 303

def contains?(triple, context = nil)
  #puts "contains? #{triple}"
  object = triple.object
  if object.is_a?(Literal)
    triple = Triple.new(triple.subject, triple.predicate, nil)
    triples(triple, context) do |t, cg|
      return true if t.object == object
    end
    false
  else
    !triples(triple, context).empty?
  end
end

- (true) context_aware?

Supports contexts

Returns:

  • (true)


57
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 57

def context_aware?; true; end

- (Array<Graph>) contexts(triple = nil)

Contexts containing the triple (no matching), or total number of contexts in store

Parameters:

  • triple (Triple) (defaults to: nil)

    (nil) Containing the triple/pattern if not nil

Returns:



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
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 410

def contexts(triple = nil)
  parameters = []
  
  if triple
    subject, predicate, object = triple.subject, triple.predicate, triple.object
    if predicate == RDF_TYPE
      # select from asserted rdf:type partition and quoted table (if a context is specified)
      clauseString, *params = self.buildClause('typeTable',triple,nil, true)
      parameters += params
      selects = [
        [
          asserted_type_table,
          'typeTable',
          clauseString,
          ASSERTED_TYPE_PARTITION
        ],
      ]
    #elsif predicate.is_a?(REGEXTerm) && predicate.compiledExpr.match(RDF_TYPE) || predicate.nil?
    elsif predicate.nil?
      # Select from quoted partition (if context is specified), literal partition if (obj is Literal or None) and asserted non rdf:type partition (if obj is URIRef or None)
      clauseString, *params = self.buildClause('typeTable',Triple.new(subject, RDF_TYPE, object),nil, true)
      parameters += params
      selects = [
        [
          asserted_type_table,
          'typeTable',
          clauseString,
          ASSERTED_TYPE_PARTITION
        ],
      ]

      if !STRONGLY_TYPED_TERMS || triple.object.is_a?(Literal) || triple.object.nil?
        clauseString, *params = self.buildClause('literal',triple)
        parameters += params
        selects += [
          [
            literal_table,
            'literal',
            clauseString,
            ASSERTED_LITERAL_PARTITION
          ]
        ]
      end
      if !object.is_a?(Literal) || object.nil?
        clauseString, *params = self.buildClause('asserted',triple)
        parameters += params
        selects += [
          [
            asserted_table,
            'asserted',
            clauseString,
            ASSERTED_NON_TYPE_PARTITION
          ]
        ]
      end
    elsif predicate
      # select from asserted non rdf:type partition (optionally), quoted partition (if context is speciied), and literal partition (optionally)
      selects = []
      if !STRONGLY_TYPED_TERMS || object.is_a?(Literal) || object.nil?
        clauseString, *params = self.buildClause('literal',triple)
        parameters += params
        selects += [
          [
            literal_table,
            'literal',
            clauseString,
            ASSERTED_LITERAL_PARTITION
          ]
        ]
      end
      if !object.is_a?(Literal) || object.nil?
        clauseString, *params = self.buildClause('asserted',triple)
        parameters += params
        selects += [
          [
            asserted_table,
            'asserted',
            clauseString,
            ASSERTED_NON_TYPE_PARTITION
          ]
        ]
      end
    end

    clauseString, *params = self.buildClause('quoted',triple)
    parameters += params
    selects += [
      [
        quoted_table,
        'quoted',
        clauseString,
        QUOTED_PARTITION
      ]
    ]
  else
    selects = [
      [
        asserted_type_table,
        'typeTable',
        '',
        ASSERTED_TYPE_PARTITION
      ],
      [
        quoted_table,
        'quoted',
        '',
        QUOTED_PARTITION
      ],
      [
        asserted_table,
        'asserted',
        '',
        ASSERTED_NON_TYPE_PARTITION
      ],
      [
        literal_table,
        'literal',
        '',
        ASSERTED_LITERAL_PARTITION
      ],
    ]
  end

  q=unionSELECT(selects, :distinct => true, :select_type => CONTEXT_SELECT)
  executeSQL(_normalizeSQLCmd(q), parameters).map do |row|
    id, termComb = row

    termCombString = REVERSE_TERM_COMBINATIONS[termComb.to_i]
    subjTerm, predTerm, objTerm, ctxTerm = termCombString.scan(/./)

    graphKlass, idKlass = constructGraph(ctxTerm)
    [graphKlass, idKlass.new(id)]
  end.uniq.map do |gi|
    graphKlass, id = gi
    graphKlass.new(:store => self, :identifier => id)
  end
end

- (Object) createTerm(termString, termType, objLanguage = nil, objDatatype = nil) (protected)

Takes a term value, and term type and Creates a term object. QuotedGraphs are instantiated differently



915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 915

def createTerm(termString,termType,objLanguage=nil,objDatatype=nil)
  #puts "createTerm(#{termString}, #{termType}, ...)" if ::RdfContext::debug?
  case termType
  when "L"
    @literalCache[[termString, objLanguage, objDatatype]] ||= Literal.n3_encoded(termString, objLanguage, objDatatype)
  when "F"
    @otherCache[[termType, termString]] ||= QuotedGraph(:identifier => URIRef(termString), :store => self)
  when "B"
    @bnodeCache[termString] ||= begin
      bn = BNode.new
      bn.identifier = termString
      bn
    end
  when "U"
    @uriCache[termString] || URIRef.new(termString)
#      when "V"
  else
    raise StoreException.new("Unknown termType: #{termType}")
  end
end

- (Object) destroy(configuration = {})

Destroy store or context If context is specified remove that context, otherwise, remove all triples

Parameters:

  • configuration (Hash) (defaults to: {})

    a customizable set of options

Options Hash (configuration):

  • :context (Graph)

    Remove the specified context



79
80
81
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 79

def destroy(configuration = {})
  remove(Triple.new(nil, nil, nil), configuration[:context])
end

- (Object) executeSQL(qStr, *params, &block) (protected)

This takes the query string and parameters and (depending on the SQL implementation) either fill in the parameter in-place or pass it on to the DB impl (if it supports this). The default (here) is to fill the parameters in-place surrounding each param with quote characters

Yields each row



658
659
660
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 658

def executeSQL(qStr, *params, &block)
  @db.execute(qStr, *params, &block)
end

- (Object) extractTriple(tupleRt, hardCodedContext = nil) (protected)

Takes a tuple which represents an entry in a result set and converts it to a tuple of terms using the termComb integer to interpret how to instanciate each term tupleRt is an array containing one or more of:

  • subject

  • predicate

  • obj

  • rtContext

  • termComb

  • objLanguage

  • objDatatype

Raises:



896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 896

def extractTriple(tupleRt, hardCodedContext = nil)
  subject, predicate, obj, rtContext, termComb, objLanguage, objDatatype = tupleRt

  raise StoreException, "extractTriple: unknow termComb: '#{termComb}'" unless REVERSE_TERM_COMBINATIONS.has_key?(termComb.to_i)

  context = rtContext || hardCodedContext
  termCombString = REVERSE_TERM_COMBINATIONS[termComb.to_i]
  subjTerm, predTerm, objTerm, ctxTerm = termCombString.scan(/./)
  
  s = createTerm(subject, subjTerm)
  p = createTerm(predicate, predTerm)
  o = createTerm(obj, objTerm, objLanguage, objDatatype)

  graphKlass, idKlass = constructGraph(ctxTerm)
  return [Triple.new(s, p, o), graphKlass, idKlass, context]
end

- (true) formula_aware?

Supports formulae

Returns:

  • (true)


61
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 61

def formula_aware?; true; end

- (Object) literal_table (protected)



637
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 637

def literal_table; "#{@internedId}_literal_statements"; end

- (Namespace) namespace(prefix)

Namespace for prefix

Parameters:

Returns:



572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 572

def namespace(prefix)
  @namespaceCache ||= {}
  @namespaceUriCache ||= {}
  unless @namespaceCache.has_key?(prefix.to_s)
    @namespaceCache[prefix] = nil
    executeSQL("SELECT uri FROM #{namespace_binds} WHERE prefix=?", prefix.to_s) do |row|
      @namespaceCache[prefix.to_s] = Namespace.new(row[0], prefix.to_s)
      @namespaceUriCache[row[0].to_s] = prefix.to_s
    end
  end
  @namespaceCache[prefix.to_s]
end

- (Object) namespace_binds (protected)



638
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 638

def namespace_binds; "#{@internedId}_namespace_binds"; end

- (Object) normalizeTerm(term) (protected)

T akes a term and 'normalizes' it. Literals are escaped, Graphs are replaced with just their identifiers



669
670
671
672
673
674
675
676
677
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 669

def normalizeTerm(term)
  case term
  when Graph    then normalizeTerm(term.identifier)
  when Literal  then term.to_s.rdf_escape
  when URIRef   then term.to_s.rdf_escape
  when BNode    then term.to_s
  else               term
  end
end

- (Hash{String => Namespace}) nsbinding

Hash of prefix => Namespace bindings

Returns:



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 604

def nsbinding
  unless @nsbinding.is_a?(Hash)
    @nsbinding = {}
    @uri_binding = {}
    executeSQL("SELECT prefix, uri FROM #{namespace_binds}") do |row|
      prefix, uri = row
      namespace = Namespace.new(uri, prefix)
      @nsbinding[prefix] = namespace
      # Over-write an empty prefix
      @uri_binding[uri] = namespace unless prefix.to_s.empty?
      @uri_binding[uri] ||= namespace
    end
    @nsbinding
  end
  @nsbinding
end

- (String) prefix(namespace)

Prefix for namespace

Parameters:

Returns:



588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 588

def prefix(namespace)
  uri = namespace.is_a?(Namespace) ? namespace.uri.to_s : namespace

  @namespaceCache ||= {}
  @namespaceUriCache ||= {}
  unless @namespaceUriCache.has_key?(uri.to_s)
    @namespaceUriCache[uri.to_s] = nil
    executeSQL("SELECT prefix FROM #{namespace_binds} WHERE uri=?", uri) do |row|
      @namespaceUriCache[uri.to_s] = row[0]
    end
  end
  @namespaceUriCache[uri.to_s]
end

- (Object) queryAnalysis(query) (protected)

Helper function for executing EXPLAIN on all dispatched SQL statements - for the pupose of analyzing index usage



835
836
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 835

def queryAnalysis(query)
end

- (Object) quoted_table (protected)



634
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 634

def quoted_table; "#{@internedId}_quoted_statements"; end

- remove(triple, context = nil)

This method returns an undefined value.

Remove a triple from the context and store

if subject, predicate and object are nil and context is not nil, the context is removed

Parameters:

  • triple (Triple)
  • context (Graph) (defaults to: nil)

    (nil)



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
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 116

def remove(triple, context = nil)
  if context
    if triple.subject == nil && triple.predicate.nil? && triple.object.nil?
      return remove_context(context)
    end
  end
  
  if triple.predicate.nil? || triple.predicate != RDF_TYPE
    # Remove predicates other than rdf:type
    if !STRONGLY_TYPED_TERMS || triple.object.is_a?(Literal)
      clauseString, *params = self.buildClause(literal_table,triple,context)
      if !clauseString.empty?
        cmd = "DELETE FROM #{literal_table} #{clauseString}"
      else
        cmd = "DELETE FROM #{literal_table}"
      end
      executeSQL(_normalizeSQLCmd(cmd), params)
    end
    
    [quoted_table, asserted_table].each do |table|
      # If asserted non rdf:type table and obj is Literal, don't do anything (already taken care of)
      next if table == asserted_table && triple.object.is_a?(Literal)
      
      clauseString, *params = self.buildClause(table, triple, context)
      if !clauseString.empty?
        cmd = "DELETE FROM #{table} #{clauseString}"
      else
        cmd = "DELETE FROM #{table}"
      end
      executeSQL(_normalizeSQLCmd(cmd), params)
    end
  elsif triple.predicate == RDF_TYPE || triple.predicate.nil?
    # Need to check rdf:type and quoted partitions (in addition perhaps)
    clauseString, *params = self.buildClause(asserted_type_table,triple,context, true)
    if !clauseString.empty?
      cmd = "DELETE FROM #{asserted_type_table} #{clauseString}"
    else
      cmd = "DELETE FROM #{asserted_type_table}"
    end
    executeSQL(_normalizeSQLCmd(cmd), params)

    clauseString, *params = self.buildClause(quoted_table,triple,context)
    if !clauseString.empty?
      cmd = "DELETE FROM #{quoted_table} #{clauseString}"
    else
      cmd = "DELETE FROM #{quoted_table}"
    end
    executeSQL(_normalizeSQLCmd(cmd), params)
  end
end

- (Object) remove_context(identifier) (protected)



640
641
642
643
644
645
646
647
648
649
650
651
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 640

def remove_context(identifier)
  executeSQL("SET AUTOCOMMIT=0") if @autocommit_default
  
  %w(quoted asserted type literal)
  [quoted_table,asserted_table,asserted_type_table,literal_table].each do |table|
    clauseString, *params = self.buildContextClause(identifier,table)
    executeSQL(
        _normalizeSQLCmd("DELETE from #{table} where #{clauseString}"),
        params
    )
  end
end

- (Object) rollback



631
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 631

def rollback; @db.rollback; end

- (Integer) size(context = nil)

Number of statements in the store.

Parameters:

  • context (Graph) (defaults to: nil)

    (nil)

Returns:

  • (Integer)


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
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 320

def size(context = nil)
  parameters = []
  quotedContext = assertedContext = typeContext = literalContext = nil

  clauseParts = self.buildContextClause(context,quoted_table)
  if clauseParts
    quotedContext = clauseParts.shift
    parameters += clauseParts
  end

  clauseParts = self.buildContextClause(context,asserted_table)
  if clauseParts
    assertedContext = clauseParts.shift
    parameters += clauseParts
  end

  clauseParts = self.buildContextClause(context,asserted_type_table)
  if clauseParts
    typeContext = clauseParts.shift
    parameters += clauseParts
  end

  clauseParts = self.buildContextClause(context,literal_table)
  if clauseParts
    literalContext = clauseParts.shift
    parameters += clauseParts
  end

  if context
    selects = [
      [
        asserted_type_table,
        'typeTable',
        typeContext ? 'where ' + typeContext : '',
        ASSERTED_TYPE_PARTITION
      ],
      [
        quoted_table,
        'quoted',
        quotedContext ? 'where ' + quotedContext : '',
        QUOTED_PARTITION
      ],
      [
        asserted_table,
        'asserted',
        assertedContext ? 'where ' + assertedContext : '',
        ASSERTED_NON_TYPE_PARTITION
      ],
      [
        literal_table,
        'literal',
        literalContext ? 'where ' + literalContext : '',
        ASSERTED_LITERAL_PARTITION
      ],
    ]
    q=unionSELECT(selects, :distinct => true, :select_type => COUNT_SELECT)
  else
    selects = [
      [
        asserted_type_table,
        'typeTable',
        typeContext ? 'where ' + typeContext : '',
        ASSERTED_TYPE_PARTITION
      ],
      [
        asserted_table,
        'asserted',
        assertedContext ? 'where ' + assertedContext : '',
        ASSERTED_NON_TYPE_PARTITION
      ],
      [
        literal_table,
        'literal',
        literalContext ? 'where ' + literalContext : '',
        ASSERTED_LITERAL_PARTITION
      ],
    ]
    q=unionSELECT(selects, :select_type => COUNT_SELECT)
  end

  count = 0
  executeSQL(self._normalizeSQLCmd(q), parameters) do |row|
    count += row[0].to_i
  end
  count
end

- (true) transaction_aware?

Supports transactions

Returns:

  • (true)


65
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 65

def transaction_aware?; true; end

- (Array<Triplle>) triples(triple, context = nil) {|triple, context| ... }

TODO:

These union all selects may be further optimized by joins

A generator over all the triples matching pattern.

quoted table

<id>_quoted_statements

asserted rdf:type table

<id>_type_statements

asserted non rdf:type table

<id>_asserted_statements

triple columns: subject,predicate,object,context,termComb,objLanguage,objDatatype class membership columns: member,klass,context termComb

Parameters:

  • triple (Triple)
  • context (Graph) (defaults to: nil)

    (nil)

Yields:

  • (triple, context)

Yield Parameters:

Returns:

Raises:



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
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 185

def triples(triple, context = nil)  # :yields: triple, context
  parameters = []
  
  if triple.predicate == RDF_TYPE
    # select from asserted rdf:type partition and quoted table (if a context is specified)
    clauseString, *params = self.buildClause('typeTable',triple,context, true)
    parameters += params
    selects = [
      [
        asserted_type_table,
        'typeTable',
        clauseString,
        ASSERTED_TYPE_PARTITION
      ],
    ]
  # elsif triple.predicate.is_a?(REGEXTerm) && triple.predicate.compiledExpr.match(RDF_TYPE) || triple.predicate.nil?
  elsif triple.predicate.nil?
    # Select from quoted partition (if context is specified), literal partition if (obj is Literal or None) and asserted non rdf:type partition (if obj is URIRef or None)
    selects = []
    if !STRONGLY_TYPED_TERMS || triple.object.is_a?(Literal) || triple.object.nil?
      clauseString, *params = self.buildClause('literal',triple,context)
      parameters += params
      selects += [
        [
          literal_table,
          'literal',
          clauseString,
          ASSERTED_LITERAL_PARTITION
        ]
      ]
    end
  
    if !triple.object.is_a?(Literal) || triple.object.nil?
      clauseString, *params = self.buildClause('asserted',triple,context)
      parameters += params
      selects += [
        [
          asserted_table,
          'asserted',
          clauseString,
          ASSERTED_NON_TYPE_PARTITION
        ]
      ]
    end

    clauseString, *params = self.buildClause('typeTable',Triple.new(triple.subject, RDF_TYPE, triple.object),context, true)
    parameters += params
    selects += [
      [
        asserted_type_table,
        'typeTable',
        clauseString,
        ASSERTED_TYPE_PARTITION
      ]
    ]
  elsif triple.predicate
    # select from asserted non rdf:type partition (optionally), quoted partition (if context is speciied), and literal partition (optionally)
    selects = []
    if !STRONGLY_TYPED_TERMS || triple.object.is_a?(Literal) || triple.object.nil?
      clauseString, *params = self.buildClause('literal',triple,context)
      parameters += params
      selects += [
        [
          literal_table,
          'literal',
          clauseString,
          ASSERTED_LITERAL_PARTITION
        ]
      ]
    end

    if !triple.object.is_a?(Literal) || triple.object.nil?
      clauseString, *params = self.buildClause('asserted',triple,context)
      parameters += params
      selects += [
        [
          asserted_table,
          'asserted',
          clauseString,
          ASSERTED_NON_TYPE_PARTITION
        ]
      ]
    end
  end
  
  if context
    clauseString, *params = self.buildClause('quoted',triple,context)
    parameters += params
    selects += [
      [
        quoted_table,
        'quoted',
        clauseString,
        QUOTED_PARTITION
      ]
    ]
  end
  
  q = _normalizeSQLCmd(unionSELECT(selects))
  results = []
  executeSQL(q, parameters) do |row|
    triple, graphKlass, idKlass, graphId = extractTriple(row, context)
    currentContext = graphKlass.new(:store => self, :identifier => idKlass.new(graphId))
    if block_given?
      yield(triple, currentContext)
    else
      results << triple
    end
  end
  
  results.uniq
end

- (Object) unionSELECT(selectComponents, options = {}) (protected)

Helper function for building union all select statement

options

true or false

options

Defaults to TRIPLE_SELECT

Parameters:

  • select_components:: (Array)

    list of [table_name, table_alias, table_type, where_clause]

  • options:: (Hash)

    Options



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
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 843

def unionSELECT(selectComponents, options = {})
  selectType = options[:select_type] || TRIPLE_SELECT
  selects = []
  
  selectComponents.each do |sc|
    tableName, tableAlias, whereClause, tableType = sc

    case
    when selectType == COUNT_SELECT
      selectString = "select count(*)"
      tableSource = " from #{tableName} "
    when selectType == CONTEXT_SELECT
      selectString = "select #{tableAlias}.context, " + 
                            "#{tableAlias}.termComb as termComb "
      tableSource = " from #{tableName} as #{tableAlias} "
    when FULL_TRIPLE_PARTITIONS.include?(tableType)
      selectString = "select *"
      tableSource = " from #{tableName} as #{tableAlias} "
    when tableType == ASSERTED_TYPE_PARTITION
      selectString = "select #{tableAlias}.member as subject, " +
                            "\"#{RDF_TYPE}\" as predicate, " + 
                            "#{tableAlias}.klass as object, " + 
                            "#{tableAlias}.context as context, " + 
                            "#{tableAlias}.termComb as termComb, " + 
                            "NULL as objLanguage, " + 
                            "NULL as objDatatype"
      tableSource = " from #{tableName} as #{tableAlias} "
    when tableType == ASSERTED_NON_TYPE_PARTITION
      selectString = "select *, NULL as objLanguage, NULL as objDatatype"
      tableSource = " from #{tableName} as #{tableAlias} "
    else
      raise StoreException, "unionSELECT failed to find template: selectType = #{selectType}, tableType = #{tableType}"
    end
    
    selects << "#{selectString}#{tableSource}#{whereClause}"
  end
  
  orderStmt = selectType == TRIPLE_SELECT ? " order by subject, predicate, object" : ""
  
  selects.join(options[:distinct] ? " union all ": " union ") + orderStmt
end

- (Hash{URIRef => Namespace}) uri_binding

Hash of uri => Namespace bindings

Returns:



623
624
625
626
# File 'lib/rdf_context/store/abstract_sql_store.rb', line 623

def uri_binding
  nsbinding
  @uri_binding
end