Skip to content

# `` store

### Types of store

`Context-aware`: An RDF store capable of storing statements within contexts is considered context-aware. Essentially, such a store is able to partition the RDF model it represents into individual, named, and addressable sub-graphs.

Relevant Notation3 reference regarding formulae, quoted statements, and such: http://www.w3.org/DesignIssues/Notation3.html

`Formula-aware`: An RDF store capable of distinguishing between statements that are asserted and statements that are quoted is considered formula-aware.

`Transaction-capable`: capable of providing transactional integrity to the RDF operations performed on it.

`Graph-aware`: capable of keeping track of empty graphs.

Classes:

- `NodePickler` –
- `Store` –
- `StoreCreatedEvent` –

  This event is fired when the Store is created.

- `TripleAddedEvent` –

  This event is fired when a triple is added.

- `TripleRemovedEvent` –

  This event is fired when a triple is removed.

## `` CORRUPTED_STORE `module-attribute`

    CORRUPTED_STORE = 0

## `` NO_STORE `module-attribute`

    NO_STORE = -1

## `` Pickler `module-attribute`

    Pickler = Pickler

## `` UNKNOWN `module-attribute`

    UNKNOWN: None = None

## `` Unpickler `module-attribute`

    Unpickler = Unpickler

## `` UnpicklingError `module-attribute`

    UnpicklingError = UnpicklingError

## `` VALID_STORE `module-attribute`

    VALID_STORE = 1

## `` __all__ `module-attribute`

    __all__ = ['StoreCreatedEvent', 'TripleAddedEvent', 'TripleRemovedEvent', 'NodePickler', 'Store']

## `` NodePickler

    NodePickler()

Methods:

- `__getstate__` –
- `__setstate__` –
- `dumps` –
- `loads` –
- `register` –

Source code in `rdflib/store.py`

    102
    103
    104
    105

    def __init__(self) -> None:
        self._objects: Dict[str, Any] = {}
        self._ids: Dict[Any, str] = {}
        self._get_object = self._objects.__getitem__

### `` __getstate__

    __getstate__() -> Mapping[str, Any]

Source code in `rdflib/store.py`

    138
    139
    140
    141
    142
    143
    144

    def __getstate__(self) -> Mapping[str, Any]:
        state = self.__dict__.copy()
        del state["_get_object"]
        state.update(
            {"_ids": tuple(self._ids.items()), "_objects": tuple(self._objects.items())}
        )
        return state

### `` __setstate__

    __setstate__(state: Mapping[str, Any]) -> None

Source code in `rdflib/store.py`

    146
    147
    148
    149
    150

    def __setstate__(self, state: Mapping[str, Any]) -> None:
        self.__dict__.update(state)
        self._ids = dict(self._ids)
        self._objects = dict(self._objects)
        self._get_object = self._objects.__getitem__

### `` dumps

    dumps(obj: Node, protocol: Optional[Any] = None, bin: Optional[Any] = None)

Source code in `rdflib/store.py`

    127
    128
    129
    130
    131
    132
    133
    134
    135
    136

    def dumps(
        self, obj: Node, protocol: Optional[Any] = None, bin: Optional[Any] = None
    ):
        src = BytesIO()
        p = Pickler(src)
        # NOTE on type error: https://github.com/python/mypy/issues/2427
        # type error: Cannot assign to a method
        p.persistent_id = self._get_ids  # type: ignore[assignment]
        p.dump(obj)
        return src.getvalue()

### `` loads

    loads(s: bytes) -> Node

Source code in `rdflib/store.py`

    117
    118
    119
    120
    121
    122
    123
    124
    125

    def loads(self, s: bytes) -> Node:
        up = Unpickler(BytesIO(s))
        # NOTE on type error: https://github.com/python/mypy/issues/2427
        # type error: Cannot assign to a method
        up.persistent_load = self._get_object  # type: ignore[assignment]
        try:
            return up.load()
        except KeyError as e:
            raise UnpicklingError("Could not find Node class for %s" % e)

