API reference
pyjelly
Modules:
| Name | Description |
|---|---|
errors |
|
integrations |
|
jelly |
|
options |
|
parse |
|
serialize |
|
errors
Classes:
| Name | Description |
|---|---|
JellyConformanceError |
Raised when Jelly conformance is violated. |
JellyAssertionError |
Raised when a recommended assertion from the specification fails. |
JellyNotImplementedError |
Raised when a future feature is not yet implemented. |
JellyIncompleteResultsError |
Raised when the producer of SPARQL results reports that they are incomplete. |
JellyTruncatedResultsWarning |
Issued when a stream of SPARQL results ends without a trailer. |
JellyConformanceError
Bases: Exception
Raised when Jelly conformance is violated.
JellyAssertionError
Bases: AssertionError
Raised when a recommended assertion from the specification fails.
JellyNotImplementedError
Bases: NotImplementedError
Raised when a future feature is not yet implemented.
JellyIncompleteResultsError(message, error, result=None)
Bases: Exception
Raised when the producer of SPARQL results reports that they are incomplete.
For example, the query failed midway. The rows read before the error are valid.
Source code in pyjelly/errors.py
JellyTruncatedResultsWarning
Bases: UserWarning
Issued when a stream of SPARQL results ends without a trailer.
Some results may be missing, e.g., because the writer stopped or the connection was lost.
integrations
Modules:
| Name | Description |
|---|---|
generic |
|
rdflib |
|
generic
Modules:
| Name | Description |
|---|---|
decode |
Adapters that make generic terms and statements from decoded Jelly rows. |
generic_sink |
|
parse |
|
serialize |
|
sparql |
Jelly-SPARQL support for the generic API (without rdflib). |
decode
Adapters that make generic terms and statements from decoded Jelly rows.
Compiled with mypyc, like the decoder that calls them.
Classes:
| Name | Description |
|---|---|
GenericStatementSinkAdapter |
Implement Adapter for generic statements. |
GenericTriplesAdapter |
Triples adapted implementation for GenericStatementSink. |
GenericQuadsAdapter |
Extends GenericQuadsBaseAdapter for QUADS physical type. |
GenericGraphsAdapter |
Extends GenericQuadsBaseAdapter for GRAPHS physical type. |
GenericStatementSinkAdapter(options, parsing_mode=ParsingMode.FLAT)
Bases: Adapter
Implement Adapter for generic statements.
Notes: Returns custom RDF terms expected by GenericStatementSink, handles namespace declarations, and quoted triples.
Args: Adapter (type): base Adapter class
Source code in pyjelly/parse/decode.py
GenericTriplesAdapter(options)
Bases: GenericStatementSinkAdapter
Triples adapted implementation for GenericStatementSink.
Args: GenericStatementSinkAdapter (type): base GenericStatementSink adapter implementation that handles terms and namespaces.
Source code in pyjelly/integrations/generic/decode.py
GenericQuadsAdapter(options)
Bases: GenericQuadsBaseAdapter
Extends GenericQuadsBaseAdapter for QUADS physical type.
Args: GenericQuadsBaseAdapter (type): quads adapter that handles base quads processing.
Source code in pyjelly/integrations/generic/decode.py
GenericGraphsAdapter(options)
Bases: GenericQuadsBaseAdapter
Extends GenericQuadsBaseAdapter for GRAPHS physical type.
Notes: introduces graph start/end, checks if graph exists.
Args: GenericQuadsBaseAdapter (type): quads adapter that handles base quads processing.
Raises: JellyConformanceError: raised if graph start message was not received.
Source code in pyjelly/integrations/generic/decode.py
generic_sink
Classes:
| Name | Description |
|---|---|
BlankNode |
Class for blank nodes, storing BN's identifier as a string. |
IRI |
Class for IRIs, storing IRI as a string. |
Literal |
Class for literals. |
Triple |
Class for RDF triples. |
Quad |
Class for RDF quads. |
Prefix |
Class for generic namespace declaration. |
GenericStatementSink |
A graph or dataset of generic statements, kept in memory in order. |
Attributes:
| Name | Type | Description |
|---|---|---|
DefaultGraph |
The name of the default graph, used as the graph name of quads in it. |
DefaultGraph = _DefaultGraph()
The name of the default graph, used as the graph name of quads in it.
BlankNode(identifier)
Class for blank nodes, storing BN's identifier as a string.
Attributes:
| Name | Type | Description |
|---|---|---|
identifier |
str
|
The identifier of the blank node, without the |
Source code in pyjelly/integrations/generic/generic_sink.py
identifier
The identifier of the blank node, without the _: prefix.
IRI(iri)
Literal(lex, langtag=None, datatype=None, direction=None)
Class for literals.
Notes: Consists of: lexical form, and optional language tag and datatype. A language-tagged string may also have a base direction, "ltr" or "rtl" (RDF 1.2). All parts of literal are stored as strings.
Attributes:
| Name | Type | Description |
|---|---|---|
lex |
str
|
The lexical form, without quotes or escapes. |
langtag |
str | None
|
The language tag, or None if there is none. |
datatype |
str | None
|
The datatype IRI as a string, or None if it is not given. |
direction |
str | None
|
The base direction, "ltr" or "rtl", or None if there is none. |
Source code in pyjelly/integrations/generic/generic_sink.py
lex
The lexical form, without quotes or escapes.
langtag
The language tag, or None if there is none.
datatype
The datatype IRI as a string, or None if it is not given.
direction
The base direction, "ltr" or "rtl", or None if there is none.
Triple
Bases: NamedTuple
Class for RDF triples.
Attributes:
| Name | Type | Description |
|---|---|---|
s |
Node
|
The subject. |
p |
Node
|
The predicate. |
o |
Node
|
The object. |
s
The subject.
p
The predicate.
o
The object.
Quad
Bases: NamedTuple
Class for RDF quads.
Attributes:
| Name | Type | Description |
|---|---|---|
s |
Node
|
The subject. |
p |
Node
|
The predicate. |
o |
Node
|
The object. |
g |
GraphName
|
The graph name, |
s
The subject.
p
The predicate.
o
The object.
g
The graph name, DefaultGraph for the default graph.
Prefix
Bases: NamedTuple
Class for generic namespace declaration.
Attributes:
| Name | Type | Description |
|---|---|---|
prefix |
str
|
The prefix. |
iri |
IRI
|
The namespace IRI. |
prefix
The prefix.
iri
The namespace IRI.
GenericStatementSink(identifier=DefaultGraph)
A graph or dataset of generic statements, kept in memory in order.
It holds triples or quads, and the namespaces bound to it.
Notes: _store preserves the order of statements.
Args: identifier (str, optional): Identifier for a sink. Defaults to DefaultGraph.
Methods:
| Name | Description |
|---|---|
add |
Add a statement at the end of the sink. |
bind |
Bind a prefix to a namespace, replacing an earlier binding of it. |
parse |
Read a Jelly stream into the sink. |
serialize |
Write the sink as a Jelly stream, with the default options. |
Attributes:
| Name | Type | Description |
|---|---|---|
namespaces |
Generator[tuple[str, IRI]]
|
The bound namespaces, as (prefix, namespace IRI) pairs. |
identifier |
GraphName
|
The name of the graph, |
store |
Generator[Triple | Quad]
|
The statements, in the order they were added. |
is_triples_sink |
bool
|
Check if the sink contains triples or quads. |
Source code in pyjelly/integrations/generic/generic_sink.py
namespaces
The bound namespaces, as (prefix, namespace IRI) pairs.
identifier
The name of the graph, DefaultGraph if it is not given.
store
The statements, in the order they were added.
is_triples_sink
Check if the sink contains triples or quads.
Returns: bool: true, if length of statement is 3.
add(statement)
bind(prefix, namespace)
Bind a prefix to a namespace, replacing an earlier binding of it.
parse(input_file)
Read a Jelly stream into the sink.
The statements, namespaces and identifier of the sink are replaced with those read from the stream.
Args: input_file (IO[bytes]): binary file to read.
Source code in pyjelly/integrations/generic/generic_sink.py
serialize(output_file)
Write the sink as a Jelly stream, with the default options.
To choose the options, use flat_stream_to_file or
grouped_stream_to_file from pyjelly.integrations.generic.serialize.
Args: output_file (IO[bytes]): binary file to write.
Source code in pyjelly/integrations/generic/generic_sink.py
parse
Functions:
| Name | Description |
|---|---|
parse_triples_stream |
Parse flat triple stream. |
parse_quads_stream |
Parse flat quads stream. |
parse_jelly_grouped |
Take a jelly file and return generators of generic statements sinks. |
parse_jelly_to_graph |
Add statements from Generator to GenericStatementSink. |
parse_jelly_flat |
Parse jelly file with FLAT logical type into a Generator of stream events. |
parse_triples_stream(frames, options, frame_metadata=None)
Parse flat triple stream.
Args: frames (Iterable[jelly.RdfStreamFrame]): iterator over stream frames options (ParserOptions): stream options frame_metadata: (ContextVar[ScalarMap[str, bytes]]): context variable used for extracting frame metadata
Yields: Generator[Iterable[Triple | Prefix]]: Generator of iterables of Triple or Prefix objects, one iterable per frame.
Source code in pyjelly/integrations/generic/parse.py
parse_quads_stream(frames, options, frame_metadata=None)
Parse flat quads stream.
Args: frames (Iterable[jelly.RdfStreamFrame]): iterator over stream frames options (ParserOptions): stream options frame_metadata: (ContextVar[ScalarMap[str, bytes]]): context variable used for extracting frame metadata
Yields: Generator[Iterable[Quad | Prefix]]: Generator of iterables of Quad or Prefix objects, one iterable per frame.
Source code in pyjelly/integrations/generic/parse.py
parse_jelly_grouped(inp, sink_factory=GenericStatementSink, *, logical_type_strict=False, frame_metadata=None)
Take a jelly file and return generators of generic statements sinks.
Yields one generic statements sink per frame.
Args: inp (IO[bytes]): input jelly buffered binary stream sink_factory (Callable): lambda to construct a statement sink. By default, creates an empty in-memory GenericStatementSink. logical_type_strict (bool): If True, validate the logical type in stream options and require a grouped logical type. Otherwise, only the physical type is used to route parsing. frame_metadata: (ContextVar[ScalarMap[str, bytes]]): context variable used for extracting frame metadata
Raises: NotImplementedError: is raised if a physical type is not implemented
Yields: Generator[GenericStatementSink]: returns generators for GenericStatementSink, regardless of stream type.
Source code in pyjelly/integrations/generic/parse.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | |
parse_jelly_to_graph(inp, sink_factory=GenericStatementSink)
Add statements from Generator to GenericStatementSink.
Args: inp (IO[bytes]): input jelly stream. sink_factory (Callable[[], GenericStatementSink]): factory to create statement sink. By default creates an empty in-memory GenericStatementSink. Has no division for datasets/graphs, utilizes the same underlying data structures.
Returns: GenericStatementSink: GenericStatementSink with statements.
Source code in pyjelly/integrations/generic/parse.py
parse_jelly_flat(inp, frames=None, options=None, *, logical_type_strict=False)
Parse jelly file with FLAT logical type into a Generator of stream events.
Args: inp (IO[bytes]): input jelly buffered binary stream. frames (Iterable[jelly.RdfStreamFrame | None): jelly frames if read before. options (ParserOptions | None): stream options if read before. logical_type_strict (bool): If True, validate the logical type in stream options and require FLAT (TRIPLES/QUADS). Otherwise, only the physical type is used to route parsing.
Raises: NotImplementedError: if physical type is not supported
Yields: Generator[Statement | Prefix]: Generator of stream events
Source code in pyjelly/integrations/generic/parse.py
serialize
Classes:
| Name | Description |
|---|---|
GenericSinkTermEncoder |
|
Functions:
| Name | Description |
|---|---|
triples_stream_frames |
Serialize a GenericStatementSink into frames using physical type triples stream. |
quads_stream_frames |
Serialize a GenericStatementSink into jelly frames using physical type quads stream. |
guess_options |
Guess the serializer options based on the store type. |
guess_stream |
Return an appropriate stream implementation for the given options. |
grouped_stream_to_frames |
Transform multiple GenericStatementSinks into Jelly frames. |
grouped_stream_to_file |
Write stream of GenericStatementSink to a binary file. |
flat_stream_to_frames |
Serialize a stream of raw GenericStatementSink's triples or quads into Jelly frames. |
flat_stream_to_file |
Write Triple or Quad events to a binary file. |
GenericSinkTermEncoder(lookup_preset=None)
Bases: TermEncoder
Methods:
| Name | Description |
|---|---|
same_term |
Check whether two terms are equal, to find repeated terms. |
encode_spo |
Encode term based on its GenericSink object. |
encode_graph |
Encode graph term based on its GenericSink object. |
Source code in pyjelly/serialize/encode.py
same_term(a, b)
Check whether two terms are equal, to find repeated terms.
IRIs, blank nodes and literals are compared field by field, which is cheaper than calling their eq.
Source code in pyjelly/integrations/generic/serialize.py
encode_spo(term, out)
Encode term based on its GenericSink object.
Args: term (object): term to encode out (EncodedTerm): where to put the encoded term.
Source code in pyjelly/integrations/generic/serialize.py
encode_graph(term, out)
Encode graph term based on its GenericSink object.
Args: term (object): term to encode out (EncodedTerm): where to put the encoded graph name.
Source code in pyjelly/integrations/generic/serialize.py
triples_stream_frames(stream, data)
Serialize a GenericStatementSink into frames using physical type triples stream.
Args: stream (TripleStream): stream that specifies triples processing data (GenericStatementSink | Generator[Triple]): GenericStatementSink/Statements to serialize.
Yields: Generator[jelly.RdfStreamFrame]: jelly frames.
Source code in pyjelly/integrations/generic/serialize.py
quads_stream_frames(stream, data)
Serialize a GenericStatementSink into jelly frames using physical type quads stream.
Args: stream (QuadStream): stream that specifies quads processing data (GenericStatementSink | Generator[Quad]): Dataset to serialize.
Yields: Generator[jelly.RdfStreamFrame]: jelly frames
Source code in pyjelly/integrations/generic/serialize.py
guess_options(sink, *, grouped=False)
Guess the serializer options based on the store type.
For a stream of graphs or datasets (grouped), each is an RDF Message in
Jelly-RDF 1.2, and one frame in Jelly-RDF 1.1.
Source code in pyjelly/integrations/generic/serialize.py
guess_stream(options, sink)
Return an appropriate stream implementation for the given options.
Notes: if base(!) logical type is GRAPHS and sink.is_triples_sink is false, initializes TripleStream
Source code in pyjelly/integrations/generic/serialize.py
grouped_stream_to_frames(sink_generator, options=None)
Transform multiple GenericStatementSinks into Jelly frames.
Notes: One frame per GenericStatementSink.
Note: options are guessed if not provided.
Args: sink_generator (Generator[GenericStatementSink]): Generator of GenericStatementSink to transform. options (SerializerOptions | None, optional): stream options to use. Options are guessed based on the sink store type. Defaults to None.
Yields: Generator[jelly.RdfStreamFrame]: produced Jelly frames
Source code in pyjelly/integrations/generic/serialize.py
grouped_stream_to_file(stream, output_file, **kwargs)
Write stream of GenericStatementSink to a binary file.
Args: stream (Generator[GenericStatementSink]): Generator of GenericStatementSink to serialize. output_file (IO[bytes]): output buffered writer. **kwargs (Any): options to pass to stream.
Source code in pyjelly/integrations/generic/serialize.py
flat_stream_to_frames(statements, options=None)
Serialize a stream of raw GenericStatementSink's triples or quads into Jelly frames.
Args: statements (Generator[Triple | Quad]): s/p/o triples or s/p/o/g quads to serialize. options (SerializerOptions | None, optional): if omitted, guessed based on the first tuple.
Yields: Generator[jelly.RdfStreamFrame]: generated frames.
Source code in pyjelly/integrations/generic/serialize.py
flat_stream_to_file(statements, output_file, options=None)
Write Triple or Quad events to a binary file.
Args: statements (Generator[Triple | Quad]): statements to serialize. output_file (IO[bytes]): output buffered writer. options (SerializerOptions | None, optional): stream options.
Source code in pyjelly/integrations/generic/serialize.py
sparql
Jelly-SPARQL support for the generic API (without rdflib).
Functions:
| Name | Description |
|---|---|
parse_jelly_sparql |
Read SPARQL query results from Jelly-SPARQL. |
parse_jelly_sparql_sequence |
Read a sequence of SPARQL query results from one Jelly-SPARQL stream. |
sparql_stream |
Create a Jelly-SPARQL writer for generic API terms. |
serialize_jelly_sparql |
Write a solution sequence (the result of a SELECT query) in Jelly-SPARQL. |
serialize_jelly_sparql_ask |
Write a boolean result (of an ASK query) in Jelly-SPARQL. |
serialize_jelly_sparql_sequence |
Write a sequence of SPARQL query results in one Jelly-SPARQL stream. |
parse_jelly_sparql(inp)
Read SPARQL query results from Jelly-SPARQL.
Rows are read during iteration (only once), so the input must stay open until then.
Args: inp (IO[bytes] | bytes): the stream, delimited or not. It must have one result set (the FLAT stream type, the default).
Returns: SparqlResultSet: the results. Iterating it gives the rows, as tuples with one value per variable, None if the variable is unbound.
Raises: JellyIncompleteResultsError: if the writer reported that the results are incomplete. Raised at the end of the iteration, or right away for a boolean result.
Source code in pyjelly/integrations/generic/sparql.py
parse_jelly_sparql_sequence(inp)
Read a sequence of SPARQL query results from one Jelly-SPARQL stream.
This reads PUNCTUATED streams, which hold any number of results. A FLAT stream (the default) holds one. Rows are read during iteration. If the next result set is read first, the unread rows are kept in memory.
Args: inp (IO[bytes] | bytes): the stream, delimited.
Yields: SparqlResultSet: the results, one per result set.
Source code in pyjelly/integrations/generic/sparql.py
sparql_stream(options=None)
Create a Jelly-SPARQL writer for generic API terms.
Source code in pyjelly/integrations/generic/sparql.py
serialize_jelly_sparql(variables, rows, out, options=None, *, links=())
Write a solution sequence (the result of a SELECT query) in Jelly-SPARQL.
If the rows fail midway (e.g., the query fails), the stream is ended with the error so readers know the results are incomplete, and the exception is re-raised.
Args: variables (Iterable[str]): variable names, in projection order. rows (Iterable[Sequence[Node | None]]): the rows, with one value per variable, None if the variable is unbound. out (IO[bytes]): output stream. options (SparqlOptions | None): options of the stream. links (Sequence[str]): link IRIs for the results.
Source code in pyjelly/integrations/generic/sparql.py
serialize_jelly_sparql_ask(value, out, options=None, *, links=())
Write a boolean result (of an ASK query) in Jelly-SPARQL.
Args: value (bool): the result. out (IO[bytes]): output stream. options (SparqlOptions | None): options of the stream. links (Sequence[str]): link IRIs for the result.
Source code in pyjelly/integrations/generic/sparql.py
serialize_jelly_sparql_sequence(results, out, options=None)
Write a sequence of SPARQL query results in one Jelly-SPARQL stream.
The stream is PUNCTUATED, with one result set per result.
Args: results (Iterable[SequenceItem]): the results, each a (variables, rows) pair for a SELECT query, or a bool for an ASK query. out (IO[bytes]): output stream. options (SparqlOptions | None): options of the stream, which must be punctuated. Defaults to SparqlOptions(punctuated=True).
Source code in pyjelly/integrations/generic/sparql.py
rdflib
Modules:
| Name | Description |
|---|---|
decode |
Adapters that make rdflib terms and statements from decoded Jelly rows. |
encode |
Encoding of rdflib terms. Compiled with mypyc, like the other encoders. |
parse |
|
serialize |
|
sparql |
Jelly-SPARQL support for rdflib's SPARQL query results (rdflib.query.Result). |
statements |
The statements and prefixes that the rdflib parser yields. |
walk |
Walk rdflib graphs grouped by graph, subject and predicate (gspo order). |
Functions:
| Name | Description |
|---|---|
register_extension_to_rdflib |
Make rdflib.util.guess_format discover Jelly format. |
register_extension_to_rdflib(extension='.jelly')
Make rdflib.util.guess_format discover Jelly format.
rdflib.util.guess_format("foo.jelly") register_extension_to_rdflib() rdflib.util.guess_format("foo.jelly") 'jelly'
Source code in pyjelly/integrations/rdflib/__init__.py
decode
Adapters that make rdflib terms and statements from decoded Jelly rows.
Compiled with mypyc, like the decoder that calls them. rdflib is not installed
when mypyc builds pyjelly, so its classes are only Any to the type checker here.
Classes:
| Name | Description |
|---|---|
RDFLibAdapter |
RDFLib adapter class, is extended by triples and quads implementations. |
RDFLibTriplesAdapter |
Triples adapter RDFLib implementation. |
RDFLibQuadsAdapter |
Extended RDFLib adapter for the QUADS physical type. |
RDFLibGraphsAdapter |
Extension of RDFLibQuadsBaseAdapter for the GRAPHS physical type. |
BindingRows |
Row factory that turns the cells of Jelly-SPARQL frames into rdflib bindings. |
RDFLibAdapter(options, *, validate_iris=False)
Bases: Adapter
RDFLib adapter class, is extended by triples and quads implementations.
Args: options (ParserOptions): options of the stream validate_iris (bool): whether rdflib checks the IRIs. An invalid IRI is still read, rdflib only logs a warning. Checking slows down parsing.
Source code in pyjelly/integrations/rdflib/decode.py
RDFLibTriplesAdapter(options, *, validate_iris=False)
Bases: RDFLibAdapter
Triples adapter RDFLib implementation.
Notes: returns triple/namespace declaration as soon as receives them.
Source code in pyjelly/integrations/rdflib/decode.py
RDFLibQuadsAdapter(options, *, validate_iris=False)
Bases: RDFLibQuadsBaseAdapter
Extended RDFLib adapter for the QUADS physical type.
Args: RDFLibQuadsBaseAdapter (RDFLibAdapter): base quads adapter (shared with graphs physical type)
Source code in pyjelly/integrations/rdflib/decode.py
RDFLibGraphsAdapter(options, *, validate_iris=False)
Bases: RDFLibQuadsBaseAdapter
Extension of RDFLibQuadsBaseAdapter for the GRAPHS physical type.
Notes: introduces graph start/end, checks if graph exists.
Args: RDFLibQuadsBaseAdapter (RDFLibAdapter): base adapter for quads management.
Raises: JellyConformanceError: if no graph_start was encountered
Source code in pyjelly/integrations/rdflib/decode.py
BindingRows()
Row factory that turns the cells of Jelly-SPARQL frames into rdflib bindings.
A binding is a dict from each bound Variable to its value, as in rdflib's query results. Equal names share one Variable object (see variables()).
Methods:
| Name | Description |
|---|---|
variables |
Get the Variable objects for these names. |
Source code in pyjelly/integrations/rdflib/decode.py
variables(names)
Get the Variable objects for these names.
encode
Encoding of rdflib terms. Compiled with mypyc, like the other encoders.
rdflib is not installed when mypyc builds pyjelly, so its classes are only Any
to the type checker here.
Classes:
| Name | Description |
|---|---|
RDFLibTermEncoder |
|
RDFLibTermEncoder(lookup_preset=None)
Bases: TermEncoder
Methods:
| Name | Description |
|---|---|
same_term |
Return whether two terms are equal, for repeated terms. |
encode_spo |
Encode s/p/o term based on its RDFLib object. |
encode_graph |
Encode graph name term based on its RDFLib object. |
Source code in pyjelly/serialize/encode.py
same_term(a, b)
Return whether two terms are equal, for repeated terms.
rdflib's eq is slow Python code, so the common cases are answered here by comparing the terms as strings:
- Two URIRefs or two BNodes are equal if their strings are.
- Two Literals with different lexical forms are never equal. With the same lexical form, language tag and datatype, they are equal. Otherwise rdflib decides (e.g., for language tags that differ only in case).
- Terms of different classes among these three are never equal.
Source code in pyjelly/integrations/rdflib/encode.py
encode_spo(term, out)
Encode s/p/o term based on its RDFLib object.
Args: term (object): term to encode out (EncodedTerm): where to put the encoded term.
Source code in pyjelly/integrations/rdflib/encode.py
encode_graph(term, out)
Encode graph name term based on its RDFLib object.
Args: term (object): term to encode out (EncodedTerm): where to put the encoded graph name.
Source code in pyjelly/integrations/rdflib/encode.py
parse
Classes:
| Name | Description |
|---|---|
RDFLibJellyParser |
|
Functions:
| Name | Description |
|---|---|
parse_triples_stream |
Parse flat triple stream. |
parse_quads_stream |
Parse flat quads stream. |
parse_jelly_grouped |
Take jelly file and return generators based on the detected physical type. |
parse_jelly_to_graph |
Add statements from Generator to provided Graph/Dataset. |
parse_jelly_flat |
Parse jelly file with FLAT logical type into a Generator of stream events. |
RDFLibJellyParser
Bases: Parser
Methods:
| Name | Description |
|---|---|
parse |
Parse jelly file into provided RDFLib Graph. |
parse(source, sink, *, validate_iris=False)
Parse jelly file into provided RDFLib Graph.
Args: source (InputSource): jelly file as buffered binary stream InputSource obj sink (Graph): RDFLib Graph validate_iris (bool): whether rdflib checks the IRIs, see parse_jelly_to_graph(). Pass it to Graph.parse().
Raises: TypeError: raises error if invalid input
Source code in pyjelly/integrations/rdflib/parse.py
parse_triples_stream(frames, options, frame_metadata=None, *, validate_iris=False)
Parse flat triple stream.
Args: frames (Iterable[jelly.RdfStreamFrame]): iterator over stream frames options (ParserOptions): stream options frame_metadata: (ContextVar[ScalarMap[str, bytes]]): context variable used for extracting frame metadata validate_iris (bool): whether rdflib checks the IRIs. An invalid IRI is still read, rdflib only logs a warning. Checking slows down parsing.
Yields: Generator[Iterable[Triple | Prefix]]: Generator of iterables of Triple or Prefix objects, one iterable per frame.
Source code in pyjelly/integrations/rdflib/parse.py
parse_quads_stream(frames, options, frame_metadata=None, *, validate_iris=False)
Parse flat quads stream.
Args: frames (Iterable[jelly.RdfStreamFrame]): iterator over stream frames options (ParserOptions): stream options frame_metadata: (ContextVar[ScalarMap[str, bytes]]): context variable used for extracting frame metadata validate_iris (bool): whether rdflib checks the IRIs. An invalid IRI is still read, rdflib only logs a warning. Checking slows down parsing.
Yields: Generator[Iterable[Quad | Prefix]]: Generator of iterables of Quad or Prefix objects, one iterable per frame.
Source code in pyjelly/integrations/rdflib/parse.py
parse_jelly_grouped(inp, graph_factory=Graph, dataset_factory=Dataset, *, logical_type_strict=False, frame_metadata=None, validate_iris=False)
Take jelly file and return generators based on the detected physical type.
Yields one graph/dataset per frame.
Args: inp (IO[bytes]): input jelly buffered binary stream graph_factory (Callable): lambda to construct a Graph. By default creates an empty in-memory Graph, but you can pass something else here. dataset_factory (Callable): lambda to construct a Dataset. By default creates an empty in-memory Dataset, but you can pass something else here. logical_type_strict (bool): If True, validate the logical type in stream options and require a grouped logical type. Otherwise, only the physical type is used to route parsing. frame_metadata: (ContextVar[ScalarMap[str, bytes]]): context variable used for extracting frame metadata validate_iris (bool): whether rdflib checks the IRIs. An invalid IRI is still read, rdflib only logs a warning. Checking slows down parsing.
Raises: NotImplementedError: is raised if a physical type is not implemented
Yields: Generator[Graph] | Generator[Dataset]: returns generators for graphs/datasets based on the type of input
Source code in pyjelly/integrations/rdflib/parse.py
108 109 110 111 112 113 114 115 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 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 | |
parse_jelly_to_graph(inp, graph_factory=Graph, dataset_factory=Dataset, *, validate_iris=False, default_graph=None)
Add statements from Generator to provided Graph/Dataset.
Args: inp (IO[bytes]): input jelly stream. graph_factory (Callable[[], Graph]): factory to create Graph. By default creates an empty in-memory Graph, but you can pass something else here. dataset_factory (Callable[[], Dataset]): factory to create Dataset. By default creates an empty in-memory Dataset, but you can pass something else here. validate_iris (bool): whether rdflib checks the IRIs. An invalid IRI is still read, rdflib only logs a warning. Checking slows down parsing. default_graph (Graph | None): graph for the quads in the default graph, in the same store as the Dataset. By default, the Dataset's default graph.
Returns: Dataset | Graph: Dataset or Graph with statements.
Source code in pyjelly/integrations/rdflib/parse.py
parse_jelly_flat(inp, frames=None, options=None, *, logical_type_strict=False, validate_iris=False)
Parse jelly file with FLAT logical type into a Generator of stream events.
Args: inp (IO[bytes]): input jelly buffered binary stream. frames (Iterable[jelly.RdfStreamFrame | None): jelly frames if read before. options (ParserOptions | None): stream options if read before. logical_type_strict (bool): If True, validate the logical type in stream options and require FLAT_(TRIPLES|QUADS). Otherwise, only the physical type is used to route parsing. validate_iris (bool): whether rdflib checks the IRIs. An invalid IRI is still read, rdflib only logs a warning. Checking slows down parsing.
Raises: NotImplementedError: if physical type is not supported
Yields: Generator[Statement | Prefix]: Generator of stream events
Source code in pyjelly/integrations/rdflib/parse.py
serialize
Classes:
| Name | Description |
|---|---|
RDFLibJellySerializer |
RDFLib serializer for writing graphs in Jelly RDF stream format. |
Functions:
| Name | Description |
|---|---|
triples_stream_frames |
Serialize a Graph/Dataset into jelly frames. |
quads_stream_frames |
Serialize a Dataset into jelly frames. |
guess_options |
Guess the serializer options based on the store type. |
guess_stream |
Return an appropriate stream implementation for the given options. |
grouped_stream_to_frames |
Transform Graphs/Datasets into Jelly frames, one frame per Graph/Dataset. |
grouped_stream_to_file |
Write stream of Graphs/Datasets to a binary file. |
flat_stream_to_frames |
Serialize a stream of raw triples or quads into Jelly frames. |
flat_stream_to_file |
Write Triple or Quad events to a binary file in Jelly flat format. |
RDFLibJellySerializer(store)
Bases: Serializer
RDFLib serializer for writing graphs in Jelly RDF stream format.
Handles streaming RDF terms into Jelly frames using internal encoders. Supports only graphs and datasets (not quoted graphs).
Methods:
| Name | Description |
|---|---|
serialize |
Serialize self.store content to Jelly format. |
Source code in pyjelly/integrations/rdflib/serialize.py
serialize(out, /, *, stream=None, options=None, **unused)
Serialize self.store content to Jelly format.
Args: out (IO[bytes]): output buffered writer stream (Stream | None, optional): Jelly stream object. Defaults to None. options (SerializerOptions | None, optional): Serializer options if defined beforehand, e.g., read from a separate file. Defaults to None. **unused(Any): unused args for RDFLib serialize
Source code in pyjelly/integrations/rdflib/serialize.py
triples_stream_frames(stream, data)
Serialize a Graph/Dataset into jelly frames.
Args: stream (TripleStream): stream that specifies triples processing data (Graph | Dataset | Iterable[Triple]): Graph/Dataset/Statements to serialize.
Notes: if Dataset (or ConjunctiveGraph) is given, its graphs are unpacked and iterated over. If flow is GraphsFrameFlow, emits a frame per graph.
Yields: Generator[jelly.RdfStreamFrame]: jelly frames.
Source code in pyjelly/integrations/rdflib/serialize.py
quads_stream_frames(stream, data)
Serialize a Dataset into jelly frames.
Notes: Emits one frame per dataset if flow is of DatasetsFrameFlow. A ConjunctiveGraph is written as a Dataset, with its default context as the default graph.
Args: stream (QuadStream): stream that specifies quads processing data (Dataset | Iterable[Quad]): Dataset to serialize.
Yields: Generator[jelly.RdfStreamFrame]: jelly frames
Source code in pyjelly/integrations/rdflib/serialize.py
guess_options(sink, *, grouped=False)
Guess the serializer options based on the store type.
For a stream of graphs or datasets (grouped), each is an RDF Message in
Jelly-RDF 1.2, and one frame in Jelly-RDF 1.1.
guess_options(Graph()).logical_type 1 guess_options(Dataset()).logical_type 2 guess_options(Dataset(), grouped=True).logical_type 4
A ConjunctiveGraph (e.g., the one rdfpipe reads into) holds quads too:
guess_options(ConjunctiveGraph()).logical_type 2
Source code in pyjelly/integrations/rdflib/serialize.py
guess_stream(options, sink)
Return an appropriate stream implementation for the given options.
Notes: if base(!) logical type is GRAPHS and Dataset (or ConjunctiveGraph) is given, initializes TripleStream
graph_ser = RDFLibJellySerializer(Graph()) ds_ser = RDFLibJellySerializer(Dataset())
type(guess_stream(guess_options(graph_ser.store), graph_ser.store))
type(guess_stream(guess_options(ds_ser.store), ds_ser.store))
Source code in pyjelly/integrations/rdflib/serialize.py
grouped_stream_to_frames(sink_generator, options=None)
Transform Graphs/Datasets into Jelly frames, one frame per Graph/Dataset.
Note: options are guessed if not provided.
Args: sink_generator (Generator[Graph] | Generator[Dataset]): Generator of Graphs/Dataset to transform. options (SerializerOptions | None, optional): stream options to use. Options are guessed based on the sink store type. Defaults to None.
Yields: Generator[jelly.RdfStreamFrame]: produced Jelly frames
Source code in pyjelly/integrations/rdflib/serialize.py
grouped_stream_to_file(stream, output_file, **kwargs)
Write stream of Graphs/Datasets to a binary file.
Args: stream (Generator[Graph] | Generator[Dataset]): Generator of Graphs/Dataset to transform. output_file (IO[bytes]): output buffered writer. **kwargs (Any): options to pass to stream.
Source code in pyjelly/integrations/rdflib/serialize.py
flat_stream_to_frames(statements, options=None)
Serialize a stream of raw triples or quads into Jelly frames.
Args: statements (Generator[Triple | Quad]): s/p/o triples or s/p/o/g quads to serialize. options (SerializerOptions | None, optional): if omitted, guessed based on the first tuple.
Yields: Generator[jelly.RdfStreamFrame]: generated frames.
Source code in pyjelly/integrations/rdflib/serialize.py
flat_stream_to_file(statements, output_file, options=None)
Write Triple or Quad events to a binary file in Jelly flat format.
Args: statements (Generator[Triple | Quad]): statements to serialize. output_file (IO[bytes]): output buffered writer. options (SerializerOptions | None, optional): stream options.
Source code in pyjelly/integrations/rdflib/serialize.py
sparql
Jelly-SPARQL support for rdflib's SPARQL query results (rdflib.query.Result).
With pyjelly installed, rdflib reads and writes results in the "jelly" format:
result = graph.query("SELECT ?s ?o WHERE { ?s ?p ?o }")
result.serialize("results.jellys", format="jelly")
result = Result.parse(open("results.jellys", "rb"), format="jelly")
Classes:
| Name | Description |
|---|---|
JellySparqlResult |
An rdflib Result read from Jelly-SPARQL, with a few extra attributes. |
RDFLibJellySparqlParser |
rdflib parser plugin for Jelly-SPARQL results, used by Result.parse(). |
RDFLibJellySparqlSerializer |
rdflib serializer plugin for Jelly-SPARQL, used by Result.serialize(). |
Functions:
| Name | Description |
|---|---|
parse_jelly_sparql |
Read SPARQL query results from Jelly-SPARQL. |
parse_jelly_sparql_sequence |
Read a sequence of SPARQL query results from one Jelly-SPARQL stream. |
sparql_stream |
Create a Jelly-SPARQL writer for rdflib terms. |
serialize_jelly_sparql |
Write SPARQL query results (of a SELECT or ASK query) in Jelly-SPARQL. |
serialize_jelly_sparql_sequence |
Write a sequence of SPARQL query results in one Jelly-SPARQL stream. |
JellySparqlResult(type_)
Bases: Result
An rdflib Result read from Jelly-SPARQL, with a few extra attributes.
Attributes: links: link IRIs for the results, as in head.link of SPARQL JSON results. truncated: whether the stream ended without a trailer, so some results may be missing. error: error message from the writer, if the results are incomplete. Only set by parse_jelly_sparql_sequence(). parse_jelly_sparql() raises JellyIncompleteResultsError instead.
Source code in pyjelly/integrations/rdflib/sparql.py
RDFLibJellySparqlParser
Bases: ResultParser
rdflib parser plugin for Jelly-SPARQL results, used by Result.parse().
Methods:
| Name | Description |
|---|---|
parse |
Read the results. |
parse(source, content_type=None, *, validate_iris=False, lazy=False)
Read the results.
Args: source (IO[bytes] | bytes | str | Path): a stream, bytes, or a file path. content_type (str | None): unused. validate_iris (bool): whether rdflib checks the IRIs, see parse_jelly_sparql(). lazy (bool): read the rows during iteration, see parse_jelly_sparql(). Only for streams, not paths.
Source code in pyjelly/integrations/rdflib/sparql.py
RDFLibJellySparqlSerializer
Bases: ResultSerializer
rdflib serializer plugin for Jelly-SPARQL, used by Result.serialize().
Methods:
| Name | Description |
|---|---|
serialize |
Write the results. |
serialize(stream, encoding='utf-8', *, options=None)
Write the results.
Args: stream (IO[bytes]): output stream. encoding (str): unused, as Jelly is binary. options (SparqlOptions | None): options of the stream.
Source code in pyjelly/integrations/rdflib/sparql.py
parse_jelly_sparql(inp, *, validate_iris=False, lazy=False)
Read SPARQL query results from Jelly-SPARQL.
Args: inp (IO[bytes] | bytes): the stream, delimited or not. It must have one result set (the FLAT stream type, the default). validate_iris (bool): whether rdflib checks the IRIs. An invalid IRI is still read, rdflib only logs a warning. Checking slows down parsing. lazy (bool): read the rows during iteration instead of all at once. The stream must stay open until the result has been iterated, and the error of incomplete results is raised at the end of the iteration.
Returns: JellySparqlResult: the results, an rdflib Result.
Raises:
JellyIncompleteResultsError: if the writer said that the results are
incomplete, e.g., because the query failed midway. Its result holds
the results read before the error.
Source code in pyjelly/integrations/rdflib/sparql.py
parse_jelly_sparql_sequence(inp, *, validate_iris=False)
Read a sequence of SPARQL query results from one Jelly-SPARQL stream.
This reads PUNCTUATED streams, which hold any number of results. A FLAT stream (the default) holds one.
An incomplete result does not stop the sequence. Instead, its error
attribute is set, so check it. The results after it are still read.
Args: inp (IO[bytes] | bytes): the stream, delimited. validate_iris (bool): whether rdflib checks the IRIs, see parse_jelly_sparql().
Yields: JellySparqlResult: the results, an rdflib Result for each result set.
Source code in pyjelly/integrations/rdflib/sparql.py
sparql_stream(options=None)
Create a Jelly-SPARQL writer for rdflib terms.
Source code in pyjelly/integrations/rdflib/sparql.py
serialize_jelly_sparql(result, out, options=None)
Write SPARQL query results (of a SELECT or ASK query) in Jelly-SPARQL.
If the results fail midway (e.g., the query fails), the stream is ended with the error so readers know the results are incomplete, and the exception is re-raised. Results read from Jelly-SPARQL that were incomplete or truncated are written as incomplete.
Args: result (Result): the results. out (IO[bytes]): output stream. options (SparqlOptions | None): options of the stream.
Source code in pyjelly/integrations/rdflib/sparql.py
serialize_jelly_sparql_sequence(results, out, options=None)
Write a sequence of SPARQL query results in one Jelly-SPARQL stream.
The stream is PUNCTUATED, with one result set per result.
Args: results (Iterable[Result]): the results. out (IO[bytes]): output stream. options (SparqlOptions | None): options of the stream, which must be punctuated. Defaults to SparqlOptions(punctuated=True).
Source code in pyjelly/integrations/rdflib/sparql.py
statements
The statements and prefixes that the rdflib parser yields.
Not compiled with mypyc, which can't compile subclasses of tuple. The classes have
empty __slots__, so their instances have no __dict__ and are as small as
plain tuples.
Classes:
| Name | Description |
|---|---|
Triple |
Describe RDFLib triple. |
Quad |
Describe RDFLib quad. |
Prefix |
Describe RDF Prefix(i.e, namespace declaration). |
Triple
Quad
Bases: tuple[Node, Node, Node, GraphName]
Describe RDFLib quad.
Args: tuple (Node, Node, Node, GraphName): s/p/o/g as a tuple of RDFLib nodes and a GraphName,
Returns: Quad: quad as tuple.
Attributes:
| Name | Type | Description |
|---|---|---|
s |
Node
|
The subject. |
p |
Node
|
The predicate. |
o |
Node
|
The object. |
g |
GraphName
|
The graph name. |
s
The subject.
p
The predicate.
o
The object.
g
The graph name.
Prefix
Describe RDF Prefix(i.e, namespace declaration).
Args: tuple (str, rdflib.URIRef): expects prefix as a string, and full namespace URI as Rdflib.URIRef.
Returns: Prefix: prefix as tuple(prefix, iri).
Attributes:
| Name | Type | Description |
|---|---|---|
prefix |
str
|
The prefix. |
iri |
URIRef
|
The namespace IRI. |
prefix
The prefix.
iri
The namespace IRI.
walk
Walk rdflib graphs grouped by graph, subject and predicate (gspo order).
Jelly writes a term only when it differs from the same term in the previous statement, and keeps recently used IRIs in lookup tables. Both work much better when statements are sorted by their terms.
Functions:
| Name | Description |
|---|---|
spo_tree |
Return the graph's triples as a subject -> predicate -> objects tree. |
gspo_trees |
Return the dataset's graphs, each as its name and its triples as a tree. |
dataset_quads |
Return the dataset's quads, with graph names rather than Graph objects. |
write_tree |
Write the statements of a subject -> predicate -> objects tree. |
write_trees |
Write the statements of graphs, see gspo_trees() and write_tree(). |
spo_tree(graph)
Return the graph's triples as a subject -> predicate -> objects tree.
Only for rdflib's in-memory store, whose triples are in memory anyway. For any other store, return None: such a store can be far too big to group in memory. Its triples are then written in the store's own order, which for stores with indexes (e.g., Oxigraph, BerkeleyDB) is usually already grouped by subject.
Source code in pyjelly/integrations/rdflib/walk.py
gspo_trees(dataset)
Return the dataset's graphs, each as its name and its triples as a tree.
Only for rdflib's in-memory store, see spo_tree(). Each graph is grouped only when it's its turn, so at most one graph's tree is in memory at a time. The default graph is named DATASET_DEFAULT_GRAPH_ID, see dataset_quads().
Source code in pyjelly/integrations/rdflib/walk.py
dataset_quads(dataset)
Return the dataset's quads, with graph names rather than Graph objects.
The default graph is named DATASET_DEFAULT_GRAPH_ID. A Dataset already names it so, but a ConjunctiveGraph (e.g., the one rdfpipe reads into) names it with a random blank node. The quads of that graph go into the default graph, as with rdflib's TriG serializer.
Source code in pyjelly/integrations/rdflib/walk.py
write_tree(stream, tree)
Write the statements of a subject -> predicate -> objects tree.
Uses the stream's cursor API, so the stream doesn't compare terms. In a tree, each subject differs from the one before it, and so do the predicates of one subject and the objects of one predicate. Only the first subject of the tree and the first predicate of a subject can be equal to the one before it (e.g., rdf:type as the first predicate of every subject), so only those are compared. The first object of a predicate is rarely equal to the object before it, and most predicates have only one object, so objects are not compared: an equal one is just written again.
Yields: jelly.RdfStreamFrame: full frames.
Source code in pyjelly/integrations/rdflib/walk.py
write_trees(stream, trees)
Write the statements of graphs, see gspo_trees() and write_tree().
Source code in pyjelly/integrations/rdflib/walk.py
jelly
Modules:
| Name | Description |
|---|---|
rdf_pb2 |
Generated protocol buffer code. |
sparql_pb2 |
Generated protocol buffer code. |
rdf_pb2
Generated protocol buffer code.
sparql_pb2
Generated protocol buffer code.
options
Classes:
| Name | Description |
|---|---|
LookupPreset |
Sizes of the lookups of a stream. |
StreamTypes |
|
StreamParameters |
Parameters of a stream, other than its types and lookup sizes. |
SparqlOptions |
Options for writing a Jelly-SPARQL stream. |
Functions:
| Name | Description |
|---|---|
is_row_layout |
Return whether streams of a protocol version use the row layout. |
register_mimetypes |
Associate files that have Jelly extension with Jelly MIME types. |
stream_type_for |
Return the Jelly-RDF 1.2 stream type of a stream that is written. |
Attributes:
| Name | Type | Description |
|---|---|---|
INTEGRATION_SIDE_EFFECTS |
bool
|
Whether to allow integration module imports to trigger side effects. |
INTEGRATION_SIDE_EFFECTS = True
Whether to allow integration module imports to trigger side effects.
These side effects are cheap and may include populating some registries for guessing the defaults for external integrations that work with Jelly.
LookupPreset(max_names=DEFAULT_NAME_LOOKUP_SIZE, max_prefixes=DEFAULT_PREFIX_LOOKUP_SIZE, max_datatypes=DEFAULT_DATATYPE_LOOKUP_SIZE)
Sizes of the lookups of a stream.
The defaults are those of Jelly-RDF. Jelly-SPARQL streams use larger lookups
by default, see SparqlOptions.
Attributes: max_names: size of the name lookup, at least 8. max_prefixes: size of the prefix lookup, 0 to not use prefixes. max_datatypes: size of the datatype lookup.
Methods:
| Name | Description |
|---|---|
small |
Return small lookups: 128 names, 32 prefixes and 32 datatypes. |
StreamTypes(physical_type=jelly.PHYSICAL_STREAM_TYPE_UNSPECIFIED, logical_type=jelly.LOGICAL_STREAM_TYPE_UNSPECIFIED)
Methods:
| Name | Description |
|---|---|
__repr__ |
Return the representation of StreamTypes. |
__repr__()
Return the representation of StreamTypes.
repr(StreamTypes(9999, 8888)) 'StreamTypes(9999, 8888)'
Source code in pyjelly/options.py
StreamParameters(generalized_statements=False, rdf_star=False, version=MAX_VERSION, delimited=True, namespace_declarations=False, stream_name='', stream_type=jelly.RDF_STREAM_TYPE_FLAT, rdf_version=jelly.RDF_VERSION_UNSPECIFIED)
Parameters of a stream, other than its types and lookup sizes.
By default, streams are written in Jelly-RDF 1.2. Set version to 1 or 2 to
write Jelly-RDF 1.0 or 1.1 instead, which older parsers can read.
Attributes: generalized_statements: Jelly-RDF 1.0 and 1.1 only: whether the stream may have generalized statements. rdf_star: Jelly-RDF 1.0 and 1.1 only: whether the stream may have RDF-star statements. version: protocol version. delimited: whether the frames are delimited. namespace_declarations: whether the stream has namespace declarations. Not available in Jelly-RDF 1.0. stream_name: name of the stream. stream_type: Jelly-RDF 1.2 only: whether the stream is one graph or dataset (FLAT), or a sequence of RDF Messages (MESSAGES). rdf_version: Jelly-RDF 1.2 only: the version of RDF whose terms may occur in the stream. RDF 1.1 does not allow base directions or triple terms, RDF 1.2 Basic does not allow triple terms.
SparqlOptions(lookup_preset=SPARQL_LOOKUP_PRESET, rdf_version=jelly.RDF_VERSION_UNSPECIFIED, punctuated=False, frame_values=DEFAULT_SPARQL_FRAME_VALUES, delimited=True, stream_name='')
Options for writing a Jelly-SPARQL stream.
Attributes: lookup_preset: lookup sizes. The name lookup needs at least 128 entries. rdf_version: RDF version of the terms in the stream. RDF 1.1 allows no base directions or triple terms, RDF 1.2 Basic no triple terms. punctuated: write a sequence of result sets (the PUNCTUATED stream type) instead of one result set. frame_values: maximum values (rows times variables) per frame. A frame can end earlier if the lookups fill up. delimited: write delimited frames, which files and HTTP need. A non-delimited stream is a single frame, e.g. one message for a message broker. All terms of the results must then fit in the lookups. stream_name: name of the stream.
Methods:
| Name | Description |
|---|---|
rows_per_frame |
Compute the maximum rows per frame for this number of variables. |
rows_per_frame(variables)
Compute the maximum rows per frame for this number of variables.
SparqlOptions().rows_per_frame(4) 1024 SparqlOptions(frame_values=10).rows_per_frame(0) 10
Source code in pyjelly/options.py
is_row_layout(version)
Return whether streams of a protocol version use the row layout.
is_row_layout(VERSION_1_1) True is_row_layout(VERSION_1_2) False
register_mimetypes(extension='.jelly')
Associate files that have Jelly extension with Jelly MIME types.
register_mimetypes() mimetypes.guess_type("out.jelly") ('application/x-jelly-rdf', None)
Source code in pyjelly/options.py
stream_type_for(params, logical_type)
Return the Jelly-RDF 1.2 stream type of a stream that is written.
As in Jelly-JVM, a stream of graphs or datasets (the logical types GRAPHS and DATASETS, and their subtypes) is a stream of RDF Messages, one per graph or dataset.
stream_type_for(StreamParameters(), jelly.LOGICAL_STREAM_TYPE_FLAT_TRIPLES) 0 stream_type_for(StreamParameters(), jelly.LOGICAL_STREAM_TYPE_NAMED_GRAPHS) 1
Source code in pyjelly/options.py
parse
Modules:
| Name | Description |
|---|---|
columns |
Decoding of the column layout of Jelly-RDF 1.2. |
decode |
|
ioutils |
|
lookup |
|
sparql |
Jelly-SPARQL reader: SPARQL query results in frames, with one column per variable. |
columns
Decoding of the column layout of Jelly-RDF 1.2.
The terms are decoded once per run, and the runs are only expanded into statements at the end, so the memory needed does not depend on the row count declared by the frame.
Classes:
| Name | Description |
|---|---|
MessageEnd |
The end of an RDF Message, among the rows of Decoder.iter_rows(). |
IriSequence |
IRIs written as RdfIri messages, in the order they are read. |
ColumnDecoder |
Decodes the frames of a Jelly-RDF 1.2 stream for a Decoder. |
MessageEnd
The end of an RDF Message, among the rows of Decoder.iter_rows().
IriSequence(decoder)
IRIs written as RdfIri messages, in the order they are read.
A prefix index of 0 means the same prefix as the IRI before (none in the first IRI), and a name index of 0 means the name after the one of the IRI before.
Source code in pyjelly/parse/columns.py
ColumnDecoder(decoder)
Decodes the frames of a Jelly-RDF 1.2 stream for a Decoder.
Methods:
| Name | Description |
|---|---|
iter_frame |
Return the namespace declarations and statements of a frame. |
restate_options |
Read restated stream options, which empty the lookups. |
end_of_stream |
Yield the end of the last RDF Message, if it has statements. |
iter_batch |
Return the namespace declarations and statements of a batch. |
message_lengths |
Return the lengths of the RDF Messages that end in a batch. |
apply_entries |
Apply a frame's packed lookup entries. |
statements |
Yield the statements, |
runs |
Decode a column into its runs, whose cells add up to the row count. |
cells |
Decode a Jelly-SPARQL column into its cells, in order. |
run_values |
Decode the run values of a column, in order. |
mixed_values |
Decode the run values of a column whose kinds say which type each is. |
literal_kind |
Resolve a literal kind: its language tag, datatype and base direction. |
direction |
Return a base direction read from the stream. |
Source code in pyjelly/parse/columns.py
iter_frame(frame)
Return the namespace declarations and statements of a frame.
The stream options and the lookup entries of the frame are read right away, the statements as they are iterated.
Source code in pyjelly/parse/columns.py
restate_options(options)
Read restated stream options, which empty the lookups.
Returns: bool: whether an RDF Message ended, because it had statements.
Source code in pyjelly/parse/columns.py
end_of_stream()
Yield the end of the last RDF Message, if it has statements.
iter_batch(batch)
Return the namespace declarations and statements of a batch.
Source code in pyjelly/parse/columns.py
message_lengths(batch, rows)
Return the lengths of the RDF Messages that end in a batch.
Source code in pyjelly/parse/columns.py
apply_entries(names, prefixes, datatypes)
Apply a frame's packed lookup entries.
Source code in pyjelly/parse/columns.py
statements(counts, subjects, predicates, objects, graphs)
Yield the statements, counts at a time, with MESSAGE_END in between.
Source code in pyjelly/parse/columns.py
runs(column, rows, allowed, position)
Decode a column into its runs, whose cells add up to the row count.
Source code in pyjelly/parse/columns.py
cells(column, rows, position)
Decode a Jelly-SPARQL column into its cells, in order.
The column may hold terms of any type. Unbound cells are None.
Source code in pyjelly/parse/columns.py
run_values(column, allowed, position)
Decode the run values of a column, in order.
Source code in pyjelly/parse/columns.py
mixed_values(column, counts, position)
Decode the run values of a column whose kinds say which type each is.
Source code in pyjelly/parse/columns.py
literal_kind(kind, langtags, directions)
Resolve a literal kind: its language tag, datatype and base direction.
Source code in pyjelly/parse/columns.py
direction(value)
Return a base direction read from the stream.
Source code in pyjelly/parse/columns.py
decode
Classes:
| Name | Description |
|---|---|
ParsingMode |
Specifies how jelly frames should be treated. |
Adapter |
|
Decoder |
|
Functions:
| Name | Description |
|---|---|
check_stream_options |
Check that the parser can read a stream with these options. |
parser_options |
Return the parser options of a stream, after checking them. |
options_from_frame |
Fill stream options based on the options row. |
messages |
Group the rows of a stream of RDF Messages by message. |
grouped_rows |
Return the rows of each frame, or of each message in a stream of RDF Messages. |
flat_rows |
Return the rows of all frames, without the ends of RDF Messages. |
ParsingMode
Bases: Enum
Specifies how jelly frames should be treated.
Modes: FLAT Yield all frames as one Graph or Dataset. GROUPED Yield one Graph/Dataset per frame (grouped parsing).
Adapter(options, parsing_mode=ParsingMode.FLAT)
Methods:
| Name | Description |
|---|---|
iri |
Return an IRI term. The decoder reuses it, so it must be immutable. |
literal |
Return a literal term. The decoder reuses it, so it must be immutable. |
directional_literal |
Return a language-tagged string with a base direction, "ltr" or "rtl". |
namespace_declaration |
Return a namespace declaration. |
Source code in pyjelly/parse/decode.py
iri(iri)
literal(lex, language=None, datatype=None)
Return a literal term. The decoder reuses it, so it must be immutable.
directional_literal(lex, language, direction)
Return a language-tagged string with a base direction, "ltr" or "rtl".
Source code in pyjelly/parse/decode.py
namespace_declaration(name, iri)
Return a namespace declaration. iri is a term made by iri().
Source code in pyjelly/parse/decode.py
Decoder(adapter)
Initializes decoder with lookup tables of preset sizes and an integration-dependent adapter.
Args: adapter (Adapter): integration-dependent adapter that specifies terms conversion to specific objects, framing, namespace declarations, and graphs/datasets forming.
Methods:
| Name | Description |
|---|---|
new_lookups |
Make empty lookups, of the sizes in the options. |
restate_options |
Use restated options of a Jelly-RDF 1.2 stream. This empties the lookups. |
end_of_stream |
Yield what ends with the stream: the last RDF Message, if any. |
iter_rows |
Iterate through rows in the frame. |
iter_row_layout |
Yield the decoded rows of a frame of a Jelly-RDF 1.0 or 1.1 stream. |
decode_other_row |
Decode a row that gives nothing to yield: graph start or end, options. |
validate_stream_options |
Check that repeated stream options are the same as the first ones. |
ingest_prefix_entry |
Update prefix lookup table based on the table entry. |
ingest_name_entry |
Update name lookup table based on the table entry. |
ingest_datatype_entry |
Update datatype lookup table based on the table entry. |
decode_term |
Decode a term based on its type: IRI/literal/BN/default graph. |
decode_iri |
Decode RdfIri message to IRI using a custom adapter. |
iri_term |
Return the IRI made of the entries at the indices (prefix 0 is none). |
new_iri |
Make an IRI term, and cache it for its name entry. |
decode_bnode |
Decode string message to blank node (BN) using a custom adapter. |
decode_literal |
Decode RdfLiteral to literal based on custom adapter implementation. |
literal_term |
Return a literal, reusing a recently made one if it's the same. |
literal_cache |
Return recent literals of a language tag and datatype, by lexical form. |
new_literal |
Make a literal term, and keep it in its literal_cache(). |
decode_statement |
Decode the terms of a triple or quad message. |
Source code in pyjelly/parse/decode.py
new_lookups()
Make empty lookups, of the sizes in the options.
Source code in pyjelly/parse/decode.py
restate_options(options)
Use restated options of a Jelly-RDF 1.2 stream. This empties the lookups.
Source code in pyjelly/parse/decode.py
end_of_stream()
Yield what ends with the stream: the last RDF Message, if any.
iter_rows(frame)
Iterate through rows in the frame.
Args: frame (jelly.RdfStreamFrame): jelly frame
Returns: Iterator[Any]: decoded rows, and in streams of RDF Messages, MESSAGE_END at the end of each message
Source code in pyjelly/parse/decode.py
iter_row_layout(frame)
Yield the decoded rows of a frame of a Jelly-RDF 1.0 or 1.1 stream.
Source code in pyjelly/parse/decode.py
decode_other_row(row_owner, kind)
Decode a row that gives nothing to yield: graph start or end, options.
Source code in pyjelly/parse/decode.py
validate_stream_options(options)
Check that repeated stream options are the same as the first ones.
Source code in pyjelly/parse/decode.py
ingest_prefix_entry(entry)
Update prefix lookup table based on the table entry.
Args: entry (jelly.RdfPrefixEntry): prefix message, containing id and value
Source code in pyjelly/parse/decode.py
ingest_name_entry(entry)
Update name lookup table based on the table entry.
Args: entry (jelly.RdfNameEntry): name message, containing id and value
Source code in pyjelly/parse/decode.py
ingest_datatype_entry(entry)
Update datatype lookup table based on the table entry.
Args: entry (jelly.RdfDatatypeEntry): name message, containing id and value
Source code in pyjelly/parse/decode.py
decode_term(term)
Decode a term based on its type: IRI/literal/BN/default graph.
Notes: requires a custom adapter with implemented methods for terms decoding.
Args: term (Any): IRI/literal/BN(string)/Default graph message
Raises: TypeError: raises error if no handler for the term is found
Returns: Any: decoded term (currently, rdflib objects, e.g., rdflib.term.URIRef)
Source code in pyjelly/parse/decode.py
decode_iri(iri)
Decode RdfIri message to IRI using a custom adapter.
The term is reused if the same name and prefix entries were decoded before, so the adapter's IRI terms must be immutable.
Args: iri (jelly.RdfIri): RdfIri message
Returns: Any: IRI, based on adapter implementation, e.g., rdflib.term.URIRef
Source code in pyjelly/parse/decode.py
iri_term(prefix_index, name_index)
Return the IRI made of the entries at the indices (prefix 0 is none).
Source code in pyjelly/parse/decode.py
new_iri(name_index, name, prefix)
Make an IRI term, and cache it for its name entry.
decode_bnode(bnode)
Decode string message to blank node (BN) using a custom adapter.
Args: bnode (str): blank node id
Returns: Any: blank node object from the custom adapter
Source code in pyjelly/parse/decode.py
decode_literal(literal)
Decode RdfLiteral to literal based on custom adapter implementation.
Recently decoded literals are reused, so the adapter's literal terms must be immutable.
Args: literal (jelly.RdfLiteral): RdfLiteral message
Returns: Any: literal returned by the custom adapter
Source code in pyjelly/parse/decode.py
literal_term(lex, language, datatype, direction)
Return a literal, reusing a recently made one if it's the same.
Source code in pyjelly/parse/decode.py
literal_cache(language, datatype)
Return recent literals of a language tag and datatype, by lexical form.
Source code in pyjelly/parse/decode.py
new_literal(lex, language, datatype, cache)
Make a literal term, and keep it in its literal_cache().
Source code in pyjelly/parse/decode.py
decode_statement(fields, size)
Decode the terms of a triple or quad message.
Notes: also updates the repeated terms
Args: fields (list[Any]): the message's fields, from ListFields() size (int): 3 for a triple, 4 for a quad
Raises: JellyConformanceError: if a missing repeated term is encountered
Returns: Any: a list of decoded terms
Source code in pyjelly/parse/decode.py
check_stream_options(options)
Check that the parser can read a stream with these options.
The fields of one layout must not be set in a stream of the other. The lookups must not be larger than the parser allows (see the MAX_*_LOOKUP_SIZE constants).
Raises: JellyConformanceError: if it can't.
Source code in pyjelly/parse/decode.py
parser_options(options, *, delimited)
Return the parser options of a stream, after checking them.
Args: options (jelly.RdfStreamOptions): the stream options delimited (bool): whether the stream is delimited
Returns: ParserOptions: types, lookup sizes and other parameters of the stream
Raises: JellyConformanceError: if the parser can't read the stream.
Source code in pyjelly/parse/decode.py
options_from_frame(frame, *, delimited)
Fill stream options based on the options row.
Args: frame (jelly.RdfStreamFrame): first non-empty frame from the stream delimited (bool): derived delimited flag
Returns: ParserOptions: filled options with types/lookups/stream parameters information
Raises: JellyConformanceError: if the parser can't read the stream.
Source code in pyjelly/parse/decode.py
messages(rows)
Group the rows of a stream of RDF Messages by message.
Args: rows (Iterable[Iterable[Any]]): the rows that Decoder.iter_rows() returns for each frame, and Decoder.end_of_stream()
Yields: list[Any]: the namespace declarations and statements of each message
Source code in pyjelly/parse/decode.py
grouped_rows(rows, options)
Return the rows of each frame, or of each message in a stream of RDF Messages.
Args: rows (Iterable[Iterable[Any]]): the rows that Decoder.iter_rows() returns for each frame, and Decoder.end_of_stream() options (ParserOptions): the stream's options
Source code in pyjelly/parse/decode.py
flat_rows(rows, options)
Return the rows of all frames, without the ends of RDF Messages.
Args: rows (Iterable[Iterable[Any]]): the rows that Decoder.iter_rows() returns for each frame, and Decoder.end_of_stream() options (ParserOptions): the stream's options
Source code in pyjelly/parse/decode.py
ioutils
Functions:
| Name | Description |
|---|---|
single_byte_tags |
Return the single-byte tags that a message's fields can have. |
hint_bytes_needed |
Return how many bytes |
delimited_jelly_hint |
Detect whether a Jelly stream is delimited, from its first bytes. |
read_hint_header |
Read just enough of the start of the stream to detect delimiting. |
detect_delimited |
Detect from the first bytes whether a stream is delimited. |
parse_delimited |
Read the next length-prefixed message, or None at the end of the input. |
get_options_and_frames |
Return stream options and frames from the buffered binary stream. |
Attributes:
| Name | Type | Description |
|---|---|---|
FRAME_TAGS |
Final
|
Tag bytes a non-delimited frame can start with (currently 0x0A, 0x12, 0x7A). |
SPARQL_FRAME_TAGS |
Final
|
Tag bytes that a non-delimited Jelly-SPARQL frame can start with. |
FRAME_TAGS = single_byte_tags(cast('Descriptor', jelly.RdfStreamFrame.DESCRIPTOR))
Tag bytes a non-delimited frame can start with (currently 0x0A, 0x12, 0x7A).
SPARQL_FRAME_TAGS = single_byte_tags(cast('Descriptor', jelly.SparqlResultsFrame.DESCRIPTOR))
Tag bytes that a non-delimited Jelly-SPARQL frame can start with.
single_byte_tags(descriptor)
Return the single-byte tags that a message's fields can have.
Only fields numbered 1 to 15 have a one-byte tag. A repeated scalar field may be written packed or not, so both of its tags are returned.
Args: descriptor (Descriptor): descriptor of the message
Returns: frozenset[int]: tag bytes of the message's fields
Source code in pyjelly/parse/ioutils.py
hint_bytes_needed(first_byte, tags=FRAME_TAGS)
Return how many bytes delimited_jelly_hint needs to decide.
Args: first_byte (int): first byte of the stream tags (frozenset[int]): tag bytes a frame can start with
Returns: int: number of bytes to read from the start of the stream, at most 128
hint_bytes_needed(0x11) 1
hint_bytes_needed(0x0A) 11
Source code in pyjelly/parse/ioutils.py
delimited_jelly_hint(header, tags=FRAME_TAGS)
Detect whether a Jelly stream is delimited, from its first bytes.
A non-delimited stream is a single frame, so it starts with the tag of one of the frame's fields -- any of them, because a writer may put the fields in any order. A delimited stream starts with the size of its first frame. So, if the first byte is not a frame tag, the stream is delimited. Otherwise it may still be the size of a small first frame, of at most 127 bytes: the stream is then delimited if the bytes after it are exactly that many bytes of frame fields.
Pass as much of the start of the stream as you have, up to 128 bytes --
hint_bytes_needed tells you how much is actually needed once you have the
first byte. Given fewer bytes than the check needs, the stream is reported
as non-delimited.
Args: header (bytes): first bytes of the stream tags (frozenset[int]): tag bytes a frame can start with, FRAME_TAGS for Jelly-RDF and SPARQL_FRAME_TAGS for Jelly-SPARQL
Returns: bool: True if the stream is delimited
An empty stream is an empty non-delimited frame:
delimited_jelly_hint(b"") False
0x11 is not a frame tag, so it is the size of the first frame:
delimited_jelly_hint(bytes([0x11, 0x0A, 0x0F, 0x0A, 0x0D])) True
A 10-byte frame holding one name entry, written non-delimited. It starts with the tag of the rows field, and the 9 bytes after it are not a whole frame of 10 bytes:
frame = bytes([0x0A, 0x08, 0x4A, 0x06, 0x12, 0x04, 0x6E, 0x61, 0x6D, 0x65]) delimited_jelly_hint(frame) False
The same frame written delimited. Its size, 10, is also the tag of the rows field, but the 10 bytes after it are exactly one frame's worth of fields:
delimited_jelly_hint(bytes([0x0A]) + frame) True
A stream of empty delimited frames is delimited too -- 0 is never a tag:
delimited_jelly_hint(bytes([0x00, 0x00, 0x00])) True
Two bytes of garbage are not enough to tell, so they count as a frame:
delimited_jelly_hint(bytes([0x12, 0x34])) False
Source code in pyjelly/parse/ioutils.py
read_hint_header(inp, tags=FRAME_TAGS)
Read just enough of the start of the stream to detect delimiting.
Reads one byte, and at most 128. Pass the result to delimited_jelly_hint.
Args: inp (IO[bytes]): stream to read from tags (frozenset[int]): tag bytes a frame can start with
Returns: bytes: bytes read from the start of the stream
Source code in pyjelly/parse/ioutils.py
detect_delimited(inp, tags=FRAME_TAGS)
Detect from the first bytes whether a stream is delimited.
Args: inp (IO[bytes]): the stream tags (frozenset[int]): tag bytes a frame can start with
Returns: tuple[IO[bytes], bool]: a stream positioned at the start again, and whether it is delimited
Source code in pyjelly/parse/ioutils.py
parse_delimited(message_class, inp)
Read the next length-prefixed message, or None at the end of the input.
Raises: DecodeError: if the bytes are not a message of the class, or the input ends in the middle of one. Or UnicodeDecodeError, see DECODE_ERRORS. ValueError: if the input is closed.
Source code in pyjelly/parse/ioutils.py
get_options_and_frames(inp)
Return stream options and frames from the buffered binary stream.
The options are in the first frame that has rows. A stream with no such frame (e.g., an empty file) is an empty graph, with the options of an empty Jelly-RDF 1.2 stream of triples.
Args: inp (IO[bytes]): jelly buffered binary stream
Raises: JellyConformanceError: if the parser can't read the stream
Returns: tuple[ParserOptions, Iterator[jelly.RdfStreamFrame]]: ParserOptions holds: stream types, lookup presets and other stream options
Source code in pyjelly/parse/ioutils.py
lookup
Classes:
| Name | Description |
|---|---|
LookupDecoder |
Shared base for RDF lookup encoders using Jelly compression. |
LookupDecoder(*, lookup_size)
Shared base for RDF lookup encoders using Jelly compression.
Tracks the last assigned and last reused index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup_size
|
int
|
Maximum lookup size. |
required |
Source code in pyjelly/parse/lookup.py
sparql
Jelly-SPARQL reader: SPARQL query results in frames, with one column per variable.
SparqlDecoder decodes frames one at a time. read_result_sets() groups the rows of the frames into result sets.
Classes:
| Name | Description |
|---|---|
DecodedFrame |
Contents of one decoded Jelly-SPARQL frame. |
SparqlDecoder |
Decoder of the frames of a Jelly-SPARQL stream, in stream order. |
ResultSetReader |
Reads and decodes frames one at a time, for the result sets. |
SparqlResultSet |
One result set of a Jelly-SPARQL stream: a solution sequence or a boolean result. |
Functions:
| Name | Description |
|---|---|
tuple_rows |
Build the rows of a frame as tuples, with one value per variable. |
check_sparql_options |
Check that this parser supports a Jelly-SPARQL stream with these options. |
sparql_parser_options |
Build the adapter options for a Jelly-SPARQL stream. |
decode_links |
Split the "link" metadata value into IRIs. Return None if it isn't UTF-8. |
sparql_frames |
Iterate the frames of a Jelly-SPARQL stream, delimited or not. |
read_result_sets |
Read the result sets of a Jelly-SPARQL stream. |
read_result_set |
Read the single result set of a FLAT Jelly-SPARQL stream. |
DecodedFrame()
Contents of one decoded Jelly-SPARQL frame.
Source code in pyjelly/parse/sparql.py
SparqlDecoder(adapter_factory, *, row_factory=tuple_rows, max_rows=MAX_SPARQL_FRAME_ROWS, max_values=MAX_SPARQL_FRAME_VALUES)
Decoder of the frames of a Jelly-SPARQL stream, in stream order.
Args: adapter_factory (AdapterFactory): builds the term adapter from the stream options. row_factory (RowFactory): builds the rows of a frame. Tuples by default. max_rows (int): maximum rows per frame. max_values (int): maximum values (rows times variables) per frame. A frame is decoded all at once, so this caps its memory use.
Methods:
| Name | Description |
|---|---|
decode |
Decode a frame. |
read_options |
Read the stream options. Repeated options also empty the lookups. |
start_result_set |
Reset the per-result-set state, for the next result set. |
read_variables |
Read the frame's header, if any, and return the current variables. |
Source code in pyjelly/parse/sparql.py
decode(frame)
Decode a frame.
Source code in pyjelly/parse/sparql.py
read_options(options)
Read the stream options. Repeated options also empty the lookups.
Source code in pyjelly/parse/sparql.py
start_result_set()
Reset the per-result-set state, for the next result set.
Source code in pyjelly/parse/sparql.py
read_variables(frame, *, has_options)
Read the frame's header, if any, and return the current variables.
Source code in pyjelly/parse/sparql.py
ResultSetReader(frames, decoder)
Reads and decodes frames one at a time, for the result sets.
Methods:
| Name | Description |
|---|---|
next |
Return the next frame, or None at the end of the stream. |
Source code in pyjelly/parse/sparql.py
next()
Return the next frame, or None at the end of the stream.
Source code in pyjelly/parse/sparql.py
SparqlResultSet(reader, first)
One result set of a Jelly-SPARQL stream: a solution sequence or a boolean result.
Rows are read from the stream lazily, during iteration. Each row is a tuple with one value per variable, None if the variable is unbound. A loop that stops early can be resumed later. Once all rows have been read, iterating again raises an error. If the next result set is read first, the unread rows are kept in memory.
If the producer ended the result set with an error, iterating raises
JellyIncompleteResultsError after the last row, and so does boolean. If the
stream ends without a trailer, truncated is set and a
JellyTruncatedResultsWarning is issued.
Methods:
| Name | Description |
|---|---|
collect |
Append all remaining rows to a list. Faster than iterating. |
keep |
Read the remaining rows into memory, for iteration later. |
Attributes:
| Name | Type | Description |
|---|---|---|
boolean |
bool | None
|
Boolean result of an ASK query, or None for a solution sequence. |
is_boolean |
bool
|
Whether this is a boolean result (of an ASK query). |
Source code in pyjelly/parse/sparql.py
boolean
Boolean result of an ASK query, or None for a solution sequence.
Raises: JellyIncompleteResultsError: if the producer reported an error.
is_boolean
Whether this is a boolean result (of an ASK query).
collect(rows)
Append all remaining rows to a list. Faster than iterating.
Raises: JellyIncompleteResultsError: if the result set is incomplete. The rows are appended first.
Source code in pyjelly/parse/sparql.py
keep()
Read the remaining rows into memory, for iteration later.
tuple_rows(variables, cells, rows)
Build the rows of a frame as tuples, with one value per variable.
check_sparql_options(options)
Check that this parser supports a Jelly-SPARQL stream with these options.
Raises: JellyConformanceError: if it can't.
Source code in pyjelly/parse/sparql.py
sparql_parser_options(options)
Build the adapter options for a Jelly-SPARQL stream.
Terms are decoded like in a Jelly-RDF 1.2 stream with the same lookup sizes and RDF version. The stream types are left unspecified.
Source code in pyjelly/parse/sparql.py
decode_links(value)
Split the "link" metadata value into IRIs. Return None if it isn't UTF-8.
decode_links(b"http://example.org/a\nhttp://example.org/b") ['http://example.org/a', 'http://example.org/b'] decode_links(b"") [] decode_links(b"\xff") is None True
Source code in pyjelly/parse/sparql.py
sparql_frames(inp)
Iterate the frames of a Jelly-SPARQL stream, delimited or not.
Raises: JellyConformanceError: if the stream is empty, or isn't Jelly-SPARQL.
Source code in pyjelly/parse/sparql.py
read_result_sets(inp, adapter_factory, *, row_factory=tuple_rows, max_rows=MAX_SPARQL_FRAME_ROWS, max_values=MAX_SPARQL_FRAME_VALUES)
Read the result sets of a Jelly-SPARQL stream.
A FLAT stream (the default) has one result set, a PUNCTUATED stream any number. Moving on to the next result set reads the rest of the current one and keeps its unread rows in memory.
Args: inp (IO[bytes] | bytes): the stream, delimited or not. adapter_factory (AdapterFactory): builds the term adapter from the stream options. row_factory (RowFactory): builds the rows. Tuples by default. max_rows (int): maximum rows per frame. max_values (int): maximum values (rows times variables) per frame.
Yields: SparqlResultSet: the result sets, in order.
Source code in pyjelly/parse/sparql.py
read_result_set(inp, adapter_factory, *, row_factory=tuple_rows, max_rows=MAX_SPARQL_FRAME_ROWS, max_values=MAX_SPARQL_FRAME_VALUES)
Read the single result set of a FLAT Jelly-SPARQL stream.
The first frame is read now, the rows during iteration. For PUNCTUATED streams, use read_result_sets().
Raises: JellyConformanceError: if the stream is PUNCTUATED. JellyIncompleteResultsError: for a boolean result that the producer could not complete.
Source code in pyjelly/parse/sparql.py
serialize
Modules:
| Name | Description |
|---|---|
columns |
The column layout of Jelly-RDF 1.2: a frame's statements, column by column. |
encode |
|
flows |
|
ioutils |
|
lookup |
|
sparql |
Jelly-SPARQL writer: SPARQL query results in frames. |
streams |
|
columns
The column layout of Jelly-RDF 1.2: a frame's statements, column by column.
Classes:
| Name | Description |
|---|---|
Column |
The cells of one statement position in the frame being built. |
ColumnBatch |
The column batch of the frame being built. |
Column(allowed, position)
The cells of one statement position in the frame being built.
Methods:
| Name | Description |
|---|---|
add_value |
Add a run value: a term that is not the same as the one before. |
end_run |
End the current run, adding a layout token if it isn't one cell long. |
write |
Write the column into its message, and empty it for the next frame. |
Source code in pyjelly/serialize/columns.py
add_value(term)
Add a run value: a term that is not the same as the one before.
Source code in pyjelly/serialize/columns.py
end_run()
End the current run, adding a layout token if it isn't one cell long.
Source code in pyjelly/serialize/columns.py
write(column)
Write the column into its message, and empty it for the next frame.
Source code in pyjelly/serialize/columns.py
ColumnBatch(encoder, *, quads, messages)
The column batch of the frame being built.
The terms are encoded by the stream's TermEncoder. The frame flow decides when the frame ends (see FrameFlow.to_stream_frame()).
Args: encoder (TermEncoder): encoder of the stream's terms. quads (bool): whether the statements are quads. messages (bool): whether the stream is a stream of RDF Messages.
Methods:
| Name | Description |
|---|---|
has_room |
Return whether one more statement fits in the frame. |
add |
Add a subject, predicate or object to its column. |
add_changed |
Add a term of the cursor API, which tells if it changed. |
add_graph |
Add a graph name, an unbound cell for the default graph. |
add_graph_changed |
Add a graph name of the cursor API, which tells if it changed. |
add_triple |
Add a triple, and keep its terms in |
add_quad |
Add a quad, and keep its terms in |
add_namespace |
Add a namespace declaration, which comes before the frame's statements. |
end_message |
End the current RDF Message, which may have started in an earlier frame. |
write |
Write the frame's statements into its batch, and start the next frame. |
Source code in pyjelly/serialize/columns.py
has_room()
add(column, term)
Add a subject, predicate or object to its column.
Source code in pyjelly/serialize/columns.py
add_changed(column, term, *, changed)
Add a term of the cursor API, which tells if it changed.
add_graph(term)
Add a graph name, an unbound cell for the default graph.
Source code in pyjelly/serialize/columns.py
add_graph_changed(term, *, changed)
Add a graph name of the cursor API, which tells if it changed.
Source code in pyjelly/serialize/columns.py
add_triple(terms, repeated_terms)
Add a triple, and keep its terms in repeated_terms, as the row layout.
Source code in pyjelly/serialize/columns.py
add_quad(terms, repeated_terms)
Add a quad, and keep its terms in repeated_terms, as the row layout.
Source code in pyjelly/serialize/columns.py
add_namespace(name, iri)
Add a namespace declaration, which comes before the frame's statements.
Source code in pyjelly/serialize/columns.py
end_message()
End the current RDF Message, which may have started in an earlier frame.
write(batch)
Write the frame's statements into its batch, and start the next frame.
Source code in pyjelly/serialize/columns.py
encode
Classes:
| Name | Description |
|---|---|
EncodedTerm |
A term encoded for a statement, before it is written into the statement. |
TermEncoder |
|
Functions:
| Name | Description |
|---|---|
split_iri |
Split iri into prefix and name. |
write_term |
Write an encoded subject (slot 0), predicate (1) or object (2). |
write_graph |
Write an encoded graph name. |
encode_triple |
Encode one triple, adding its rows to the encoder's flow. |
encode_quad |
Encode one quad, adding its rows to the encoder's flow. |
encode_namespace_declaration |
Encode namespace declaration, adding its rows to the encoder's flow. |
encode_options |
Encode stream options to ProtoBuf message. |
EncodedTerm()
A term encoded for a statement, before it is written into the statement.
A statement is written in two steps: first its terms are encoded (adding new lookup entries to the frame), then the terms are written into the statement's row (row layout) or columns (column layout). This way the row is filled in place, and never copied.
Source code in pyjelly/serialize/encode.py
TermEncoder(lookup_preset=None)
Methods:
| Name | Description |
|---|---|
same_term |
Return whether two terms are equal, for repeated terms. |
new_epoch |
Start encoding a new statement (or other row with terms) in the row layout. |
new_frame |
Start encoding a new frame in the column layout. |
has_room |
Return whether one more statement fits in the frame, see new_frame(). |
reserve_iris |
Take IRIs that later statements may need out of the frame's budget. |
iri_indices |
Return the indices of an IRI's prefix and name entries, adding new entries. |
encode_iri_indices |
Encode lookup indices for IRI, as written in the row layout. |
encode_iri |
Encode iri into |
encode_bnode |
Encode a blank node into |
encode_default_graph |
Encode default graph into |
encode_literal |
Encode literal into |
encode_direction |
Return the RdfBaseDirection value of a base direction. |
encode_datatype |
Return the index of a datatype, adding an entry if it's new. |
encode_quoted_triple |
Encode a quoted triple into |
encode_triple_term |
Encode a triple term of the column layout, adding new lookup entries. |
encode_spo |
Encode a subject, predicate or object into |
encode_graph |
Encode a graph name into |
Source code in pyjelly/serialize/encode.py
same_term(a, b)
Return whether two terms are equal, for repeated terms.
Integrations can make it faster for their term classes.
new_epoch()
Start encoding a new statement (or other row with terms) in the row layout.
Until the next epoch, the lookup entries it uses are not evicted: the row still refers to them.
Source code in pyjelly/serialize/encode.py
new_frame(iris, literals=1)
Start encoding a new frame in the column layout.
The frame is one epoch of the lookups: all its entries must fit in them, because they are all applied before its statements are read. So each lookup gets a budget, which leaves room for one more statement (see has_room()).
Args: iris (int): the most IRIs that one statement can have. literals (int): maximum number of literals in one statement or row. In a statement, only the object can be a literal.
Source code in pyjelly/serialize/encode.py
has_room()
Return whether one more statement fits in the frame, see new_frame().
reserve_iris(count)
Take IRIs that later statements may need out of the frame's budget.
iri_indices(iri_string)
Return the indices of an IRI's prefix and name entries, adding new entries.
Most IRIs repeat, so how an IRI splits into prefix and name, and the indices of their entries, are cached (see _CachedIri).
Args: iri_string (str): full iri in string format.
Returns: tuple[int, int]: indices in prefix and name tables.
Source code in pyjelly/serialize/encode.py
encode_iri_indices(iri_string)
Encode lookup indices for IRI, as written in the row layout.
The indices are relative to the IRI before (see RdfIri), so IRIs must be encoded in the order they are written.
Args: iri_string (str): full iri in string format.
Returns: tuple[int, int]: indices in prefix and name tables.
Source code in pyjelly/serialize/encode.py
encode_iri(iri_string, out)
Encode iri into out, adding new lookup entries.
Source code in pyjelly/serialize/encode.py
encode_bnode(label, out)
encode_default_graph(out)
encode_literal(*, lex, language=None, datatype=None, direction=None, out)
Encode literal into out, adding a new datatype entry.
Args: lex (str): lexical form/literal value language (str | None, optional): langtag. Defaults to None. datatype (str | None, optional): data type if it is a typed literal. Defaults to None. direction (str | None, optional): base direction of a language-tagged string, "ltr" or "rtl". Defaults to None. out (EncodedTerm): where to put the encoded literal.
Raises: JellyConformanceError: if datatype specified while datatable is not used, or if the stream can't have the base direction.
Source code in pyjelly/serialize/encode.py
encode_direction(direction)
Return the RdfBaseDirection value of a base direction.
Source code in pyjelly/serialize/encode.py
encode_datatype(datatype)
Return the index of a datatype, adding an entry if it's new.
Source code in pyjelly/serialize/encode.py
encode_quoted_triple(terms, out)
Encode a quoted triple into out, adding new lookup entries.
In the column layout, it is a triple term, see encode_triple_term().
Notes: Although a triple, it is treated as a part of a statement. Repeated terms are not used when encoding quoted triples.
Args: terms (Iterable[object]): triple terms to encode. out (EncodedTerm): where to put the encoded triple.
Source code in pyjelly/serialize/encode.py
encode_triple_term(terms)
Encode a triple term of the column layout, adding new lookup entries.
Its IRIs are in the IRI sequence of the frame's triple terms, in the order
subject, predicate, object. triple_iris counts the IRIs of the outermost
triple term, nested ones included.
Args: terms (Iterable[object]): the subject, predicate and object.
Returns: jelly.RdfTripleTerm: the triple term.
Source code in pyjelly/serialize/encode.py
encode_spo(term, out)
split_iri(iri_string)
Split iri into prefix and name.
Args: iri_string (str): full iri string.
Returns: tuple[str, str]: iri's prefix and name.
Source code in pyjelly/serialize/encode.py
write_term(term, statement, slot)
Write an encoded subject (slot 0), predicate (1) or object (2).
Source code in pyjelly/serialize/encode.py
write_graph(term, quad)
Write an encoded graph name.
Source code in pyjelly/serialize/encode.py
encode_triple(terms, term_encoder, repeated_terms)
Encode one triple, adding its rows to the encoder's flow.
Args: terms (Iterable[object]): original terms to encode term_encoder (TermEncoder): current encoder with lookup tables repeated_terms (list[object | None]): list of repeated terms.
Source code in pyjelly/serialize/encode.py
encode_quad(terms, term_encoder, repeated_terms)
Encode one quad, adding its rows to the encoder's flow.
Args: terms (Iterable[object]): original terms to encode term_encoder (TermEncoder): current encoder with lookup tables repeated_terms (list[object | None]): list of repeated terms.
Source code in pyjelly/serialize/encode.py
encode_namespace_declaration(name, value, term_encoder)
Encode namespace declaration, adding its rows to the encoder's flow.
Args: name (str): namespace prefix label value (str): namespace iri term_encoder (TermEncoder): current encoder
Source code in pyjelly/serialize/encode.py
encode_options(lookup_preset, stream_types, params)
Encode stream options to ProtoBuf message.
Args: lookup_preset (options.LookupPreset): lookup tables options stream_types (options.StreamTypes): physical and logical types params (options.StreamParameters): other params.
Returns: jelly.RdfStreamOptions: encoded stream options
Source code in pyjelly/serialize/encode.py
flows
Classes:
| Name | Description |
|---|---|
FrameFlow |
Abstract base class for producing Jelly frames from RDF stream rows. |
ManualFrameFlow |
Produces frames only when manually requested (never automatically). |
BoundedFrameFlow |
Produce frames automatically when a fixed number of rows is reached. |
GraphsFrameFlow |
|
DatasetsFrameFlow |
|
Functions:
| Name | Description |
|---|---|
flow_for_type |
Return flow based on logical type requested. |
FrameFlow(*, logical_type=None)
Abstract base class for producing Jelly frames from RDF stream rows.
Rows are added straight into the frame being built (see new_row()), so they
never have to be copied: protobuf copies a message by serializing it and
parsing it again.
In Jelly-RDF 1.2 streams, the frame's statements are in its column batch (see
batch), and the rows only store the stream options. A frame may then also
end because the lookups are full.
Allows for passing LogicalStreamType, required for logical subtypes and non-delimited streams.
Methods:
| Name | Description |
|---|---|
new_row |
Add an empty row at the end of the current frame, and return it. |
__len__ |
Return how many rows (in Jelly-RDF 1.2, statements) the frame has. |
frame_from_graph |
End a graph: in a stream of RDF Messages, end its message. |
frame_from_dataset |
End a dataset: in a stream of RDF Messages, end its message. |
end_message |
End the current RDF Message, in a stream of RDF Messages. |
frame_from_bounds |
Produce a frame if no more statements fit in it. |
to_stream_frame |
Return the current frame, and start a new one. |
Source code in pyjelly/serialize/flows.py
new_row()
__len__()
Return how many rows (in Jelly-RDF 1.2, statements) the frame has.
frame_from_graph()
End a graph: in a stream of RDF Messages, end its message.
Default implementation returns None: the frame goes on.
frame_from_dataset()
End a dataset: in a stream of RDF Messages, end its message.
Default implementation returns None: the frame goes on.
end_message()
frame_from_bounds()
Produce a frame if no more statements fit in it.
Only in Jelly-RDF 1.2, where the lookups must fit all the frame's entries.
Source code in pyjelly/serialize/flows.py
to_stream_frame()
Return the current frame, and start a new one.
Returns: jelly.RdfStreamFrame | None: stream frame, None if it is empty
Source code in pyjelly/serialize/flows.py
ManualFrameFlow(*, logical_type=None)
Bases: FrameFlow
Produces frames only when manually requested (never automatically).
Warning
All stream rows are kept in memory until to_stream_frame() is called.
This may lead to high memory usage for large streams.
Used for non-delimited serialization.
Source code in pyjelly/serialize/flows.py
BoundedFrameFlow(*, logical_type=None, frame_size=None)
Bases: FrameFlow
Produce frames automatically when a fixed number of rows is reached.
In Jelly-RDF 1.2, it is a number of statements. Used for delimited encoding (default mode).
Methods:
| Name | Description |
|---|---|
frame_from_bounds |
Emit frame from flow if full. |
Source code in pyjelly/serialize/flows.py
frame_from_bounds()
Emit frame from flow if full.
Returns: jelly.RdfStreamFrame | None: stream frame
Source code in pyjelly/serialize/flows.py
GraphsFrameFlow(*, logical_type=None)
Bases: FrameFlow
Methods:
| Name | Description |
|---|---|
frame_from_graph |
Emit current flow content (one graph) as jelly frame. |
Source code in pyjelly/serialize/flows.py
frame_from_graph()
Emit current flow content (one graph) as jelly frame.
Returns: jelly.RdfStreamFrame | None: jelly frame or none if flow is empty.
Source code in pyjelly/serialize/flows.py
DatasetsFrameFlow(*, logical_type=None)
Bases: FrameFlow
Methods:
| Name | Description |
|---|---|
frame_from_dataset |
Emit current flow content (dataset) as jelly frame. |
Source code in pyjelly/serialize/flows.py
frame_from_dataset()
Emit current flow content (dataset) as jelly frame.
Returns: jelly.RdfStreamFrame | None: jelly frame or none if flow is empty.
Source code in pyjelly/serialize/flows.py
flow_for_type(logical_type)
Return flow based on logical type requested.
Note: uses base logical type for subtypes (i.e., SUBJECT_GRAPHS uses the same flow as its base type GRAPHS).
Args: logical_type (jelly.LogicalStreamType): logical type requested.
Raises: NotImplementedError: if (base) logical stream type is not supported.
Returns: type[FrameFlow]: FrameFlow for respective logical type.
Source code in pyjelly/serialize/flows.py
ioutils
Functions:
| Name | Description |
|---|---|
varint |
Encode a non-negative integer as a protobuf varint. |
write_delimited |
Write a frame prefixed with its size (the delimited variant of Jelly). |
varint(value)
Encode a non-negative integer as a protobuf varint.
varint(300) b'\xac\x02'
Source code in pyjelly/serialize/ioutils.py
write_delimited(frame, output_stream)
Write a frame prefixed with its size (the delimited variant of Jelly).
Source code in pyjelly/serialize/ioutils.py
lookup
Classes:
| Name | Description |
|---|---|
Lookup |
Fixed-size 1-based string-to-index mapping. |
PackedEntries |
The new entries of a lookup for the next frame of a Jelly-RDF 1.2 stream. |
LookupEncoder |
Shared base for RDF lookup encoders using Jelly compression. |
Lookup(max_size)
Fixed-size 1-based string-to-index mapping.
- Assigns incrementing indices starting from 1.
- When full, evicts entries in index order, skipping those used recently. This way new entries mostly take the previous index + 1, which Jelly writes as 0, making files smaller. The same strategy as in Jelly-JVM.
- Index 0 is reserved for delta encoding in Jelly streams.
An entry is cold if it was not used in the last max_size // 2 uses. An entry
is pinned if it was used in the current epoch (see new_epoch()): what is
being encoded still refers to it, so it must not be evicted.
An epoch may have a budget: how many entries it may use. remaining counts
down for every entry the epoch uses for the first time, and is negative once
the epoch went over its budget.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_size
|
int
|
Maximum number of entries. Zero disables lookup. |
required |
Methods:
| Name | Description |
|---|---|
new_epoch |
Start a new epoch: only the entries used from now on are pinned. |
touch |
Mark the entry at the index as used. |
use |
Mark the entry as used, and return its index, or 0 if there is none. |
victim |
Return the index of the entry to evict from the full lookup. |
Source code in pyjelly/serialize/lookup.py
new_epoch(budget=NO_BUDGET)
touch(index)
Mark the entry at the index as used.
use(key)
Mark the entry as used, and return its index, or 0 if there is none.
Source code in pyjelly/serialize/lookup.py
victim()
Return the index of the entry to evict from the full lookup.
That is the next index in order (after the last evicted one), if it is cold and not pinned. Else, the least recently used one that is not pinned among a few indices spread evenly over the table, starting with that next index. The next eviction then goes on from the index picked, which is usually among a run of other old entries.
Source code in pyjelly/serialize/lookup.py
PackedEntries()
The new entries of a lookup for the next frame of a Jelly-RDF 1.2 stream.
Entries with consecutive indices are packed into one RdfLookupEntryPacked.
Methods:
| Name | Description |
|---|---|
write |
Add the packed entries to a repeated RdfLookupEntryPacked field. |
Source code in pyjelly/serialize/lookup.py
write(out)
Add the packed entries to a repeated RdfLookupEntryPacked field.
Source code in pyjelly/serialize/lookup.py
LookupEncoder(*, lookup_size)
Shared base for RDF lookup encoders using Jelly compression.
Tracks the last assigned and last reused index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup_size
|
int
|
Maximum lookup size. |
required |
Methods:
| Name | Description |
|---|---|
encode_entry_index |
Get or assign the index to use in an entry, and mark the entry as used. |
encode_entry |
Get or add the entry for the key, and mark it as used. |
name_index_to_write |
Return how to write a reference to the name entry at the index. |
prefix_index_to_write |
Return how to write a reference to the prefix entry at the index. |
Source code in pyjelly/serialize/lookup.py
encode_entry_index(key)
Get or assign the index to use in an entry, and mark the entry as used.
Call it once for every use of the key, before encode_*_term_index().
Returns:
| Type | Description |
|---|---|
int or None
|
|
If the return value is None, the entry is already in the lookup and does not
|
|
need to be emitted. Any integer value (including 0) means the entry is new
|
|
and should be emitted.
|
|
Source code in pyjelly/serialize/lookup.py
encode_entry(key)
Get or add the entry for the key, and mark it as used.
Returns:
| Type | Description |
|---|---|
tuple[int, int]
|
The entry's index, and the index to write in a new entry row: -1 if
the entry was already there (no row needed), 0 if the new index is
sequential ( |
Source code in pyjelly/serialize/lookup.py
name_index_to_write(index)
Return how to write a reference to the name entry at the index.
Source code in pyjelly/serialize/lookup.py
prefix_index_to_write(index, *, empty)
Return how to write a reference to the prefix entry at the index.
Source code in pyjelly/serialize/lookup.py
sparql
Jelly-SPARQL writer: SPARQL query results in frames.
Classes:
| Name | Description |
|---|---|
VariableColumn |
Cells of one variable in the frame being built. |
SparqlStream |
Writer of SPARQL query results as Jelly-SPARQL frames. |
FrameWriter |
Writer of frames to a file, either delimited or as a single frame. |
Functions:
| Name | Description |
|---|---|
links_value |
Join link IRIs with LF, for the "link" metadata key. |
variable_names |
Strip a leading "?" or "$" from each variable name. |
error_message |
Format an exception as the error message of a trailer. |
write_solutions |
Write a solution sequence (the result of a SELECT query) as one result set. |
write_bindings |
Like write_solutions(), with rows given as bindings. |
VariableColumn()
Bases: Column
Cells of one variable in the frame being built.
Source code in pyjelly/serialize/sparql.py
SparqlStream(encoder, options=None)
Writer of SPARQL query results as Jelly-SPARQL frames.
A result set is either a solution sequence (SELECT) or a boolean result (ASK). For a solution sequence, call start(), then row() for each row, then end(). row() returns a frame when one is full, and end() returns the last frame. ask() returns the single frame of a boolean result.
A stream holds one result set, or any number of them with SparqlOptions(punctuated=True).
Args: encoder (TermEncoder): term encoder, with the same lookup sizes as the options. options (SparqlOptions | None): options of the stream.
Methods:
| Name | Description |
|---|---|
start |
Start a solution sequence. |
row |
Add a row (solution) to the result set. |
binding |
Add a row (solution) given as a mapping from variables to values. |
rows |
Add many rows, see row(). |
add |
Add a value to a column. None is an unbound cell. |
end_frame |
End the current frame and return it. |
write_frame |
Fill in the frame: options, header, lookup entries and rows. |
write_start |
Add the stream options and the header, if they are still due. |
end |
End the result set and return its last frame, which has the trailer. |
ask |
Return the frame of a boolean result (of an ASK query). |
Source code in pyjelly/serialize/sparql.py
start(variables, links=())
Start a solution sequence.
Args: variables (Iterable[str]): variable names, in projection order. A leading "?" or "$" is removed. links (Sequence[str]): link IRIs for the result set, as in head.link of SPARQL JSON results.
Source code in pyjelly/serialize/sparql.py
row(values)
Add a row (solution) to the result set.
Args: values (Sequence[object | None]): one value per variable, None if the variable is unbound.
Returns: jelly.SparqlResultsFrame | None: the frame, if this row filled it.
Source code in pyjelly/serialize/sparql.py
binding(binding, variables)
Add a row (solution) given as a mapping from variables to values.
Args: binding (Mapping[Any, object | None]): values of the bound variables, keyed by variable or by variable name. variables (Sequence[object]): variables of the result set, in order.
Returns: jelly.SparqlResultsFrame | None: the frame, if this row filled it.
Source code in pyjelly/serialize/sparql.py
rows(rows)
Add many rows, see row().
Yields: jelly.SparqlResultsFrame: each frame as it fills up.
Source code in pyjelly/serialize/sparql.py
add(column, term)
Add a value to a column. None is an unbound cell.
Source code in pyjelly/serialize/sparql.py
end_frame()
End the current frame and return it.
Source code in pyjelly/serialize/sparql.py
write_frame(frame)
Fill in the frame: options, header, lookup entries and rows.
Source code in pyjelly/serialize/sparql.py
write_start(frame)
Add the stream options and the header, if they are still due.
Source code in pyjelly/serialize/sparql.py
end(error='')
End the result set and return its last frame, which has the trailer.
Args: error (str): reason the result set is incomplete, if it is. It tells readers that some results are missing.
Returns: jelly.SparqlResultsFrame: the last frame.
Source code in pyjelly/serialize/sparql.py
ask(value, links=(), error='')
Return the frame of a boolean result (of an ASK query).
Args: value (bool): the result. links (Sequence[str]): link IRIs for the result. error (str): reason the result is incomplete, if it is.
Returns: jelly.SparqlResultsFrame: the result's only frame.
Source code in pyjelly/serialize/sparql.py
FrameWriter(out, *, delimited)
Writer of frames to a file, either delimited or as a single frame.
Each frame is flushed, so a reader on the other end of a connection gets the rows right away.
Source code in pyjelly/serialize/sparql.py
links_value(links)
Join link IRIs with LF, for the "link" metadata key.
links_value(["http://example.org/a", "http://example.org/b"]) b'http://example.org/a\nhttp://example.org/b'
Source code in pyjelly/serialize/sparql.py
variable_names(variables)
Strip a leading "?" or "$" from each variable name.
variable_names(["?s", "$p", "o"]) ['s', 'p', 'o']
Source code in pyjelly/serialize/sparql.py
error_message(error)
Format an exception as the error message of a trailer.
error_message(KeyError("x")) "KeyError: 'x'" error_message(JellyIncompleteResultsError("...", "timeout")) 'timeout'
Source code in pyjelly/serialize/sparql.py
write_solutions(stream, variables, rows, writer, *, links=(), error='')
Write a solution sequence (the result of a SELECT query) as one result set.
If iterating the rows raises (e.g., the query fails midway), the result set is
ended with that error so readers know it is incomplete, and the exception is
re-raised. Pass error if the rows are already known to be incomplete.
Source code in pyjelly/serialize/sparql.py
write_bindings(stream, variables, bindings, writer, *, links=(), error='')
Like write_solutions(), with rows given as bindings.
Args: stream (SparqlStream): the stream. variables (Sequence[object]): the variables, as str objects (e.g., rdflib's Variable). Their names are written. bindings (Iterable[Mapping[Any, object | None]]): the rows, see SparqlStream.binding(). writer (FrameWriter): writer of the frames. links (Sequence[str]): link IRIs for the results. error (str): reason the rows are incomplete, if known.
Source code in pyjelly/serialize/sparql.py
streams
Classes:
| Name | Description |
|---|---|
SerializerOptions |
Options for writing a Jelly-RDF stream. |
Stream |
|
TripleStream |
|
QuadStream |
|
Functions:
| Name | Description |
|---|---|
stream_for_type |
Give a Stream based on physical type specified. |
SerializerOptions(flow=None, frame_size=DEFAULT_FRAME_SIZE, logical_type=jelly.LOGICAL_STREAM_TYPE_UNSPECIFIED, params=StreamParameters(), lookup_preset=LookupPreset())
Options for writing a Jelly-RDF stream.
Attributes: flow: how statements are split into frames. If None, it is chosen from the logical stream type. frame_size: target number of rows per frame. logical_type: logical stream type. If unspecified, it is guessed from the data. params: other stream parameters, e.g., the protocol version. lookup_preset: lookup sizes.
Stream(*, encoder, options=None)
Methods:
| Name | Description |
|---|---|
column_batch |
Set the stream up to write Jelly-RDF 1.2, and return its column batch. |
infer_flow |
Return flow based on the stream options provided. |
enroll |
Initialize start of the stream. |
stream_options |
Encode and append stream options row to the current flow. |
namespace_declaration |
Add namespace declaration to jelly stream. |
set_subject |
Set the subject of the next statement. |
set_predicate |
Set the predicate of the next statement. |
set_object |
Set the object of the next statement. |
emit |
Add a statement made of the terms set with the cursor API. |
encode_changed_spo |
Encode the subject, predicate and object that were set since the last emit. |
add_changed_spo |
Add the subject, predicate and object of the cursor API to their columns. |
write_changed_spo |
Write the terms encoded by encode_changed_spo() into the statement. |
for_rdflib |
Initialize stream with RDFLib encoder. |
Source code in pyjelly/serialize/streams.py
column_batch(params)
Set the stream up to write Jelly-RDF 1.2, and return its column batch.
Source code in pyjelly/serialize/streams.py
infer_flow()
Return flow based on the stream options provided.
Returns: FrameFlow: initialised FrameFlow object.
Source code in pyjelly/serialize/streams.py
enroll()
stream_options()
Encode and append stream options row to the current flow.
Source code in pyjelly/serialize/streams.py
namespace_declaration(name, iri)
Add namespace declaration to jelly stream.
Args: name (str): namespace prefix label iri (str): namespace iri
Returns: jelly.RdfStreamFrame | None: the frame before, if the declaration has to start a new one
Source code in pyjelly/serialize/streams.py
set_subject(s)
set_predicate(p)
set_object(o)
emit()
Add a statement made of the terms set with the cursor API.
Returns: jelly.RdfStreamFrame | None: stream frame if flow supports frames slicing and current flow is full
Source code in pyjelly/serialize/streams.py
encode_changed_spo()
Encode the subject, predicate and object that were set since the last emit.
They are encoded in this order no matter in which order they were set: IRIs are encoded relative to the IRI before them, in the order the parser reads them. Rows for new lookup entries are added to the flow.
Returns: int: which of them were encoded, as bits 0 (subject) to 2 (object).
Source code in pyjelly/serialize/streams.py
add_changed_spo(batch)
Add the subject, predicate and object of the cursor API to their columns.
Source code in pyjelly/serialize/streams.py
write_changed_spo(statement, changed)
Write the terms encoded by encode_changed_spo() into the statement.
Source code in pyjelly/serialize/streams.py
for_rdflib(options=None)
Initialize stream with RDFLib encoder.
Args: options (SerializerOptions | None, optional): Stream options. Defaults to None.
Raises: TypeError: if Stream is passed, and not a Stream for specific physical type.
Returns: Stream: initialized stream with RDFLib encoder.
Source code in pyjelly/serialize/streams.py
TripleStream(*, encoder, options=None)
Bases: Stream
Methods:
| Name | Description |
|---|---|
triple |
Process one triple to Protobuf messages. |
triples |
Process triples, see triple(). |
emit |
Add a triple made of the terms set with the cursor API. |
Source code in pyjelly/serialize/streams.py
triple(terms)
Process one triple to Protobuf messages.
Note: Adds new rows to the current flow and returns StreamFrame if frame size conditions are met.
Args: terms (Iterable[object]): RDF terms to encode.
Returns: jelly.RdfStreamFrame | None: stream frame if flow supports frames slicing and current flow is full
Source code in pyjelly/serialize/streams.py
triples(statements)
Process triples, see triple().
Yields: jelly.RdfStreamFrame: full frames.
Source code in pyjelly/serialize/streams.py
emit()
Add a triple made of the terms set with the cursor API.
Returns: jelly.RdfStreamFrame | None: stream frame if flow supports frames slicing and current flow is full
Source code in pyjelly/serialize/streams.py
QuadStream(*, encoder, options=None)
Bases: Stream
Methods:
| Name | Description |
|---|---|
quad |
Process one quad to Protobuf messages. |
quads |
Process quads, see quad(). |
set_graph |
Set the graph name of the next quad. |
emit |
Add a quad made of the terms set with the cursor API. |
Source code in pyjelly/serialize/streams.py
quad(terms)
Process one quad to Protobuf messages.
Args: terms (Iterable[object]): terms to encode.
Returns: jelly.RdfStreamFrame | None: stream frame if flow supports frames slicing and current flow is full
Source code in pyjelly/serialize/streams.py
quads(statements)
Process quads, see quad().
Yields: jelly.RdfStreamFrame: full frames.
Source code in pyjelly/serialize/streams.py
set_graph(g)
emit()
Add a quad made of the terms set with the cursor API.
Returns: jelly.RdfStreamFrame | None: stream frame if flow supports frames slicing and current flow is full
Source code in pyjelly/serialize/streams.py
stream_for_type(physical_type)
Give a Stream based on physical type specified.
Args: physical_type (jelly.PhysicalStreamType): jelly stream physical type.
Raises: NotImplementedError: if no stream for requested physical type is available.
Returns: type[Stream]: jelly stream