Package
SparqlModel — SPARQL ORM for RDF triple stores.
The SQLModel of SPARQL: typed models, SPARQLSession
as the main entry point, and Python queries that compile to SPARQL.
Requires triplemodel>=0.12 and pyoxigraph for in-process graphs; SparqlModel owns the
session, query compiler, stores, and cascade policy.
- class sparqlmodel.AsyncHttpStore(endpoint, *, read_endpoint=None, write_endpoint=None, graph=None, prefixes=None, auth=None, bearer_token=None, headers=None, timeout=30.0, client=None, mirror_mode='writer', max_retries=2, retry_backoff=0.5, max_triples_per_update=500, query_method='post', graph_store_url=None)[source]
Bases:
objectAsync SPARQL 1.1 endpoint store with a local
triplemodel.Storemirror.Same semantics as
HttpStore, usinghttpx.AsyncClientfor non-blocking remote I/O. Supports optionalread_endpoint/write_endpoint,mirror_mode, chunked UPDATE (max_triples_per_update), retries (max_retries/retry_backoff), andquery_methodpostvsgetfor SELECT.Mirror limitations: Data written outside this store instance is visible to
query/executebut not tograph,get, or cascade until the mirror is updated. Usepull_subjects_into_mirror(),sync_mirror()(whengraph_store_urlis set), orget(auto-pull) to hydrate from remote. PreferAsyncMemoryStorefor asyncio tests. Assume a single writer per endpoint.If both
authandbearer_tokenare set, Basicauthwins forAuthorization.- __init__(endpoint, *, read_endpoint=None, write_endpoint=None, graph=None, prefixes=None, auth=None, bearer_token=None, headers=None, timeout=30.0, client=None, mirror_mode='writer', max_retries=2, retry_backoff=0.5, max_triples_per_update=500, query_method='post', graph_store_url=None)[source]
- property graph: RdfGraph
- property graph_store_url: str | None
Graph Store HTTP URL for
sync_mirror()(optional).
- property mirror_generation: int
Monotonic counter bumped when the local mirror is wholesale or partially replaced.
- property mirror_mode: Literal['writer', 'remote_authoritative']
Mirror mode —
writer(default) orremote_authoritative.
- property namespaces: NamespaceRegistry
- async pull_subjects_into_mirror(iris)[source]
Fetch triples for
irisfrom the remote endpoint into the local mirror.
- property query_method: Literal['post', 'get']
How remote SELECT queries are sent —
post(default) orget.
- async sync_mirror()[source]
Replace the local mirror with the remote default graph (Graph Store HTTP GET).
- class sparqlmodel.AsyncMemoryStore(graph=None, *, prefixes=None)[source]
Bases:
objectIn-memory RDF store with async methods delegating to sync
MemoryStore.- property graph: RdfGraph
- property namespaces
- class sparqlmodel.AsyncSPARQLSession(store=None, *, prefixes=None, autoflush=True, close_on_exit=True, rollback_on_error=True)[source]
Bases:
objectAsync ORM session: CRUD, queries, and graph sync with the backing store.
Use as an async context manager:
async with AsyncSPARQLSession(store=AsyncHttpStore(endpoint)) as session: await session.put(model)
Same identity map, hydration, and cascade semantics as
SPARQLSession. Not safe to share across concurrent asyncio tasks; use one session per task.- __init__(store=None, *, prefixes=None, autoflush=True, close_on_exit=True, rollback_on_error=True)[source]
- async expunge(model)[source]
Detach
modelfrom the identity map and hydration cache (store unchanged).
- async get(model_cls, iri, *, depth=0)[source]
Load a model by IRI with optional relationship depth.
- Return type:
SPARQLModel | None
- property graph: RdfGraph
- async hydrate_bindings(model_cls, bindings, *, depth=0, polymorphic=False)[source]
Hydrate query results with identity map and session cache.
- Return type:
- async merge(model)[source]
Return the session instance for
model’s identity key (no store write).- Return type:
- property namespaces: NamespaceRegistry
- async refresh(model, *, depth=0)[source]
Reload
modelfrom the store atdepth(updates cached instance when present).- Return type:
- property store: AsyncStoreProtocol
- class sparqlmodel.BackPopulates(field, model)[source]
Bases:
objectLink a field to the inverse-side field on another model (SparqlModel
back_populates).- __init__(field, model)
- exception sparqlmodel.ConfigurationError[source]
Bases:
SparqlModelErrorRaised when a model or session is misconfigured.
- sparqlmodel.Field(predicate, *, lang=None, inverse=None, literal_datatype=None, transitive=False, back_populates=None, **kwargs)[source]
Map a model attribute to an RDF predicate.
- Parameters:
predicate (str) – Compact or absolute IRI (e.g.
schema:name).lang (str | None) – Default language tag for string literals (
Langmetadata).inverse (str | None) – Inverse predicate IRI for import-only triples.
literal_datatype (str | None) – XSD datatype CURIE for typed literals.
transitive (bool) – Expand multi-valued object URIs transitively on import.
back_populates (Any) –
BackPopulates,inverse_pair, or(Model, field)tuple.**kwargs (Any) – Additional arguments passed to
pydantic.Field.
- Return type:
- exception sparqlmodel.HydrationError[source]
Bases:
SparqlModelErrorRaised when query results cannot be hydrated into models.
- class sparqlmodel.HttpStore(endpoint, *, read_endpoint=None, write_endpoint=None, graph=None, prefixes=None, auth=None, bearer_token=None, headers=None, timeout=30.0, client=None, mirror_mode='writer', max_retries=2, retry_backoff=0.5, max_triples_per_update=500, query_method='post', graph_store_url=None)[source]
Bases:
objectSPARQL 1.1 endpoint store with a local
triplemodel.Storemirror.update_graphpushesINSERT DATA/DELETE DATAto the remote endpoint (chunked whenmax_triples_per_updateis exceeded) and applies the mirror delta only after all remote chunks succeed.queryexecutes SELECT against the remote read endpoint (POST by default, optional GET viaquery_method).Optional
read_endpoint/write_endpointsupport Fuseki-style split URLs (defaults toendpointfor both). Transient HTTP failures (502/503/504, connection errors) are retried permax_retries/retry_backoff.Mirror limitations: Data written outside this store instance (another app, admin UI, or raw SPARQL UPDATE) is visible to
query/executebut not tograph,get, or cascade/orphan logic until the mirror is updated. Usepull_subjects_into_mirror(),sync_mirror()(Graph Store HTTP GET whengraph_store_urlis set), orget(which pulls automatically) to hydrate the mirror from the remote dataset. PreferMemoryStorefor single-process apps and tests. Assume a single writer per endpoint when usingHttpStore.If both
authandbearer_tokenare set, Basicauthwins forAuthorization.- __init__(endpoint, *, read_endpoint=None, write_endpoint=None, graph=None, prefixes=None, auth=None, bearer_token=None, headers=None, timeout=30.0, client=None, mirror_mode='writer', max_retries=2, retry_backoff=0.5, max_triples_per_update=500, query_method='post', graph_store_url=None)[source]
- property graph: RdfGraph
- property graph_store_url: str | None
Graph Store HTTP URL for
sync_mirror()(optional).
- property mirror_generation: int
Monotonic counter bumped when the local mirror is wholesale or partially replaced.
- property mirror_mode: Literal['writer', 'remote_authoritative']
Mirror mode —
writer(default) orremote_authoritative.
- property namespaces: NamespaceRegistry
- pull_subjects_into_mirror(iris)[source]
Fetch triples for
irisfrom the remote endpoint into the local mirror.
- property query_method: Literal['post', 'get']
How remote SELECT queries are sent —
post(default) orget.
- sync_mirror()[source]
Replace the local mirror with the remote default graph (Graph Store HTTP GET).
Requires
graph_store_urlon construction. Does not modify the remote dataset. For per-subject hydration usepull_subjects_into_mirror()instead.
- class sparqlmodel.Lang(code, direction=None)[source]
Bases:
objectField metadata: serialize
strvalues with a fixed language tag.- __init__(code, direction=None)
- class sparqlmodel.LangString(value, lang=None, direction=None)[source]
Bases:
objectA literal string value with an optional language tag and text direction.
- __init__(value, lang=None, direction=None)
- class sparqlmodel.MemoryStore(graph=None, *, prefixes=None)[source]
Bases:
objectIn-memory RDF store using
Store.- property graph: RdfGraph
- property mirror_generation: int
Monotonic counter;
0for in-memory stores (no wholesale mirror sync).
- property namespaces: NamespaceRegistry
- class sparqlmodel.MultiLangString(mapping=None, /, **langs)[source]
Bases:
objectMultiple language-tagged literals for one predicate, keyed by language code.
Use on a single field when the graph has several
@langobjects on the same predicate (for examplerdfs:label@enandrdfs:label@fr). Export emits one triple per entry; import collects all language-tagged literals on the field.- classmethod from_mapping(mapping)[source]
Build from a language code → value map (
Noneentries are omitted).- Return type:
- get(lang, default=None)[source]
- Return type:
LangString | None
- by_lang: Mapping[str, LangString]
- class sparqlmodel.OntologyRegistry(_graph=None, _parent_to_children=<factory>, _registered_inverse_forward=<factory>, _registered_inverse_reverse=<factory>, _graph_inverse_forward=<factory>, _graph_inverse_reverse=<factory>)[source]
Bases:
objectSubclass and
owl:inverseOfhints from an ontology graph and/or static registration.Use
subtypes_of()for descendant type IRIs (subclasses). For ancestor types (superclasses of a given class), usesubclass_uris()on a graph that containsrdfs:subClassOfaxioms.- __init__(_graph=None, _parent_to_children=<factory>, _registered_inverse_forward=<factory>, _registered_inverse_reverse=<factory>, _graph_inverse_forward=<factory>, _graph_inverse_reverse=<factory>)
- classmethod from_graph(graph)[source]
Build a registry backed by
graph(typically parsed OWL/RDFS Turtle).- Return type:
- classmethod from_ttl(path, *, format=None, base_iri=None)[source]
Parse a Turtle (or other) ontology file into a new registry.
- Return type:
- inverse_of(predicate_uri)[source]
Return the inverse property IRI for
predicate_uri, if known.- Return type:
str | None
- load_graph(graph)[source]
Use
graphforsubtypes_of()andinverse_of()queries.
- register_inverse(forward_predicate, inverse_predicate)[source]
Register an
owl:inverseOfpair (both directions are queryable).
- exception sparqlmodel.QueryError[source]
Bases:
SparqlModelErrorRaised when a query cannot be compiled or executed.
- sparqlmodel.Relationship(predicate, *, model=None, cascade=True, inverse=None, back_populates=None, **kwargs)[source]
Map a model attribute to an RDF object relationship.
- Parameters:
predicate (str) – Compact or absolute IRI (e.g.
schema:worksFor).model (type[Any] | None) – Related
SPARQLModelclass (inferred from annotation when omitted).cascade (bool) – When
False, nested resources are not included in put/delete cascade.inverse (str | None) – Inverse predicate for import (not with
ref_field).back_populates (Any) – Paired inverse field on another model (TripleModel 0.12+).
**kwargs (Any) – Additional arguments passed to
pydantic.Field.
- Return type:
- class sparqlmodel.ResourceRef(iri)[source]
Bases:
objectReference to an RDF resource identified by IRI.
- __init__(iri)
- class sparqlmodel.SPARQLModel(*, id=None)[source]
Bases:
TripleModelORM entity mapped to RDF; persist and query via
SPARQLSession.- classmethod get_prefixes()[source]
Return namespace prefixes for this model (includes built-in RDF prefixes).
- classmethod iter_sparql_fields()[source]
Yield (name, field_info, annotation) for mapped fields excluding id.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'str_strip_whitespace': False, 'validate_assignment': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_dump_jsonld()[source]
Serialize to a JSON-LD dict for APIs (cascade-aware ORM view).
For RDF files or HTTP bodies with all triples, use
serialize(format="json-ld")(inherited from TripleModel) instead.
- classmethod model_validate_jsonld(data)[source]
Deserialize from a JSON-LD dict (ORM presentation layer).
For RDF files, use
parse()(inherited from TripleModel) orimport_graph().- Return type:
- class sparqlmodel.SPARQLSession(store=None, *, prefixes=None, autoflush=True, close_on_exit=True, rollback_on_error=True)[source]
Bases:
objectORM session: CRUD, queries, and graph sync with the backing store.
Use as a context manager to flush pending writes on success, discard the pending queue on error, and close the backing store when it supports
HttpStore.close()when usingHttpStore:with SPARQLSession(store=HttpStore(endpoint)) as session: session.put(model)
Already-flushed writes are not rolled back on error; only the pending queue from
put(..., flush=False)is affected. Full transactional rollback may be added in a future release.Not thread-safe; use one session per thread or asyncio task.
- __init__(store=None, *, prefixes=None, autoflush=True, close_on_exit=True, rollback_on_error=True)[source]
- classmethod from_rdf_file(path, *, format='turtle', prefixes=None, autoflush=True, close_on_exit=True, rollback_on_error=True)[source]
Open a session over an on-disk RDF file.
Uses an in-memory
MemoryStore. Parsespathwith TripleModelload_graph(pass aPath, not file contents as a string). Use for tutorials, fixtures, and ETL that starts from Turtle, TriG, or other supported formats beforeput/query.- Parameters:
format (str) – RDF format hint (e.g.
"turtle","trig"); inferred from extension when omitted onload_graph.prefixes (Mapping[str, str] | None) – Namespace prefixes merged into the session registry and graph.
autoflush (bool) – Passed to
__init__().close_on_exit (bool) – Passed to
__init__().rollback_on_error (bool) – Passed to
__init__().
- Return type:
- get(model_cls, iri, *, depth=0)[source]
Load a model by IRI with optional relationship depth.
- Return type:
SPARQLModel | None
- property graph: RdfGraph
- hydrate_bindings(model_cls, bindings, *, depth=0, polymorphic=False)[source]
Hydrate query results with identity map and session cache.
- Return type:
- merge(model)[source]
Return the session instance for
model’s identity key (no store write).- Return type:
- property namespaces: NamespaceRegistry
- refresh(model, *, depth=0)[source]
Reload
modelfrom the store atdepth(updates cached instance when present).- Return type:
- property store: StoreProtocol
- sparqlmodel.SchemaRegistry
alias of
OntologyRegistry
- exception sparqlmodel.StaleTripleWarning[source]
Bases:
UserWarningWarn when
add()may leave stale triples on an existing subject.
- class sparqlmodel.TypedLiteral(value, datatype=None)[source]
Bases:
objectOne RDF literal value with its own XSD (or custom) datatype IRI.
Use as the element type of
set[TypedLiteral]orlist[TypedLiteral]when several objects on one predicate may carry different^^datatypeIRIs. Field-levelliteral_datatype=applies one datatype to every object; this type preserves each graph literal’s datatype independently.
- sparqlmodel.inverse_pair(model, field)[source]
Shorthand for
BackPopulates.Pass a class or a string name (
inverse_pair("Organization", "employees")) when the peer model is declared later in the same module.- Return type:
- sparqlmodel.not_(expr)[source]
Negate a filter expression (SPARQL
FILTER NOT EXISTS/ boolean NOT).- Return type:
- sparqlmodel.property_eq(model_cls, path, value)[source]
property_pathshorthand for equality.- Return type: