| 1 |
"""Convenience functions for working with Terms and Graphs.""" |
| 2 |
from rdflib import BNode, Graph, Literal, URIRef, Variable |
| 3 |
from rdflib.graph import QuotedGraph |
| 4 |
|
| 5 |
from rdflib_sqlalchemy.constants import ( |
| 6 |
TERM_COMBINATIONS, |
| 7 |
TERM_INSTANTIATION_DICT, |
| 8 |
REVERSE_TERM_COMBINATIONS, |
| 9 |
) |
| 10 |
|
| 11 |
__all__ = ["extract_triple"] |
| 12 |
|
| 13 |
|
| 14 |
SUBJECT = 0 |
| 15 |
PREDICATE = 1 |
| 16 |
OBJECT = 2 |
| 17 |
CONTEXT = 3 |
| 18 |
|
| 19 |
GRAPH_TERM_DICT = { |
| 20 |
"F": (QuotedGraph, URIRef), |
| 21 |
"U": (Graph, URIRef), |
| 22 |
"B": (Graph, BNode) |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
def normalize_graph(graph): |
| 27 |
""" |
| 28 |
Take an instance of a ``Graph`` and return the instance's identifier and ``type``. |
| 29 |
|
| 30 |
Types are ``U`` for a :class:`~rdflib.graph.Graph`, ``F`` for |
| 31 |
a :class:`~rdflib.graph.QuotedGraph` and ``B`` for a |
| 32 |
:class:`~rdflib.graph.ConjunctiveGraph` |
| 33 |
|
| 34 |
>>> from rdflib import plugin |
| 35 |
>>> from rdflib.graph import Graph, ConjunctiveGraph, QuotedGraph |
| 36 |
>>> from rdflib.store import Store |
| 37 |
>>> from rdflib import URIRef, Namespace |
| 38 |
>>> from rdflib_sqlalchemy.termutils import normalize_graph |
| 39 |
>>> memstore = plugin.get('IOMemory', Store)() |
| 40 |
>>> g = Graph(memstore, URIRef("http://purl.org/net/bel-epa/gjh")) |
| 41 |
>>> normalize_graph(g) |
| 42 |
(rdflib.term.URIRef(u'http://purl.org/net/bel-epa/gjh'), 'U') |
| 43 |
>>> g = ConjunctiveGraph(memstore, Namespace("http://rdflib.net/ns")) |
| 44 |
>>> normalize_graph(g) #doctest: +ELLIPSIS |
| 45 |
(rdflib.term.URIRef(u'http://rdflib.net/ns'), 'U') |
| 46 |
>>> g = QuotedGraph(memstore, Namespace("http://rdflib.net/ns")) |
| 47 |
>>> normalize_graph(g) |
| 48 |
(rdflib.term.URIRef(u'http://rdflib.net/ns'), 'F') |
| 49 |
|
| 50 |
""" |
| 51 |
if isinstance(graph, QuotedGraph): |
| 52 |
return graph.identifier, "F" |
| 53 |
else: |
| 54 |
return graph.identifier, term_to_letter(graph.identifier) |
| 55 |
|
| 56 |
|
| 57 |
def term_to_letter(term): |
| 58 |
""" |
| 59 |
Relate a given term to one of several key types. |
| 60 |
|
| 61 |
* :class:`~rdflib.term.BNode`, |
| 62 |
* :class:`~rdflib.term.Literal`, |
| 63 |
* :class:`~rdflib.term.URIRef`, |
| 64 |
* :class:`~rdflib.term.Variable` |
| 65 |
* :class:`~rdflib.graph.Graph` |
| 66 |
* :class:`~rdflib.graph.QuotedGraph` |
| 67 |
|
| 68 |
>>> from rdflib import URIRef |
| 69 |
>>> from rdflib.term import BNode |
| 70 |
>>> from rdflib.graph import Graph, QuotedGraph |
| 71 |
>>> from rdflib_sqlalchemy.termutils import term_to_letter |
| 72 |
>>> term_to_letter(URIRef('http://purl.org/net/bel-epa.com/')) |
| 73 |
'U' |
| 74 |
>>> term_to_letter(BNode()) |
| 75 |
'B' |
| 76 |
>>> term_to_letter(Literal(u'')) # noqa |
| 77 |
'L' |
| 78 |
>>> term_to_letter(Variable(u'x')) # noqa |
| 79 |
'V' |
| 80 |
>>> term_to_letter(Graph()) |
| 81 |
'B' |
| 82 |
>>> term_to_letter(QuotedGraph("IOMemory", None)) |
| 83 |
'F' |
| 84 |
>>> term_to_letter(None) |
| 85 |
'L' |
| 86 |
""" |
| 87 |
if isinstance(term, URIRef): |
| 88 |
return "U" |
| 89 |
elif isinstance(term, BNode): |
| 90 |
return "B" |
| 91 |
elif isinstance(term, Literal): |
| 92 |
return "L" |
| 93 |
elif isinstance(term, QuotedGraph): |
| 94 |
return "F" |
| 95 |
elif isinstance(term, Variable): |
| 96 |
return "V" |
| 97 |
elif isinstance(term, Graph): |
| 98 |
return term_to_letter(term.identifier) |
| 99 |
elif term is None: |
| 100 |
return "L" |
| 101 |
else: |
| 102 |
raise Exception( |
| 103 |
("The given term (%s) is not an instance of any " + |
| 104 |
"of the known types (URIRef, BNode, Literal, QuotedGraph, " + |
| 105 |
"or Variable). It is a %s") |
| 106 |
% (term, type(term))) |
| 107 |
|
| 108 |
|
| 109 |
def construct_graph(key): |
| 110 |
""" |
| 111 |
Return a tuple containing a ``Graph`` and an appropriate referent. |
| 112 |
|
| 113 |
Takes a key (one of 'F', 'U' or 'B') |
| 114 |
|
| 115 |
>>> from rdflib_sqlalchemy.termutils import construct_graph |
| 116 |
>>> construct_graph('F') |
| 117 |
(<class 'rdflib.graph.QuotedGraph'>, <class 'rdflib.term.URIRef'>) |
| 118 |
>>> construct_graph('U') |
| 119 |
(<class 'rdflib.graph.Graph'>, <class 'rdflib.term.URIRef'>) |
| 120 |
>>> construct_graph('B') |
| 121 |
(<class 'rdflib.graph.Graph'>, <class 'rdflib.term.BNode'>) |
| 122 |
|
| 123 |
""" |
| 124 |
return GRAPH_TERM_DICT[key] |
| 125 |
|
| 126 |
|
| 127 |
def triple_pattern_to_term_combinations(triple): |
| 128 |
"""Map a triple pattern to term combinations (non-functioning).""" |
| 129 |
s, p, o = triple |
| 130 |
combinations = [] |
| 131 |
if isinstance(o, Literal): |
| 132 |
for key, val in TERM_COMBINATIONS.items(): |
| 133 |
if key[OBJECT] == 'O': |
| 134 |
combinations.append(val) |
| 135 |
return combinations |
| 136 |
|
| 137 |
|
| 138 |
def type_to_term_combination(member, klass, context): |
| 139 |
"""Map a type to a term combination.""" |
| 140 |
term_combination = '{subject}U{object}{context}'.format( |
| 141 |
subject=term_to_letter(member), |
| 142 |
object=term_to_letter(klass), |
| 143 |
context=normalize_graph(context)[-1], |
| 144 |
) |
| 145 |
|
| 146 |
try: |
| 147 |
return TERM_COMBINATIONS[term_combination] |
| 148 |
except KeyError: |
| 149 |
if isinstance(member, Literal): |
| 150 |
raise ValueError( |
| 151 |
'A Literal cannot be a subject of a triple.\n\n' |
| 152 |
'Triple causing error:\n' |
| 153 |
' {member} rdf:type {klass}\n' |
| 154 |
'Context: {context}'.format( |
| 155 |
member=member, |
| 156 |
klass=klass, |
| 157 |
context=context, |
| 158 |
) |
| 159 |
) |
| 160 |
|
| 161 |
raise |
| 162 |
|
| 163 |
|
| 164 |
def statement_to_term_combination(subject, predicate, obj, context): |
| 165 |
"""Map a statement to a Term Combo.""" |
| 166 |
return TERM_COMBINATIONS["%s%s%s%s" % |
| 167 |
(term_to_letter(subject), term_to_letter(predicate), |
| 168 |
term_to_letter(obj), normalize_graph(context)[-1])] |
| 169 |
|
| 170 |
|
| 171 |
def escape_quotes(qstr): |
| 172 |
""" |
| 173 |
Escape backslashes. |
| 174 |
|
| 175 |
#FIXME: This *may* prove to be a performance bottleneck and should |
| 176 |
perhaps be implemented in C (as it was in 4Suite RDF) |
| 177 |
|
| 178 |
Ported from Ft.Lib.DbUtil |
| 179 |
""" |
| 180 |
if qstr is None: |
| 181 |
return "" |
| 182 |
tmp = qstr.replace("\\", "\\\\") |
| 183 |
tmp = tmp.replace("'", "\\'") |
| 184 |
return tmp |
| 185 |
|
| 186 |
|
| 187 |
def extract_triple(tupleRt, store, hardCodedContext=None): |
| 188 |
""" |
| 189 |
Extract a triple. |
| 190 |
|
| 191 |
Take a tuple which represents an entry in a result set and |
| 192 |
converts it to a tuple of terms using the termComb integer |
| 193 |
to interpret how to instantiate each term. |
| 194 |
|
| 195 |
""" |
| 196 |
try: |
| 197 |
id, subject, predicate, obj, rtContext, termComb, \ |
| 198 |
objLanguage, objDatatype = tupleRt |
| 199 |
termCombString = REVERSE_TERM_COMBINATIONS[termComb] |
| 200 |
subjTerm, predTerm, objTerm, ctxTerm = termCombString |
| 201 |
except ValueError: |
| 202 |
id, subject, subjTerm, predicate, predTerm, obj, objTerm, \ |
| 203 |
rtContext, ctxTerm, objLanguage, objDatatype = tupleRt |
| 204 |
|
| 205 |
context = rtContext is not None \ |
| 206 |
and rtContext \ |
| 207 |
or hardCodedContext.identifier |
| 208 |
s = create_term(subject, subjTerm, store) |
| 209 |
p = create_term(predicate, predTerm, store) |
| 210 |
o = create_term(obj, objTerm, store, objLanguage, objDatatype) |
| 211 |
|
| 212 |
graphKlass, idKlass = construct_graph(ctxTerm) |
| 213 |
|
| 214 |
return id, s, p, o, (graphKlass, idKlass, context) |
| 215 |
|
| 216 |
|
| 217 |
def create_term(termString, termType, store, objLanguage=None, objDatatype=None): |
| 218 |
""" |
| 219 |
Take a term value, term type, and store instance and creates a term object. |
| 220 |
|
| 221 |
QuotedGraphs are instantiated differently |
| 222 |
""" |
| 223 |
if termType == "L": |
| 224 |
cache = store.literalCache.get((termString, objLanguage, objDatatype)) |
| 225 |
if cache is not None: |
| 226 |
|
| 227 |
return cache |
| 228 |
else: |
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
if objLanguage and not objDatatype: |
| 233 |
rt = Literal(termString, objLanguage) |
| 234 |
store.literalCache[((termString, objLanguage))] = rt |
| 235 |
elif objDatatype and not objLanguage: |
| 236 |
rt = Literal(termString, datatype=objDatatype) |
| 237 |
store.literalCache[((termString, objDatatype))] = rt |
| 238 |
elif not objLanguage and not objDatatype: |
| 239 |
rt = Literal(termString) |
| 240 |
store.literalCache[((termString))] = rt |
| 241 |
else: |
| 242 |
rt = Literal(termString, objDatatype) |
| 243 |
store.literalCache[((termString, objDatatype))] = rt |
| 244 |
return rt |
| 245 |
elif termType == "F": |
| 246 |
cache = store.otherCache.get((termType, termString)) |
| 247 |
if cache is not None: |
| 248 |
|
| 249 |
return cache |
| 250 |
else: |
| 251 |
|
| 252 |
rt = QuotedGraph(store, URIRef(termString)) |
| 253 |
store.otherCache[(termType, termString)] = rt |
| 254 |
return rt |
| 255 |
elif termType == "B": |
| 256 |
cache = store.bnodeCache.get((termString)) |
| 257 |
if cache is not None: |
| 258 |
|
| 259 |
return cache |
| 260 |
else: |
| 261 |
|
| 262 |
rt = TERM_INSTANTIATION_DICT[termType](termString) |
| 263 |
store.bnodeCache[(termString)] = rt |
| 264 |
return rt |
| 265 |
elif termType == "U": |
| 266 |
cache = store.uriCache.get((termString)) |
| 267 |
if cache is not None: |
| 268 |
|
| 269 |
return cache |
| 270 |
else: |
| 271 |
|
| 272 |
rt = URIRef(termString) |
| 273 |
store.uriCache[(termString)] = rt |
| 274 |
return rt |
| 275 |
else: |
| 276 |
cache = store.otherCache.get((termType, termString)) |
| 277 |
if cache is not None: |
| 278 |
|
| 279 |
return cache |
| 280 |
else: |
| 281 |
|
| 282 |
rt = TERM_INSTANTIATION_DICT[termType](termString) |
| 283 |
store.otherCache[(termType, termString)] = rt |
| 284 |
return rt |