### `` register

    register(object: Any, id: str) -> None

Source code in `rdflib/store.py`

    113
    114
    115

    def register(self, object: Any, id: str) -> None:
        self._objects[id] = object
        self._ids[object] = id

## `` Store

    Store(configuration: Optional[str] = None, identifier: Optional[Identifier] = None)

Parameters:

- ### `identifier`

  (`Optional[Identifier]`, default: `None` ) –

  URIRef of the Store. Defaults to CWD

- ### `configuration`

  (`Optional[str]`, default: `None` ) –

  String containing information open can use to connect to datastore.

Methods:

- `__len__` –

  Number of statements in the store. This should only account for non-

- `add` –

  Adds the given statement to a specific context or to the model.

- `addN` –

  Adds each item in the list of statements to a specific context.

- `add_graph` –

  Add a graph to the store, no effect if the graph already

- `bind` –

  Bind a namespace to a prefix.

- `close` –

  Closes the database connection.

- `commit` –
- `contexts` –

  Generator over all contexts in the graph. If triple is specified,

- `create` –
- `destroy` –

  Destroys the instance of the store.

- `gc` –

  Allows the store to perform any needed garbage collection.

- `namespace` –
- `namespaces` –
- `open` –

  Opens the store specified by the configuration string.

- `prefix` –
- `query` –

  If stores provide their own SPARQL implementation, override this.

- `remove` –

  Remove the set of triples matching the pattern from the store

- `remove_graph` –

  Remove a graph from the store, this should also remove all

- `rollback` –
- `triples` –

  A generator over all the triples matching the pattern. Pattern can

- `triples_choices` –

  A variant of triples that can take a list of terms instead of a single

- `update` –

  If stores provide their own (SPARQL) Update implementation, override this.

Attributes:

- `context_aware` (`bool`) –
- `dispatcher` –
- `formula_aware` (`bool`) –
- `graph_aware` (`bool`) –
- `node_pickler` (`NodePickler`) –
- `transaction_aware` (`bool`) –

Source code in `rdflib/store.py`

    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175

    def __init__(
        self,
        configuration: Optional[str] = None,
        identifier: Optional[Identifier] = None,
    ):
        """Initialize the Store.

        Args:
            identifier: URIRef of the Store. Defaults to CWD
            configuration: String containing information open can use to
                connect to datastore.
        """
        self.__node_pickler: Optional[NodePickler] = None
        self.dispatcher = Dispatcher()
        if configuration:
            self.open(configuration)

### `` __node_pickler `instance-attribute`

    __node_pickler: Optional[NodePickler] = None

### `` context_aware `class-attribute` `instance-attribute`

    context_aware: bool = False

### `` dispatcher `instance-attribute`

    dispatcher = Dispatcher()

### `` formula_aware `class-attribute` `instance-attribute`

    formula_aware: bool = False

### `` graph_aware `class-attribute` `instance-attribute`

    graph_aware: bool = False

### `` node_pickler `property`

    node_pickler: NodePickler

### `` transaction_aware `class-attribute` `instance-attribute`

    transaction_aware: bool = False

### `` __len__

    __len__(context: Optional[_ContextType] = None) -> int

Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.

Parameters:

- #### `context`

  (`Optional[_ContextType]`, default: `None` ) –

  a graph instance to query or None

Source code in `rdflib/store.py`

    367
    368
    369
    370
    371
    372
    373
    374
    375
    376

    def __len__(self, context: Optional[_ContextType] = None) -> int:  # type: ignore[empty-body]
        """
        Number of statements in the store. This should only account for non-
        quoted (asserted) statements if the context is not specified,
        otherwise it should return the number of statements in the formula or
        context given.

        Args:
            context: a graph instance to query or None
        """

### `` add

    add(triple: _TripleType, context: _ContextType, quoted: bool = False) -> None

Adds the given statement to a specific context or to the model.

Parameters:

- #### `triple`

  (`_TripleType`) –

  The triple to add

- #### `context`

  (`_ContextType`) –

  The context to add the triple to

- #### `quoted`

  (`bool`, default: `False` ) –

  If True, indicates this statement is quoted/hypothetical (for formula-aware stores)

Note

It should be an error to not specify a context and have the quoted argument be True. It should also be an error for the quoted argument to be True when the store is not formula-aware.

Source code in `rdflib/store.py`

    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255

    def add(
        self,
        triple: _TripleType,
        context: _ContextType,
        quoted: bool = False,
    ) -> None:
        """Adds the given statement to a specific context or to the model.

        Args:
            triple: The triple to add
            context: The context to add the triple to
            quoted: If True, indicates this statement is quoted/hypothetical
                (for formula-aware stores)

        Note:
            It should be an error to not specify a context and have the quoted
            argument be True. It should also be an error for the quoted argument
            to be True when the store is not formula-aware.
        """
        self.dispatcher.dispatch(TripleAddedEvent(triple=triple, context=context))

### `` addN

    addN(quads: Iterable[_QuadType]) -> None

Adds each item in the list of statements to a specific context.

The quoted argument is interpreted by formula-aware stores to indicate this statement is quoted/hypothetical.

Note

The default implementation is a redirect to add.

Parameters:

- #### `quads`

  (`Iterable[_QuadType]`) –

  An iterable of quads to add

Source code in `rdflib/store.py`

    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275

    def addN(self, quads: Iterable[_QuadType]) -> None:  # noqa: N802
        """Adds each item in the list of statements to a specific context.

        The quoted argument is interpreted by formula-aware stores to indicate this
        statement is quoted/hypothetical.

        Note:
            The default implementation is a redirect to add.

        Args:
            quads: An iterable of quads to add
        """
        for s, p, o, c in quads:
            assert c is not None, "Context associated with %s %s %s is None!" % (
                s,
                p,
                o,
            )
            self.add((s, p, o), c)

### `` add_graph

    add_graph(graph: Graph) -> None

Add a graph to the store, no effect if the graph already exists.

Parameters:

- #### `graph`

  (`Graph`) –

  a Graph instance

Source code in `rdflib/store.py`

    470
    471
    472
    473
    474
    475
    476
    477

    def add_graph(self, graph: Graph) -> None:
        """Add a graph to the store, no effect if the graph already
        exists.

        Args:
            graph: a Graph instance
        """
        raise Exception("Graph method called on non-graph_aware store")

### `` bind

    bind(prefix: str, namespace: URIRef, override: bool = True) -> None

Bind a namespace to a prefix.

Parameters:

- #### `prefix`

  (`str`) –

  The prefix to bind the namespace to.

- #### `namespace`

  (`URIRef`) –

  The URIRef of the namespace to bind.

- #### `override`

  (`bool`, default: `True` ) –

  If True, rebind even if the given namespace is already bound to another prefix

Source code in `rdflib/store.py`

    436
    437
    438
    439
    440
    441
    442
    443
    444

    def bind(self, prefix: str, namespace: URIRef, override: bool = True) -> None:
        """Bind a namespace to a prefix.

        Args:
            prefix: The prefix to bind the namespace to.
            namespace: The URIRef of the namespace to bind.
            override: If True, rebind even if the given namespace is already bound
                to another prefix
        """

### `` close

    close(commit_pending_transaction: bool = False) -> None

Closes the database connection.

Parameters:

- #### `commit_pending_transaction`

  (`bool`, default: `False` ) –

  Whether to commit all pending transactions before closing (if the store is transactional).

Source code in `rdflib/store.py`

    216
    217
    218
    219
    220
    221
    222

    def close(self, commit_pending_transaction: bool = False) -> None:
        """Closes the database connection.

        Args:
            commit_pending_transaction: Whether to commit all pending
                transactions before closing (if the store is transactional).
        """

### `` commit

    commit() -> None

Source code in `rdflib/store.py`

    462
    463

    def commit(self) -> None:
        """ """

