| 1 |
"""SQLAlchemy-based RDF store.""" |
| 2 |
import hashlib |
| 3 |
import logging |
| 4 |
|
| 5 |
import sqlalchemy |
| 6 |
from rdflib import ( |
| 7 |
BNode, |
| 8 |
Literal, |
| 9 |
URIRef |
| 10 |
) |
| 11 |
from rdflib.term import Variable |
| 12 |
from rdflib.graph import Graph, QuotedGraph |
| 13 |
from rdflib.namespace import RDF |
| 14 |
from rdflib.plugins.stores.regexmatching import PYTHON_REGEX, REGEXTerm |
| 15 |
from rdflib.store import CORRUPTED_STORE, VALID_STORE, NodePickler, Store |
| 16 |
from six import text_type |
| 17 |
from sqlalchemy import MetaData, inspect |
| 18 |
from sqlalchemy.sql import expression, select, delete |
| 19 |
from sqlalchemy.exc import OperationalError |
| 20 |
|
| 21 |
from rdflib_sqlalchemy.constants import ( |
| 22 |
ASSERTED_LITERAL_PARTITION, |
| 23 |
ASSERTED_NON_TYPE_PARTITION, |
| 24 |
ASSERTED_TYPE_PARTITION, |
| 25 |
CONTEXT_SELECT, |
| 26 |
COUNT_SELECT, |
| 27 |
INTERNED_PREFIX, |
| 28 |
QUOTED_PARTITION, |
| 29 |
TRIPLE_SELECT_NO_ORDER, |
| 30 |
) |
| 31 |
from rdflib_sqlalchemy.tables import ( |
| 32 |
create_asserted_statements_table, |
| 33 |
create_literal_statements_table, |
| 34 |
create_namespace_binds_table, |
| 35 |
create_quoted_statements_table, |
| 36 |
create_type_statements_table, |
| 37 |
get_table_names, |
| 38 |
) |
| 39 |
from rdflib_sqlalchemy.base import SQLGeneratorMixin |
| 40 |
from rdflib_sqlalchemy.sql import union_select |
| 41 |
from rdflib_sqlalchemy.statistics import StatisticsMixin |
| 42 |
from rdflib_sqlalchemy.termutils import extract_triple |
| 43 |
|
| 44 |
|
| 45 |
_logger = logging.getLogger(__name__) |
| 46 |
|
| 47 |
Any = None |
| 48 |
|
| 49 |
|
| 50 |
def grouper(iterable, n): |
| 51 |
"Collect data into chunks of at most n elements" |
| 52 |
assert n > 0, 'Cannot group into chunks of zero elements' |
| 53 |
lst = [] |
| 54 |
iterable = iter(iterable) |
| 55 |
while True: |
| 56 |
try: |
| 57 |
lst.append(next(iterable)) |
| 58 |
except StopIteration: |
| 59 |
break |
| 60 |
|
| 61 |
if len(lst) == n: |
| 62 |
yield lst |
| 63 |
lst = [] |
| 64 |
|
| 65 |
if lst: |
| 66 |
yield lst |
| 67 |
|
| 68 |
|
| 69 |
def generate_interned_id(identifier): |
| 70 |
return "{prefix}{identifier_hash}".format( |
| 71 |
prefix=INTERNED_PREFIX, |
| 72 |
identifier_hash=hashlib.sha1(identifier.encode("utf8")).hexdigest()[:10], |
| 73 |
) |
| 74 |
|
| 75 |
|
| 76 |
class SQLAlchemy(Store, SQLGeneratorMixin, StatisticsMixin): |
| 77 |
""" |
| 78 |
SQL-92 formula-aware implementation of an rdflib Store. |
| 79 |
|
| 80 |
It stores its triples in the following partitions: |
| 81 |
|
| 82 |
- Asserted non rdf:type statements |
| 83 |
- Asserted literal statements |
| 84 |
- Asserted rdf:type statements (in a table which models Class membership) |
| 85 |
The motivation for this partition is primarily query speed and |
| 86 |
scalability as most graphs will always have more rdf:type statements |
| 87 |
than others |
| 88 |
- All Quoted statements |
| 89 |
|
| 90 |
In addition it persists namespace mappings in a separate table |
| 91 |
""" |
| 92 |
|
| 93 |
context_aware = True |
| 94 |
formula_aware = True |
| 95 |
transaction_aware = True |
| 96 |
regex_matching = PYTHON_REGEX |
| 97 |
configuration = Literal("sqlite://") |
| 98 |
|
| 99 |
def __init__(self, identifier=None, configuration=None, engine=None, |
| 100 |
max_terms_per_where=800): |
| 101 |
""" |
| 102 |
Initialisation. |
| 103 |
|
| 104 |
Args: |
| 105 |
identifier (rdflib.URIRef): URIRef of the Store. Defaults to CWD. |
| 106 |
configuration: the database connection URL string or a configuration dictionary |
| 107 |
corresponding to the connection options accepted by sqlalchemy.create_engine, |
| 108 |
with the additional "url" key pointing to the connection URL. See `open` documentation |
| 109 |
for more details. |
| 110 |
engine (`sqlalchemy.engine.Engine`, optional): a pre-existing engine instance. |
| 111 |
max_terms_per_where (int): The max number of terms (s/p/o) in a call to |
| 112 |
triples_choices to combine in one SQL "where" clause. Important for SQLite |
| 113 |
back-end with SQLITE_MAX_EXPR_DEPTH limit and SQLITE_LIMIT_COMPOUND_SELECT |
| 114 |
-- must find a balance that doesn't hit either of those. |
| 115 |
""" |
| 116 |
self.identifier = identifier and identifier or "hardcoded" |
| 117 |
self.engine = engine |
| 118 |
self.max_terms_per_where = max_terms_per_where |
| 119 |
|
| 120 |
# Use only the first 10 bytes of the digest |
| 121 |
self._interned_id = generate_interned_id(self.identifier) |
| 122 |
|
| 123 |
# This parameter controls how exclusively the literal table is searched |
| 124 |
# If true, the Literal partition is searched *exclusively* if the |
| 125 |
# object term in a triple pattern is a Literal or a REGEXTerm. Note, |
| 126 |
# the latter case prevents the matching of URIRef nodes as the objects |
| 127 |
# of a triple in the store. |
| 128 |
# If the object term is a wildcard (None) |
| 129 |
# Then the Literal partition is searched in addition to the others |
| 130 |
# If this parameter is false, the literal partition is searched |
| 131 |
# regardless of what the object of the triple pattern is |
| 132 |
self.STRONGLY_TYPED_TERMS = False |
| 133 |
|
| 134 |
self.cacheHits = 0 |
| 135 |
self.cacheMisses = 0 |
| 136 |
self.literalCache = {} |
| 137 |
self.uriCache = {} |
| 138 |
self.bnodeCache = {} |
| 139 |
self.otherCache = {} |
| 140 |
self._node_pickler = None |
| 141 |
|
| 142 |
self._create_table_definitions() |
| 143 |
|
| 144 |
# XXX For backward compatibility we still support getting the connection string in constructor |
| 145 |
# TODO: deprecate this once refactoring is more mature |
| 146 |
super(SQLAlchemy, self).__init__(configuration) |
| 147 |
|
| 148 |
def __repr__(self): |
| 149 |
"""Readable serialisation.""" |
| 150 |
quoted_table = self.tables["quoted_statements"] |
| 151 |
asserted_table = self.tables["asserted_statements"] |
| 152 |
asserted_type_table = self.tables["type_statements"] |
| 153 |
literal_table = self.tables["literal_statements"] |
| 154 |
|
| 155 |
selects = [ |
| 156 |
(expression.alias(asserted_type_table, "typetable"), None, ASSERTED_TYPE_PARTITION), |
| 157 |
(expression.alias(quoted_table, "quoted"), None, QUOTED_PARTITION), |
| 158 |
(expression.alias(asserted_table, "asserted"), None, ASSERTED_NON_TYPE_PARTITION), |
| 159 |
(expression.alias(literal_table, "literal"), None, ASSERTED_LITERAL_PARTITION), |
| 160 |
] |
| 161 |
q = union_select(selects, distinct=False, select_type=COUNT_SELECT) |
| 162 |
if hasattr(self, "engine"): |
| 163 |
with self.engine.connect() as connection: |
| 164 |
res = connection.execute(q) |
| 165 |
rt = res.fetchall() |
| 166 |
typeLen, quotedLen, assertedLen, literalLen = [ |
| 167 |
rtTuple[0] for rtTuple in rt] |
| 168 |
try: |
| 169 |
return ("<Partitioned SQL N3 Store: %s " |
| 170 |
"contexts, %s classification assertions, " |
| 171 |
"%s quoted statements, %s property/value " |
| 172 |
"assertions, and %s other assertions>" % ( |
| 173 |
sum(1 for _ in self.contexts()), |
| 174 |
typeLen, quotedLen, literalLen, assertedLen)) |
| 175 |
except Exception: |
| 176 |
_logger.exception('Error creating repr') |
| 177 |
return "<Partitioned SQL N3 Store>" |
| 178 |
else: |
| 179 |
return "<Partitioned unopened SQL N3 Store>" |
| 180 |
|
| 181 |
def __len__(self, context=None): |
| 182 |
"""Number of statements in the store.""" |
| 183 |
quoted_table = self.tables["quoted_statements"] |
| 184 |
asserted_table = self.tables["asserted_statements"] |
| 185 |
asserted_type_table = self.tables["type_statements"] |
| 186 |
literal_table = self.tables["literal_statements"] |
| 187 |
|
| 188 |
typetable = expression.alias(asserted_type_table, "typetable") |
| 189 |
quoted = expression.alias(quoted_table, "quoted") |
| 190 |
asserted = expression.alias(asserted_table, "asserted") |
| 191 |
literal = expression.alias(literal_table, "literal") |
| 192 |
|
| 193 |
quotedContext = self.build_context_clause(context, quoted) |
| 194 |
assertedContext = self.build_context_clause(context, asserted) |
| 195 |
typeContext = self.build_context_clause(context, typetable) |
| 196 |
literalContext = self.build_context_clause(context, literal) |
| 197 |
|
| 198 |
if context is not None: |
| 199 |
selects = [ |
| 200 |
(typetable, typeContext, |
| 201 |
ASSERTED_TYPE_PARTITION), |
| 202 |
(quoted, quotedContext, |
| 203 |
QUOTED_PARTITION), |
| 204 |
(asserted, assertedContext, |
| 205 |
ASSERTED_NON_TYPE_PARTITION), |
| 206 |
(literal, literalContext, |
| 207 |
ASSERTED_LITERAL_PARTITION), ] |
| 208 |
q = union_select(selects, distinct=True, select_type=COUNT_SELECT) |
| 209 |
else: |
| 210 |
selects = [ |
| 211 |
(typetable, typeContext, |
| 212 |
ASSERTED_TYPE_PARTITION), |
| 213 |
(asserted, assertedContext, |
| 214 |
ASSERTED_NON_TYPE_PARTITION), |
| 215 |
(literal, literalContext, |
| 216 |
ASSERTED_LITERAL_PARTITION), ] |
| 217 |
q = union_select(selects, distinct=False, select_type=COUNT_SELECT) |
| 218 |
|
| 219 |
with self.engine.connect() as connection: |
| 220 |
res = connection.execute(q) |
| 221 |
rt = res.fetchall() |
| 222 |
return int(sum(rtTuple[0] for rtTuple in rt)) |
| 223 |
|
| 224 |
@property |
| 225 |
def table_names(self): |
| 226 |
return get_table_names(interned_id=self._interned_id) |
| 227 |
|
| 228 |
@property |
| 229 |
def node_pickler(self): |
| 230 |
if getattr(self, "_node_pickler", False) or self._node_pickler is None: |
| 231 |
self._node_pickler = np = NodePickler() |
| 232 |
np.register(self, "S") |
| 233 |
np.register(URIRef, "U") |
| 234 |
np.register(BNode, "B") |
| 235 |
np.register(Literal, "L") |
| 236 |
np.register(Graph, "G") |
| 237 |
np.register(QuotedGraph, "Q") |
| 238 |
np.register(Variable, "V") |
| 239 |
return self._node_pickler |
| 240 |
|
| 241 |
def open(self, configuration, create=True): |
| 242 |
""" |
| 243 |
Open the store specified by the configuration parameter. |
| 244 |
|
| 245 |
Args: |
| 246 |
configuration: if a string, use as the DBAPI URL. If a dictionary, will use as the |
| 247 |
``**kwargs`` for the sqlalchemy.create_engine() call, and will attempt to |
| 248 |
extract the connection URL from a 'url' key in that dictionary. A valid |
| 249 |
connection string will be of the format: |
| 250 |
|
| 251 |
dialect[+driver]://user:password@host/dbname[?key=value..] |
| 252 |
|
| 253 |
create (bool): If create is True a store will be created if it does not already |
| 254 |
exist. If create is False and a store does not already exist |
| 255 |
an exception is raised. An exception is also raised if a store |
| 256 |
exists, but there is insufficient permissions to open the |
| 257 |
store. |
| 258 |
|
| 259 |
Returns: |
| 260 |
int: |
| 261 |
- CORRUPTED_STORE (0) if database exists but is empty, |
| 262 |
- VALID_STORE (1) if database exists and tables are all there, |
| 263 |
- NO_STORE (-1) if nothing exists |
| 264 |
|
| 265 |
""" |
| 266 |
# Close any existing engine connection |
| 267 |
self.close() |
| 268 |
|
| 269 |
url, kwargs = configuration, {} |
| 270 |
if isinstance(configuration, dict): |
| 271 |
url = configuration.pop("url", None) |
| 272 |
if not url: |
| 273 |
raise Exception('Configuration dict is missing the required "url" key') |
| 274 |
kwargs = configuration |
| 275 |
|
| 276 |
self.engine = sqlalchemy.create_engine(url, **kwargs) |
| 277 |
try: |
| 278 |
conn = self.engine.connect() |
| 279 |
except OperationalError: |
| 280 |
raise RuntimeError("open() - failed during engine connection") |
| 281 |
else: |
| 282 |
with conn: |
| 283 |
if create: |
| 284 |
self.create_all() |
| 285 |
|
| 286 |
ret_value = self._verify_store_exists() |
| 287 |
|
| 288 |
if ret_value != VALID_STORE and not create: |
| 289 |
raise RuntimeError("open() - create flag was set to False, but store was not created previously.") |
| 290 |
|
| 291 |
return ret_value |
| 292 |
|
| 293 |
def create_all(self): |
| 294 |
"""Create all of the database tables (idempotent).""" |
| 295 |
self.metadata.create_all(self.engine) |
| 296 |
|
| 297 |
def close(self, commit_pending_transaction=False): |
| 298 |
""" |
| 299 |
Close the current store engine connection if one is open. |
| 300 |
""" |
| 301 |
if self.engine: |
| 302 |
self.engine.dispose() |
| 303 |
self.engine = None |
| 304 |
|
| 305 |
def destroy(self, configuration): |
| 306 |
""" |
| 307 |
Delete all tables and stored data associated with the store. |
| 308 |
""" |
| 309 |
if self.engine is None: |
| 310 |
self.engine = self.open(configuration, create=False) |
| 311 |
|
| 312 |
with self.engine.begin(): |
| 313 |
try: |
| 314 |
self.metadata.drop_all(self.engine) |
| 315 |
except Exception: |
| 316 |
_logger.exception("unable to drop table.") |
| 317 |
raise |
| 318 |
|
| 319 |
# Triple Methods |
| 320 |
|
| 321 |
def add(self, triple, context=None, quoted=False): |
| 322 |
"""Add a triple to the store of triples.""" |
| 323 |
super(SQLAlchemy, self).add(triple, context, quoted) |
| 324 |
subject, predicate, obj = triple |
| 325 |
_, statement, params = self._get_build_command( |
| 326 |
(subject, predicate, obj), |
| 327 |
context, quoted, |
| 328 |
) |
| 329 |
|
| 330 |
statement = self._add_ignore_on_conflict(statement) |
| 331 |
with self.engine.begin() as connection: |
| 332 |
try: |
| 333 |
connection.execute(statement, params) |
| 334 |
except Exception: |
| 335 |
_logger.exception( |
| 336 |
"Add failed with statement: %s, params: %s", |
| 337 |
str(statement), repr(params) |
| 338 |
) |
| 339 |
raise |
| 340 |
|
| 341 |
def addN(self, quads): |
| 342 |
"""Add a list of triples in quads form.""" |
| 343 |
commands_dict = {} |
| 344 |
add_event = super(SQLAlchemy, self).add |
| 345 |
for subject, predicate, obj, context in quads: |
| 346 |
add_event((subject, predicate, obj), context) |
| 347 |
command_type, statement, params = self._get_build_command( |
| 348 |
(subject, predicate, obj), |
| 349 |
context, |
| 350 |
isinstance(context, QuotedGraph), |
| 351 |
) |
| 352 |
|
| 353 |
command_dict = commands_dict.setdefault(command_type, {}) |
| 354 |
command_dict.setdefault("statement", statement) |
| 355 |
command_dict.setdefault("params", []).append(params) |
| 356 |
|
| 357 |
with self.engine.begin() as connection: |
| 358 |
try: |
| 359 |
for command in commands_dict.values(): |
| 360 |
statement = self._add_ignore_on_conflict(command['statement']) |
| 361 |
connection.execute(statement, command["params"]) |
| 362 |
except Exception: |
| 363 |
_logger.exception("AddN failed.") |
| 364 |
raise |
| 365 |
|
| 366 |
def _add_ignore_on_conflict(self, statement): |
| 367 |
if self.engine.name == 'sqlite': |
| 368 |
statement = statement.prefix_with('OR IGNORE') |
| 369 |
elif self.engine.name == 'mysql': |
| 370 |
statement = statement.prefix_with('IGNORE') |
| 371 |
elif self.engine.name == 'postgresql': |
| 372 |
from sqlalchemy.dialects.postgresql.dml import OnConflictDoNothing |
| 373 |
statement._post_values_clause = OnConflictDoNothing() |
| 374 |
return statement |
| 375 |
|
| 376 |
def remove(self, triple, context): |
| 377 |
"""Remove a triple from the store.""" |
| 378 |
super(SQLAlchemy, self).remove(triple, context) |
| 379 |
subject, predicate, obj = triple |
| 380 |
|
| 381 |
if context is not None: |
| 382 |
if subject is None and predicate is None and object is None: |
| 383 |
self._remove_context(context) |
| 384 |
return |
| 385 |
|
| 386 |
quoted_table = self.tables["quoted_statements"] |
| 387 |
asserted_table = self.tables["asserted_statements"] |
| 388 |
asserted_type_table = self.tables["type_statements"] |
| 389 |
literal_table = self.tables["literal_statements"] |
| 390 |
|
| 391 |
with self.engine.begin() as connection: |
| 392 |
try: |
| 393 |
if predicate is None or predicate != RDF.type: |
| 394 |
# Need to remove predicates other than rdf:type |
| 395 |
|
| 396 |
if not self.STRONGLY_TYPED_TERMS or isinstance(obj, Literal): |
| 397 |
# remove literal triple |
| 398 |
clause = self.build_clause(literal_table, subject, predicate, obj, context) |
| 399 |
connection.execute(literal_table.delete().where(clause)) |
| 400 |
|
| 401 |
for table in [quoted_table, asserted_table]: |
| 402 |
# If asserted non rdf:type table and obj is Literal, |
| 403 |
# don't do anything (already taken care of) |
| 404 |
if table == asserted_table and isinstance(obj, Literal): |
| 405 |
continue |
| 406 |
else: |
| 407 |
clause = self.build_clause(table, subject, predicate, obj, context) |
| 408 |
connection.execute(table.delete().where(clause)) |
| 409 |
|
| 410 |
if predicate == RDF.type or predicate is None: |
| 411 |
# Need to check rdf:type and quoted partitions (in addition |
| 412 |
# perhaps) |
| 413 |
clause = self.build_clause(asserted_type_table, subject, RDF.type, obj, context, True) |
| 414 |
connection.execute(asserted_type_table.delete().where(clause)) |
| 415 |
|
| 416 |
clause = self.build_clause(quoted_table, subject, predicate, obj, context) |
| 417 |
connection.execute(quoted_table.delete().where(clause)) |
| 418 |
except Exception: |
| 419 |
_logger.exception("Removal failed.") |
| 420 |
raise |
| 421 |
|
| 422 |
def _triples_helper(self, triple, context=None): |
| 423 |
subject, predicate, obj = triple |
| 424 |
|
| 425 |
quoted_table = self.tables["quoted_statements"] |
| 426 |
asserted_table = self.tables["asserted_statements"] |
| 427 |
asserted_type_table = self.tables["type_statements"] |
| 428 |
literal_table = self.tables["literal_statements"] |
| 429 |
|
| 430 |
if predicate == RDF.type: |
| 431 |
# select from asserted rdf:type partition and quoted table |
| 432 |
# (if a context is specified) |
| 433 |
typeTable = expression.alias( |
| 434 |
asserted_type_table, "typetable") |
| 435 |
clause = self.build_clause(typeTable, subject, RDF.type, obj, context, True) |
| 436 |
selects = [ |
| 437 |
(typeTable, |
| 438 |
clause, |
| 439 |
ASSERTED_TYPE_PARTITION), ] |
| 440 |
|
| 441 |
elif isinstance(predicate, REGEXTerm) \ |
| 442 |
and predicate.compiledExpr.match(RDF.type) \ |
| 443 |
or predicate is None: |
| 444 |
# Select from quoted partition (if context is specified), |
| 445 |
# Literal partition if (obj is Literal or None) and asserted |
| 446 |
# non rdf:type partition (if obj is URIRef or None) |
| 447 |
selects = [] |
| 448 |
if (not self.STRONGLY_TYPED_TERMS |
| 449 |
or isinstance(obj, Literal) |
| 450 |
or obj is None |
| 451 |
or (self.STRONGLY_TYPED_TERMS and isinstance(obj, REGEXTerm))): |
| 452 |
literal = expression.alias(literal_table, "literal") |
| 453 |
clause = self.build_clause(literal, subject, predicate, obj, context) |
| 454 |
selects.append((literal, clause, ASSERTED_LITERAL_PARTITION)) |
| 455 |
|
| 456 |
if not isinstance(obj, Literal) \ |
| 457 |
and not (isinstance(obj, REGEXTerm) and self.STRONGLY_TYPED_TERMS) \ |
| 458 |
or obj is None: |
| 459 |
asserted = expression.alias(asserted_table, "asserted") |
| 460 |
clause = self.build_clause(asserted, subject, predicate, obj, context) |
| 461 |
selects.append((asserted, clause, ASSERTED_NON_TYPE_PARTITION)) |
| 462 |
|
| 463 |
typeTable = expression.alias(asserted_type_table, "typetable") |
| 464 |
clause = self.build_clause(typeTable, subject, RDF.type, obj, context, True) |
| 465 |
selects.append((typeTable, clause, ASSERTED_TYPE_PARTITION)) |
| 466 |
|
| 467 |
elif predicate: |
| 468 |
# select from asserted non rdf:type partition (optionally), |
| 469 |
# quoted partition (if context is specified), and literal |
| 470 |
# partition (optionally) |
| 471 |
selects = [] |
| 472 |
if not self.STRONGLY_TYPED_TERMS \ |
| 473 |
or isinstance(obj, Literal) \ |
| 474 |
or obj is None \ |
| 475 |
or (self.STRONGLY_TYPED_TERMS and isinstance(obj, REGEXTerm)): |
| 476 |
literal = expression.alias(literal_table, "literal") |
| 477 |
clause = self.build_clause(literal, subject, predicate, obj, context) |
| 478 |
selects.append((literal, clause, ASSERTED_LITERAL_PARTITION)) |
| 479 |
|
| 480 |
if (obj is None or (not isinstance(obj, Literal) |
| 481 |
and not (isinstance(obj, REGEXTerm) and self.STRONGLY_TYPED_TERMS))): |
| 482 |
asserted = expression.alias(asserted_table, "asserted") |
| 483 |
clause = self.build_clause(asserted, subject, predicate, obj, context) |
| 484 |
selects.append((asserted, clause, ASSERTED_NON_TYPE_PARTITION)) |
| 485 |
|
| 486 |
if context is not None: |
| 487 |
quoted = expression.alias(quoted_table, "quoted") |
| 488 |
clause = self.build_clause(quoted, subject, predicate, obj, context) |
| 489 |
selects.append((quoted, clause, QUOTED_PARTITION)) |
| 490 |
|
| 491 |
return selects |
| 492 |
|
| 493 |
def _do_triples_select(self, selects, context): |
| 494 |
q = union_select(selects, distinct=True, select_type=TRIPLE_SELECT_NO_ORDER) |
| 495 |
with self.engine.connect() as connection: |
| 496 |
res = connection.execute(q) |
| 497 |
# TODO: False but it may have limitations on text column. Check |
| 498 |
# NOTE: SQLite does not support ORDER BY terms that aren't |
| 499 |
# integers, so the entire result set must be iterated in order |
| 500 |
# to be able to return a generator of contexts |
| 501 |
result = res.fetchall() |
| 502 |
tripleCoverage = {} |
| 503 |
|
| 504 |
for rt in result: |
| 505 |
id, s, p, o, (graphKlass, idKlass, graphId) = extract_triple(rt, self, context) |
| 506 |
contexts = tripleCoverage.get((s, p, o), []) |
| 507 |
contexts.append(graphKlass(self, idKlass(graphId))) |
| 508 |
tripleCoverage[(s, p, o)] = contexts |
| 509 |
|
| 510 |
for (s, p, o), contexts in tripleCoverage.items(): |
| 511 |
yield (s, p, o), (c for c in contexts) |
| 512 |
|
| 513 |
def triples(self, triple, context=None): |
| 514 |
""" A generator over all the triples matching a pattern. """ |
| 515 |
selects = self._triples_helper(triple, context) |
| 516 |
for m in self._do_triples_select(selects, context): |
| 517 |
yield m |
| 518 |
|
| 519 |
def triples_choices(self, triple, context=None): |
| 520 |
""" |
| 521 |
A variant of triples. |
| 522 |
""" |
| 523 |
# We already support accepting a list for s/p/o |
| 524 |
subject, predicate, object_ = triple |
| 525 |
selects = [] |
| 526 |
if isinstance(object_, list): |
| 527 |
assert not isinstance( |
| 528 |
subject, list), "object_ / subject are both lists" |
| 529 |
assert not isinstance( |
| 530 |
predicate, list), "object_ / predicate are both lists" |
| 531 |
if not object_: |
| 532 |
object_ = None |
| 533 |
for o in grouper(object_, self.max_terms_per_where): |
| 534 |
for sels in self._triples_helper((subject, predicate, o), context): |
| 535 |
selects.append(sels) |
| 536 |
|
| 537 |
elif isinstance(subject, list): |
| 538 |
assert not isinstance( |
| 539 |
predicate, list), "subject / predicate are both lists" |
| 540 |
if not subject: |
| 541 |
subject = None |
| 542 |
for s in grouper(subject, self.max_terms_per_where): |
| 543 |
for sels in self._triples_helper((s, predicate, object_), context): |
| 544 |
selects.append(sels) |
| 545 |
|
| 546 |
elif isinstance(predicate, list): |
| 547 |
assert not isinstance( |
| 548 |
subject, list), "predicate / subject are both lists" |
| 549 |
if not predicate: |
| 550 |
predicate = None |
| 551 |
for p in grouper(predicate, self.max_terms_per_where): |
| 552 |
for sels in self._triples_helper((subject, p, object_), context): |
| 553 |
selects.append(sels) |
| 554 |
|
| 555 |
for m in self._do_triples_select(selects, context): |
| 556 |
yield m |
| 557 |
|
| 558 |
def contexts(self, triple=None): |
| 559 |
quoted_table = self.tables["quoted_statements"] |
| 560 |
asserted_table = self.tables["asserted_statements"] |
| 561 |
asserted_type_table = self.tables["type_statements"] |
| 562 |
literal_table = self.tables["literal_statements"] |
| 563 |
|
| 564 |
typetable = expression.alias(asserted_type_table, "typetable") |
| 565 |
quoted = expression.alias(quoted_table, "quoted") |
| 566 |
asserted = expression.alias(asserted_table, "asserted") |
| 567 |
literal = expression.alias(literal_table, "literal") |
| 568 |
|
| 569 |
if triple is not None: |
| 570 |
subject, predicate, obj = triple |
| 571 |
if predicate == RDF.type: |
| 572 |
# Select from asserted rdf:type partition and quoted table |
| 573 |
# (if a context is specified) |
| 574 |
clause = self.build_clause(typetable, subject, RDF.type, obj, Any, True) |
| 575 |
selects = [(typetable, clause, ASSERTED_TYPE_PARTITION), ] |
| 576 |
|
| 577 |
elif (predicate is None or |
| 578 |
(isinstance(predicate, REGEXTerm) and |
| 579 |
predicate.compiledExpr.match(RDF.type))): |
| 580 |
# Select from quoted partition (if context is specified), |
| 581 |
# literal partition if (obj is Literal or None) and |
| 582 |
# asserted non rdf:type partition (if obj is URIRef |
| 583 |
# or None) |
| 584 |
clause = self.build_clause(typetable, subject, RDF.type, obj, Any, True) |
| 585 |
selects = [(typetable, clause, ASSERTED_TYPE_PARTITION), ] |
| 586 |
|
| 587 |
if (not self.STRONGLY_TYPED_TERMS or |
| 588 |
isinstance(obj, Literal) or |
| 589 |
obj is None or |
| 590 |
(self.STRONGLY_TYPED_TERMS and isinstance(obj, REGEXTerm))): |
| 591 |
clause = self.build_clause(literal, subject, predicate, obj) |
| 592 |
selects.append( |
| 593 |
(literal, clause, ASSERTED_LITERAL_PARTITION)) |
| 594 |
if not isinstance(obj, Literal) \ |
| 595 |
and not (isinstance(obj, REGEXTerm) and self.STRONGLY_TYPED_TERMS) \ |
| 596 |
or obj is None: |
| 597 |
clause = self.build_clause(asserted, subject, predicate, obj) |
| 598 |
selects.append((asserted, clause, ASSERTED_NON_TYPE_PARTITION)) |
| 599 |
|
| 600 |
elif predicate: |
| 601 |
# select from asserted non rdf:type partition (optionally), |
| 602 |
# quoted partition (if context is specified), and literal |
| 603 |
# partition (optionally) |
| 604 |
selects = [] |
| 605 |
if (not self.STRONGLY_TYPED_TERMS or |
| 606 |
isinstance(obj, Literal) or obj is None or ( |
| 607 |
self.STRONGLY_TYPED_TERMS and isinstance(obj, REGEXTerm))): |
| 608 |
clause = self.build_clause(literal, subject, predicate, obj) |
| 609 |
selects.append( |
| 610 |
(literal, clause, ASSERTED_LITERAL_PARTITION)) |
| 611 |
if not isinstance(obj, Literal) \ |
| 612 |
and not (isinstance(obj, REGEXTerm) and self.STRONGLY_TYPED_TERMS) \ |
| 613 |
or obj is None: |
| 614 |
clause = self.build_clause(asserted, subject, predicate, obj) |
| 615 |
selects.append( |
| 616 |
(asserted, clause, ASSERTED_NON_TYPE_PARTITION)) |
| 617 |
|
| 618 |
clause = self.build_clause(quoted, subject, predicate, obj) |
| 619 |
selects.append((quoted, clause, QUOTED_PARTITION)) |
| 620 |
q = union_select(selects, distinct=True, select_type=CONTEXT_SELECT) |
| 621 |
else: |
| 622 |
selects = [ |
| 623 |
(typetable, None, ASSERTED_TYPE_PARTITION), |
| 624 |
(quoted, None, QUOTED_PARTITION), |
| 625 |
(asserted, None, ASSERTED_NON_TYPE_PARTITION), |
| 626 |
(literal, None, ASSERTED_LITERAL_PARTITION), ] |
| 627 |
q = union_select(selects, distinct=True, select_type=CONTEXT_SELECT) |
| 628 |
|
| 629 |
with self.engine.connect() as connection: |
| 630 |
res = connection.execute(q) |
| 631 |
rt = res.fetchall() |
| 632 |
for context in [rtTuple[0] for rtTuple in rt]: |
| 633 |
yield URIRef(context) |
| 634 |
|
| 635 |
# Namespace persistence interface implementation |
| 636 |
|
| 637 |
def bind(self, prefix, namespace): |
| 638 |
"""Bind prefix for namespace.""" |
| 639 |
with self.engine.begin() as connection: |
| 640 |
try: |
| 641 |
binds_table = self.tables["namespace_binds"] |
| 642 |
prefix = text_type(prefix) |
| 643 |
namespace = text_type(namespace) |
| 644 |
connection.execute(delete(binds_table).where( |
| 645 |
expression.or_(binds_table.c.uri == namespace, |
| 646 |
binds_table.c.prefix == prefix))) |
| 647 |
connection.execute(binds_table.insert().values(prefix=prefix, uri=namespace)) |
| 648 |
except Exception: |
| 649 |
_logger.exception("Namespace binding failed.") |
| 650 |
raise |
| 651 |
|
| 652 |
def prefix(self, namespace): |
| 653 |
"""Prefix.""" |
| 654 |
with self.engine.begin() as connection: |
| 655 |
nb_table = self.tables["namespace_binds"] |
| 656 |
namespace = text_type(namespace) |
| 657 |
s = select(nb_table.c.prefix).where(nb_table.c.uri == namespace) |
| 658 |
res = connection.execute(s) |
| 659 |
rt = [rtTuple[0] for rtTuple in res.fetchall()] |
| 660 |
res.close() |
| 661 |
if rt and (rt[0] or rt[0] == ""): |
| 662 |
return rt[0] |
| 663 |
return None |
| 664 |
|
| 665 |
def namespace(self, prefix): |
| 666 |
res = None |
| 667 |
prefix_val = text_type(prefix) |
| 668 |
try: |
| 669 |
with self.engine.begin() as connection: |
| 670 |
nb_table = self.tables["namespace_binds"] |
| 671 |
s = select(nb_table.c.uri).where(nb_table.c.prefix == prefix_val) |
| 672 |
res = connection.execute(s) |
| 673 |
rt = [rtTuple[0] for rtTuple in res.fetchall()] |
| 674 |
res.close() |
| 675 |
return rt and URIRef(rt[0]) or None |
| 676 |
except Exception: |
| 677 |
_logger.warning('exception in namespace retrieval', exc_info=True) |
| 678 |
return None |
| 679 |
|
| 680 |
def namespaces(self): |
| 681 |
with self.engine.begin() as connection: |
| 682 |
res = connection.execute(self.tables["namespace_binds"].select().distinct()) |
| 683 |
for prefix, uri in res.fetchall(): |
| 684 |
yield prefix, uri |
| 685 |
|
| 686 |
# Private methods |
| 687 |
|
| 688 |
def _create_table_definitions(self): |
| 689 |
self.metadata = MetaData() |
| 690 |
self.tables = { |
| 691 |
"asserted_statements": create_asserted_statements_table(self._interned_id, self.metadata), |
| 692 |
"type_statements": create_type_statements_table(self._interned_id, self.metadata), |
| 693 |
"literal_statements": create_literal_statements_table(self._interned_id, self.metadata), |
| 694 |
"quoted_statements": create_quoted_statements_table(self._interned_id, self.metadata), |
| 695 |
"namespace_binds": create_namespace_binds_table(self._interned_id, self.metadata), |
| 696 |
} |
| 697 |
|
| 698 |
def _get_build_command(self, triple, context=None, quoted=False): |
| 699 |
""" |
| 700 |
Assemble the SQL Query text for adding an RDF triple to store. |
| 701 |
|
| 702 |
:param triple {tuple} - tuple of (subject, predicate, object) objects to add |
| 703 |
:param context - a `rdflib.URIRef` identifier for the graph namespace |
| 704 |
:param quoted {bool} - whether should treat as a quoted statement |
| 705 |
|
| 706 |
:returns {tuple} of (command_type, add_command, params): |
| 707 |
command_type: which kind of statement it is: literal, type, other |
| 708 |
statement: the literal SQL statement to execute (with unbound variables) |
| 709 |
params: the parameters for the SQL statement (e.g the variables to bind) |
| 710 |
|
| 711 |
""" |
| 712 |
subject, predicate, obj = triple |
| 713 |
command_type = None |
| 714 |
if quoted or predicate != RDF.type: |
| 715 |
# Quoted statement or non rdf:type predicate |
| 716 |
# check if object is a literal |
| 717 |
if isinstance(obj, Literal): |
| 718 |
statement, params = self._build_literal_triple_sql_command( |
| 719 |
subject, |
| 720 |
predicate, |
| 721 |
obj, |
| 722 |
context, |
| 723 |
) |
| 724 |
command_type = "literal" |
| 725 |
else: |
| 726 |
statement, params = self._build_triple_sql_command( |
| 727 |
subject, |
| 728 |
predicate, |
| 729 |
obj, |
| 730 |
context, |
| 731 |
quoted, |
| 732 |
) |
| 733 |
command_type = "other" |
| 734 |
elif predicate == RDF.type: |
| 735 |
# asserted rdf:type statement |
| 736 |
statement, params = self._build_type_sql_command( |
| 737 |
subject, |
| 738 |
obj, |
| 739 |
context, |
| 740 |
) |
| 741 |
command_type = "type" |
| 742 |
return command_type, statement, params |
| 743 |
|
| 744 |
def _remove_context(self, context): |
| 745 |
"""Remove context.""" |
| 746 |
assert context is not None |
| 747 |
quoted_table = self.tables["quoted_statements"] |
| 748 |
asserted_table = self.tables["asserted_statements"] |
| 749 |
asserted_type_table = self.tables["type_statements"] |
| 750 |
literal_table = self.tables["literal_statements"] |
| 751 |
|
| 752 |
with self.engine.begin() as connection: |
| 753 |
try: |
| 754 |
for table in [quoted_table, asserted_table, |
| 755 |
asserted_type_table, literal_table]: |
| 756 |
clause = self.build_context_clause(context, table) |
| 757 |
connection.execute(table.delete().where(clause)) |
| 758 |
except Exception: |
| 759 |
_logger.exception("Context removal failed.") |
| 760 |
raise |
| 761 |
|
| 762 |
def _verify_store_exists(self): |
| 763 |
""" |
| 764 |
Verify store (e.g. all tables) exist. |
| 765 |
""" |
| 766 |
|
| 767 |
for table_name in self.table_names: |
| 768 |
inspector = inspect(self.engine) |
| 769 |
if not inspector.has_table(table_name): |
| 770 |
_logger.critical("create_all() - table %s is not known", table_name) |
| 771 |
# The database exists, but one of the tables doesn't exist |
| 772 |
return CORRUPTED_STORE |
| 773 |
|
| 774 |
return VALID_STORE |