### `` contexts

    contexts(triple: Optional[_TripleType] = None) -> Generator[_ContextType, None, None]

Generator over all contexts in the graph. If triple is specified, a generator over all contexts the triple is in.

if store is graph_aware, may also return empty contexts

:returns: a generator over Nodes

Source code in `rdflib/store.py`

    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389

    def contexts(  # type: ignore[empty-body]
        self, triple: Optional[_TripleType] = None
    ) -> Generator[_ContextType, None, None]:
        """
        Generator over all contexts in the graph. If triple is specified,
        a generator over all contexts the triple is in.

        if store is graph_aware, may also return empty contexts

        :returns: a generator over Nodes
        """

### `` create

    create(configuration: str) -> None

Source code in `rdflib/store.py`

    195
    196

    def create(self, configuration: str) -> None:
        self.dispatcher.dispatch(StoreCreatedEvent(configuration=configuration))

### `` destroy

    destroy(configuration: str) -> None

Destroys the instance of the store.

Parameters:

- #### `configuration`

  (`str`) –

  The configuration string identifying the store instance.

Source code in `rdflib/store.py`

    224
    225
    226
    227
    228
    229

    def destroy(self, configuration: str) -> None:
        """Destroys the instance of the store.

        Args:
            configuration: The configuration string identifying the store instance.
        """

### `` gc

    gc() -> None

Allows the store to perform any needed garbage collection.

Source code in `rdflib/store.py`

    231
    232
    233

    def gc(self) -> None:
        """Allows the store to perform any needed garbage collection."""
        pass

### `` namespace

    namespace(prefix: str) -> Optional[URIRef]

Source code in `rdflib/store.py`

    449
    450

    def namespace(self, prefix: str) -> Optional[URIRef]:
        """ """

### `` namespaces

    namespaces() -> Iterator[Tuple[str, URIRef]]

Source code in `rdflib/store.py`

    452
    453
    454
    455
    456
    457
    458

    def namespaces(self) -> Iterator[Tuple[str, URIRef]]:
        """ """
        # This is here so that the function becomes an empty generator.
        # See https://stackoverflow.com/q/13243766 and
        # https://www.python.org/dev/peps/pep-0255/#why-a-new-keyword-for-yield-why-not-a-builtin-function-instead
        if False:
            yield None  # type: ignore[unreachable]

### `` open

    open(configuration: Union[str, tuple[str, str]], create: bool = False) -> Optional[int]

Opens the store specified by the configuration string.

Parameters:

- #### `configuration`

  (`Union[str, tuple[str, str]]`) –

  Store configuration string

- #### `create`

  (`bool`, default: `False` ) –

  If True, a store will be created if it doesn’t exist. If False and the store doesn’t exist, an exception is raised.

Returns:

- `Optional[int]` –

  One of: VALID_STORE, CORRUPTED_STORE, or NO_STORE

Raises:

- `Exception` –

  If there are insufficient permissions to open the store.

Source code in `rdflib/store.py`

    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214

    def open(
        self, configuration: Union[str, tuple[str, str]], create: bool = False
    ) -> Optional[int]:
        """Opens the store specified by the configuration string.

        Args:
            configuration: Store configuration string
            create: If True, a store will be created if it doesn't exist.
                If False and the store doesn't exist, an exception is raised.

        Returns:
            One of: VALID_STORE, CORRUPTED_STORE, or NO_STORE

        Raises:
            Exception: If there are insufficient permissions to open the store.
        """
        return UNKNOWN

### `` prefix

    prefix(namespace: URIRef) -> Optional[str]

Source code in `rdflib/store.py`

    446
    447

    def prefix(self, namespace: URIRef) -> Optional[str]:
        """"""

### `` query

    query(query: Union[Query, str], initNs: Mapping[str, Any], initBindings: Mapping[str, Identifier], queryGraph: str, **kwargs: Any) -> Result

If stores provide their own SPARQL implementation, override this.

queryGraph is None, a URIRef or `__UNION__` If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If `__UNION__` the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)

Source code in `rdflib/store.py`

    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411

    def query(
        self,
        query: Union[Query, str],
        initNs: Mapping[str, Any],  # noqa: N803
        initBindings: Mapping[str, Identifier],  # noqa: N803
        queryGraph: str,  # noqa: N803
        **kwargs: Any,
    ) -> Result:
        """If stores provide their own SPARQL implementation, override this.

        queryGraph is None, a URIRef or `__UNION__`
        If None the graph is specified in the query-string/object
        If URIRef it specifies the graph to query,
        If  `__UNION__` the union of all named graphs should be queried
        (This is used by ConjunctiveGraphs
        Values other than None obviously only makes sense for
        context-aware stores.)
        """

        raise NotImplementedError

### `` remove

    remove(triple: _TriplePatternType, context: Optional[_ContextType] = None) -> None

Remove the set of triples matching the pattern from the store

Source code in `rdflib/store.py`

    277
    278
    279
    280
    281
    282
    283

    def remove(
        self,
        triple: _TriplePatternType,
        context: Optional[_ContextType] = None,
    ) -> None:
        """Remove the set of triples matching the pattern from the store"""
        self.dispatcher.dispatch(TripleRemovedEvent(triple=triple, context=context))

### `` remove_graph

    remove_graph(graph: Graph) -> None

Remove a graph from the store, this should also remove all triples in the graph

Parameters:

- #### `graphid`

  –

  a Graph instance

Source code in `rdflib/store.py`

    479
    480
    481
    482
    483
    484
    485
    486

    def remove_graph(self, graph: Graph) -> None:
        """Remove a graph from the store, this should also remove all
        triples in the graph

        Args:
            graphid: a Graph instance
        """
        raise Exception("Graph method called on non-graph_aware store")

### `` rollback

    rollback() -> None

Source code in `rdflib/store.py`

    465
    466

    def rollback(self) -> None:
        """ """

### `` triples

    triples(triple_pattern: _TriplePatternType, context: Optional[_ContextType] = None) -> Iterator[Tuple[_TripleType, Iterator[Optional[_ContextType]]]]

A generator over all the triples matching the pattern. Pattern can include any objects for used for comparing against nodes in the store, for example, REGEXTerm, URIRef, Literal, BNode, Variable, Graph, QuotedGraph, Date? DateRange?

Parameters:

- #### `context`

  (`Optional[_ContextType]`, default: `None` ) –

  A conjunctive query can be indicated by either providing a value of None, or a specific context can be queries by passing a Graph instance (if store is context aware).

Source code in `rdflib/store.py`

    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362

    def triples(  # type: ignore[return]
        self,
        triple_pattern: _TriplePatternType,
        context: Optional[_ContextType] = None,
    ) -> Iterator[Tuple[_TripleType, Iterator[Optional[_ContextType]]]]:
        """
        A generator over all the triples matching the pattern. Pattern can
        include any objects for used for comparing against nodes in the store,
        for example, REGEXTerm, URIRef, Literal, BNode, Variable, Graph,
        QuotedGraph, Date? DateRange?

        Args:
            context: A conjunctive query can be indicated by either
                providing a value of None, or a specific context can be
                queries by passing a Graph instance (if store is context aware).
        """
        subject, predicate, object = triple_pattern

### `` triples_choices

    triples_choices(triple: _TripleChoiceType, context: Optional[_ContextType] = None) -> Generator[Tuple[_TripleType, Iterator[Optional[_ContextType]]], None, None]

A variant of triples that can take a list of terms instead of a single term in any slot. Stores can implement this to optimize the response time from the default ‘fallback’ implementation, which will iterate over each term in the list and dispatch to triples

Source code in `rdflib/store.py`

    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343

    def triples_choices(
        self,
        triple: _TripleChoiceType,
        context: Optional[_ContextType] = None,
    ) -> Generator[
        Tuple[
            _TripleType,
            Iterator[Optional[_ContextType]],
        ],
        None,
        None,
    ]:
        """
        A variant of triples that can take a list of terms instead of a single
        term in any slot.  Stores can implement this to optimize the response
        time from the default 'fallback' implementation, which will iterate
        over each term in the list and dispatch to triples
        """
        subject, predicate, object_ = triple
        if isinstance(object_, list):
            assert not isinstance(subject, list), "object_ / subject are both lists"
            assert not isinstance(predicate, list), "object_ / predicate are both lists"
            if object_:
                for obj in object_:
                    for (s1, p1, o1), cg in self.triples(
                        (subject, predicate, obj), context
                    ):
                        yield (s1, p1, o1), cg
            else:
                for (s1, p1, o1), cg in self.triples(
                    (subject, predicate, None), context
                ):
                    yield (s1, p1, o1), cg

        elif isinstance(subject, list):
            assert not isinstance(predicate, list), "subject / predicate are both lists"
            if subject:
                for subj in subject:
                    for (s1, p1, o1), cg in self.triples(
                        (subj, predicate, object_), context
                    ):
                        yield (s1, p1, o1), cg
            else:
                for (s1, p1, o1), cg in self.triples(
                    (None, predicate, object_), context
                ):
                    yield (s1, p1, o1), cg

        elif isinstance(predicate, list):
            assert not isinstance(subject, list), "predicate / subject are both lists"
            if predicate:
                for pred in predicate:
                    for (s1, p1, o1), cg in self.triples(
                        (subject, pred, object_), context
                    ):
                        yield (s1, p1, o1), cg
            else:
                for (s1, p1, o1), cg in self.triples((subject, None, object_), context):
                    yield (s1, p1, o1), cg

### `` update

    update(update: Union[Update, str], initNs: Mapping[str, Any], initBindings: Mapping[str, Identifier], queryGraph: str, **kwargs: Any) -> None

If stores provide their own (SPARQL) Update implementation, override this.

queryGraph is None, a URIRef or `__UNION__` If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If `__UNION__` the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)

Source code in `rdflib/store.py`

    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432

    def update(
        self,
        update: Union[Update, str],
        initNs: Mapping[str, Any],  # noqa: N803
        initBindings: Mapping[str, Identifier],  # noqa: N803
        queryGraph: str,  # noqa: N803
        **kwargs: Any,
    ) -> None:
        """If stores provide their own (SPARQL) Update implementation, override this.

        queryGraph is None, a URIRef or `__UNION__`
        If None the graph is specified in the query-string/object
        If URIRef it specifies the graph to query,
        If  `__UNION__` the union of all named graphs should be queried
        (This is used by ConjunctiveGraphs
        Values other than None obviously only makes sense for
        context-aware stores.)
        """

        raise NotImplementedError

## `` StoreCreatedEvent

    StoreCreatedEvent(**kw)

Bases: `Event`

This event is fired when the Store is created.

Attributes:

- `configuration` –

  String used to create the store

Source code in `rdflib/events.py`

    55
    56

    def __init__(self, **kw):
        self.__dict__.update(kw)

## `` TripleAddedEvent

    TripleAddedEvent(**kw)

Bases: `Event`

This event is fired when a triple is added.

Attributes:

- `triple` –

  The triple added to the graph.

- `context` –

  The context of the triple, if any.

- `graph` –

  The graph to which the triple was added.

Source code in `rdflib/events.py`

    55
    56

    def __init__(self, **kw):
        self.__dict__.update(kw)

## `` TripleRemovedEvent

    TripleRemovedEvent(**kw)

Bases: `Event`

This event is fired when a triple is removed.

Attributes:

- `triple` –

  The triple removed from the graph.

- `context` –

  The context of the triple, if any.

- `graph` –

  The graph from which the triple was removed.

Source code in `rdflib/events.py`

    55
    56

    def __init__(self, **kw):
        self.__dict__.update(kw)