sparql-v12n: A Rust Engine for Querying Relational Databases with SPARQL
#sparql#r2rml#postgresql#rust#data-virtualization
Contents
sparql-v12n is a Rust engine that queries relational databases with SPARQL. It does not copy data into a separate store; it translates a SPARQL query into one SQL statement by an R2RML mapping and runs that statement on PostgreSQL itself.
It can run as a server (v12n serve) that takes HTTP requests, or as a CLI (v12n query) that runs a single query.
This post follows the server: why the engine was built, how it is structured and how one request is processed, followed by how it is tested and how it compares with Ontop.
1. Background
1.1 Materialization and virtualization
There are two ways to query relational data with SPARQL. Materialization converts table rows into RDF triples and loads them into an RDF store, and queries read that copy. Virtualization leaves the data in the source database and, for each incoming query, generates SQL from the mapping and runs it.
The difference between the two is covered in Materialization and Virtualization: Two Ways to Query Source Data Through an Ontology, and the RDF data model in What Is RDF? A Data Model Built on Triples.
Materialization answers queries quickly but needs the copy to be managed. When the source changes, the data has to be converted and loaded again, and until then the copy and the source can differ.
Virtualization always reads the source, so there is nothing to synchronize.
In return, the engine has to handle the semantic differences between the two languages exactly, and a slow translated query means slow answers.
sparql-v12n uses virtualization.
1.2 Design goals
sparql-v12n assumes an environment that meets two conditions.
- The data to query is already stored in PostgreSQL.
- Querying the classes and properties defined in the R2RML mapping is enough, without ontology reasoning.
For that environment, the design has four goals.
- A single binary. The
v12nbinary provides both the long-running server (v12n serve, a SPARQL 1.1 Protocol HTTP endpoint) and the CLI (v12n query,v12n explain). No separate runtime such as a JVM is needed. - Fast start-up and low memory. A server starts once and then serves requests, but every restart for a deployment or a recovery, and every new instance, misses requests for as long as start-up takes. Low resident memory makes it cheap to run the server next to the database or to run several instances.
- Result values that follow the specifications. Result literals use the canonical forms of W3C XML Schema 1.1.
For example, the PostgreSQLnumericvalue12.50becomes"12.5"^^xsd:decimal. - Schema changes without a restart. When a key or a column type changes, the next query sees it. The fingerprint check in 4.6 does this.
Start-up time and memory were measured against Ontop 5.5.0 with the same PostgreSQL, mapping and queries.
| v12n | Ontop | |
|---|---|---|
| Launch to first answer | 10 ms | 5.4 s |
| Resident memory at idle | 7.5 MiB | 344 MiB |
| Resident memory, peak | 11.9 MiB | 520 MiB |
The method and the full results are in bench/RESULTS.md in the repository.
2. Direction
2.1 Supported scope
sparql-v12n keeps its scope narrow for now and will widen it along the roadmap.
- PostgreSQL only. The SQL syntax of each database sits behind the
Dialecttrait, ready for other databases. - A subset of SPARQL
SELECT. Only the basic features of select queries are supported, and features not yet supported are rejected with an error. Aggregation, property paths and other query forms will follow the roadmap.
Supported: basic graph patterns,OPTIONAL,UNION,FILTER,BIND,DISTINCT,ORDER BY,LIMIT,OFFSET - No ontology reasoning. A class query returns only what the mapping states, not what a subclass relation would imply. RDFS and OWL 2 QL reasoning will follow the roadmap.
For example,?x a ex:Employeereturns only what the mapping states asex:Employee. Even if the ontology makesex:Managera subclass ofex:Employee, resources mapped only asex:Managerare not included.
To make mistakes visible as early as possible, a query outside the scope is rejected outright instead of being answered approximately.
An unsupported feature such as a property path returns HTTP 501, or exit code 1 in the CLI.
2.2 Roadmap
Next come more SPARQL functions and operators, aggregation, RDFS and OWL 2 QL ontology reasoning, property paths and a second database. After that, an MCP server is planned so that AI agents can send queries.
3. Structure
sparql-v12n consists of five Rust crates.
At the center, v12n-core handles planning, SQL rendering and result conversion, and defines the boundary to the database as traits (ports).
The other crates are adapters on either side of the ports.
| Port | Direction | Role | Implementation |
|---|---|---|---|
Planner | called by clients | Plans a query (SqlPlan) from the mapping and index. Needs no database | v12n-core |
Engine<B> | called by clients | Combines the shared Planner, the catalog and one database session to complete and run a plan | v12n-core |
Connector | called by the core | Opens a session with a time limit and a row limit | PostgresConnector |
Backend | called by the core | One session: reading the catalog, execution, SQL dialect | PostgresBackend |
SolutionStream | called by the core | Reads results row by row and reports whether the row limit cut them | Solutions |
Dialect | called by the core | The SQL syntax of a database | PostgresDialect |
The ports keep all code that depends on PostgreSQL in one crate.
- Server. The
v12n-servercode has no PostgreSQL types; it is generic over any type that implements theConnectortrait. - CLI.
PostgresConnectoris chosen in a single function inmain.rs. - Calls. Trait methods return
impl Future + Send, so every call is statically dispatched, with noasync-traitdependency and no boxing.
Before Rust 1.75, traits could not defineasync fn, and theasync-traitcrate was the common workaround. It turns anasync fninto a method returningPin<Box<dyn Future + Send>>, so every call allocates the future on the heap and goes through a virtual function table (async-trait documentation). v12n returnsimpl Future + Senddirectly, so it calls the implementation chosen at compile time, with no extra crate and no heap allocation.Sendis needed because the server handles requests on several threads. Anasync fnin a trait cannot requireSendof the future it returns, and the Rust team recommends returningimpl Future + Sendin that case (Rust blog).
A new database is supported by an adapter crate that implements the same ports and adds its SQL syntax as a Dialect implementation.
The server code does not change, and the CLI adds the new database to the function that chooses the connector.
4. Query processing
This section follows one example from the repository through the engine.
examples/shop has a customers table and an orders table, and the mapping exposes customers as ex:Customer and the customer_id of an order as the ex:placedBy relation.
The following query asks for the orders and amounts of VIP customers.
PREFIX ex: <http://example.org/>
# orders placed by VIP customers
SELECT ?order ?amount WHERE {
?customer a ex:Customer ; ex:tier "VIP" .
?order ex:placedBy ?customer ; ex:amount ?amount .
}
Sending this query to v12n serve with POST /sparql returns three orders.
| ?order | ?amount |
|---|---|
<http://example.org/order/1001> | 120000 |
<http://example.org/order/1003> | 87000 |
<http://example.org/order/1004> | 15000 |
The request goes through eight steps. Two of them talk to PostgreSQL directly.
4.1 Server initialization
Before it takes requests, v12n serve prepares three things.
- Mapping and index. It parses the R2RML mapping (Turtle) and builds a
MappingIndexthat finds, for each class and predicate, the triples maps that can produce that RDF term. ThePlannerthat holds the mapping and the index has the same lifecycle as the server process: the server creates one at start and shares it with every request throughArc.Arcis Rust’s reference-counted smart pointer for sharing one heap object across threads. It is not a global (static); the server passes a reference to the object it created to each request. - Session check. It opens one database session to check the connection settings. Sessions have a statement timeout (30 seconds by default) and read-only transactions.
- Catalog snapshot. It reads the schema of the tables the mapping uses. With it, it stores a fingerprint: a SHA-256 hash that PostgreSQL computes over each table’s metadata joined into one string. When a table’s structure changes, its fingerprint changes too, so comparing fingerprints is enough to tell whether the snapshot is still valid.
The catalog snapshot holds: whether each table exists, the actual names and types of columns,NOT NULL, unique keys and validated foreign keys.
Starting the example server runs one session setup statement and four catalog statements (fingerprints, columns, unique keys, foreign keys) on PostgreSQL.
4.2 Request validation
HTTP requests can take the three forms of the SPARQL 1.1 Protocol query operation: GET /sparql?query=..., a form-encoded POST, and a POST with the query in an application/sparql-query body.
- Result format. The
Acceptheader picks JSON, XML, CSV or TSV. Without the header the result is JSON; with no supported format it is 406. - Size limit. A query over
max_query_bytes(64 KiB by default) is 413 forPOSTand 414 forGET. - Dataset parameters. The mapping defines the graphs, so
default-graph-uriandnamed-graph-urigive 400.
4.3 Planning
Planner::plan parses the query text into a tree of operators such as triple patterns, joins, OPTIONAL and FILTER, and unfold turns that tree into a SQL plan, SqlPlan.
This step does not connect to the database.
The operator tree has the form the SPARQL specification defines as SPARQL Algebra.
unfold turns the operator tree into a SQL plan by these rules.
- A triple pattern becomes a table scan. The
MappingIndexfinds the triples maps that match the predicate and class, and their logical table becomes the scan. - A shared variable becomes a join condition. When two patterns use the same variable, the condition that both term maps produce the same RDF term becomes a SQL condition.
OPTIONALbecomes aLEFT JOIN;UNIONand multiple triples maps become branches. A branch is oneSELECTthat the final SQL combines withUNION ALLorUNION. Each side of a SPARQLUNIONbecomes a branch, and they are combined withUNION ALL, which keeps duplicate results. When several triples maps match one triple pattern, each triples map gets a branch, and they are combined withUNION, which removes duplicates so that each triple counts once. More than 64 branches is rejected with 400.
The limit of 64 keeps the SQL from growing too large as branch counts multiply. Optimizations that reduce the number of branches will raise it over time.
For example, if thecustomersandemployeestriples maps both defineex:name, the single pattern?x ex:name ?nbecomes two branches. Two such patterns combine into four branches.- A constant becomes a bind parameter.
"VIP"is not written into the SQL text; it is passed as$1.
?customer a ex:Customer gets no scan of its own because ex:Customer is the class defined in the subject map of the customers triples map.
The single scan t0 provides both the class and tier.
The example query has no UNION, and each pattern matches one triples map, so there is one branch.
When several triples maps match, the branches split like this.
v12n explain prints the SQL of this step.
-- v12n explain examples/shop/mapping.ttl examples/shop/queries/vip-orders.rq
SELECT q."order", q."amount"
FROM (
SELECT DISTINCT t0."id" AS "customer", t1."id" AS "order", t2."amount" AS "amount"
FROM "customers" t0
JOIN "orders" t1 ON t1."customer_id" = t0."id"
JOIN "orders" t2 ON t2."id" = t1."id"
WHERE t0."tier" = $1 AND t2."amount" IS NOT NULL
) q
It scans orders twice and includes DISTINCT.
Without information from the database, the planner cannot tell whether orders.id identifies a row or whether the result can have duplicates, so it generates the safe SQL.
amount IS NOT NULL is added because, by the R2RML Generated RDF Term rule, a NULL produces no RDF term.
A failure at planning is a problem with the query or the mapping. A syntax error is 400 and an unsupported feature is 501, both returned before a session is assigned.
4.4 Concurrency control and the session pool
Once the plan is ready, the server takes one permit out of the number of concurrent requests (max_concurrent_requests, 16 by default).
If no permit is left, it does not queue the request; it returns 503 with Retry-After.
With a permit, it borrows an idle Engine from the pool, or opens a new session with the Connector if none is idle.
A session goes back to the pool only after its results have been read to the end.
If the response is aborted or the client disconnects, the session is discarded and its connection closed, because a statement may still be running on it.
Concurrency control and the session pool are ordinary connection management rather than the core of query processing, so they get no figure.
4.5 Catalog-based optimization
CatalogPlan::new completes the plan with the catalog snapshot read in 4.1.
This step also runs inside v12n-core without a database.
A SPARQL query and an R2RML mapping carry no information about table structure. The mapping says that an order IRI is built from orders.id, but not whether id is unique, whether it can be NULL or what its type is. That information is in PostgreSQL’s catalog: the system tables (pg_catalog) in which PostgreSQL records tables, columns, indexes and constraints. See PostgreSQL documentation, System Catalogs.
The catalog information is used for two things.
- Finalizing the SQL. It confirms the actual names and types of columns. It resolves column names that PostgreSQL folds to lower case, and the column types decide the types of
UNIONbranches and how RDF terms are compared. Every query needs this step. - Optimization. Based on primary keys, unique indexes and
NOT NULLconstraints, it removes scans and conditions whose removal cannot change the result. If a table has no such constraints, nothing is removed, and the SQL from the planning step runs: one table scan per triple pattern, withDISTINCTto remove duplicates.
The example query gets three optimizations.
- Merging scans of the same row.
orders.idis aNOT NULLprimary key andt2.id = t1.id, sot2is the same row ast1. The two scans become one. - Dropping
DISTINCT. The result includes the order keyid, and each order belongs to one customer, so the result cannot have duplicates. - Dropping
IS NOT NULL. Theamountcolumn has aNOT NULLconstraint, so the condition is always true.
orders.customer_id is a foreign key to customers.id, but this query reads tier from customers, so the customers scan stays.
A query that does not read tier would lose the scan of the referenced table as well.
The foreign key guarantees that the customer orders.customer_id points to exists exactly once in customers. If a query needed only the customer’s id, orders.customer_id could stand in for it and customers would not have to be read. The example query compares tier to pick VIP customers, and tier exists only in customers, so that scan cannot be removed.
The row limit (10,000 by default) is a server setting, not catalog information.
So that the first row can tell whether the result was cut, the statement reads one row more than the limit and carries count(*) OVER () as an extra column.
The statement recorded in the PostgreSQL log is:
-- PostgreSQL log, parameters: $1 = 'VIP', $2 = '10001'
SELECT q.*, count(*) OVER ()
FROM (
SELECT t1."id" AS "order", t1."amount" AS "amount"
FROM "customers" t0
JOIN "orders" t1 ON t1."customer_id" = t0."id"
WHERE t0."tier" = $1
LIMIT $2
) q
This statement was confirmed on PostgreSQL 17.11 in testenv by setting log_statement to all for a moment and sending the example request.
4.6 Catalog check and execution
The catalog is read once at start, but every query checks that the database still matches the snapshot. The check and the execution take two round trips to PostgreSQL.
- Round trip 1: checking fingerprints and preparing the statement. The fingerprint query for the plan’s tables and the prepare of the statement are pipelined together. If a fingerprint differs from the snapshot, the statement is not run; the changed tables are read again and the plan is made once more. If they differ again, the server answers with a retryable error (503).
- Round trip 2: binding and execution. Constants are bound with the parameter types PostgreSQL inferred, and the statement runs. A constant that can never match empties only its branch.
The catalog is cached, yet every query checks the fingerprints, so a key or column that changes while the server runs never leads to SQL built from stale information.
The server log for the example request recorded sql_ms=4 total_ms=4.
4.7 Result conversion and transfer
Rows from PostgreSQL go through four steps to become the response body.
- Reading a row.
Solutions::try_nextreads one row from the connection. On the first row, it records from thecount(*) OVER ()value whether the result was cut. - Decoding. A decoder for the column’s PostgreSQL type reads the binary value as a
SqlValue.
For example, anintegercolumn becomesInteger(i64). - Conversion to RDF terms.
SolutionBuilderbuilds RDF terms by the R2RML rules.
For example,idbecomes an IRI through the templatehttp://example.org/order/{id}, andamountbecomes"120000"^^xsd:integerfollowing its column typeinteger(Natural Mapping of SQL Values). - Serialization.
ResultsWriterturns each solution (one query result) into SPARQL 1.1 Query Results JSON (or XML, CSV, TSV) and sends it in the response body.
The server does not send the status line until the first row arrives.
An error before the first row can therefore still be reported as a status code.
When the first row arrives, it sends status 200 and the headers, adding a V12N-Truncated header if the result was cut.
The body is sent in chunks whenever 16 KiB or more has collected, so the whole result is never held in memory.
{"head":{"vars":["order","amount"]},"results":{"bindings":[
{"order":{"type":"uri","value":"http://example.org/order/1001"},"amount":{"type":"literal","value":"120000","datatype":"http://www.w3.org/2001/XMLSchema#integer"}},
...
]}}
4.8 Error handling
How an error shows depends on the step.
- Errors before a session is assigned. Errors in validation and planning are returned at once, without using a permit or a connection.
- Errors before the first row. A timeout is 503 and a database error is 500. In the CLI, a timeout is exit code 4.
- Errors after the first row. Status 200 has already been sent and cannot change. The server aborts the response without the final chunk, so JSON and XML end unclosed. This keeps a partial body from looking like a complete result.
4.9 Running from the CLI
v12n query in the CLI uses the same Planner and Engine.
It differs in three ways.
- Catalog. The CLI handles one query per run. It does not read the catalog in advance; it reads only the tables the plan needs. The information is used right after it is read, so fingerprints are not checked.
- Connection. The server handles many requests at once, so it keeps several PostgreSQL connections in a session pool for reuse and limits how many requests run at the same time. The CLI runs one query and exits, so it opens one connection, uses it and closes it.
- Output. JSON, XML, CSV and TSV are printed as rows arrive. The
tableformat lays the result out as an aligned table in the terminal; it needs the longest value of each column to draw the table, so it prints after every row has arrived. If the row limit cuts the result, the CLI prints a warning and ends with exit code 5.
5. Testing
For an engine that translates SPARQL into SQL, the most dangerous mistake is returning a wrong result without an error. The tests therefore focus less on “does the SQL run” and more on “does the result match the specification”.
- Unit tests. Compare the output of functions such as parsing, unfold and rendering with expected values.
- SQL snapshots. Pin the generated SQL in files, so that any change to the SQL shows up as a diff in review.
- PostgreSQL tests. Check catalog reading and result decoding on a real PostgreSQL.
- Differential tests. Run the same input on v12n and Ontop and compare the results.
Ontop is an open-source virtualization engine that takes an R2RML mapping and SPARQL queries and runs them on a relational database, and it has been developed for more than ten years. It takes the same input and is a long-tested implementation, which made it the reference. Ontop’s result is not always the right answer, so when the two differ, the specification decides which one is correct.
6. Benchmark
HTTP response times of v12n and Ontop 5.5.0 were measured with the same PostgreSQL, mapping and queries. Each value is the median of 20 runs per query on data with 100,000 alerts, and both engines returned the same results for every query. The factor is Ontop’s time divided by v12n’s.
| Query | What it does | Rows | v12n (ms) | Ontop (ms) | Factor |
|---|---|---|---|---|---|
q01 | Lookup by primary key | 1 | 1.2 | 3.2 | 2.7 |
q02 | Join through a template IRI | 2,000 | 5.2 | 15.8 | 3.0 |
q03 | Two properties of one table | 2,000 | 2.6 | 13.0 | 5.0 |
q04 | OPTIONAL | 10,000 | 8.1 | 60.6 | 7.5 |
q05 | Integer comparison in FILTER | 10,000 | 7.2 | 59.1 | 8.2 |
q06 | UNION | 14,500 | 8.6 | 54.9 | 6.4 |
q07 | ORDER BY and LIMIT 100 | 100 | 2.6 | 12.3 | 4.7 |
q08 | DISTINCT on a table without a key | 5,000 | 21.4 | 29.2 | 1.4 |
q09 | Duplicate rows in a table without a key | 4,000 | 15.9 | 31.0 | 1.9 |
Closing
Thank you for reading this long post.
References
- sparql-v12n repository — https://github.com/CharmingGroot/sparql-v12n
- sparql-v12n architecture document — https://github.com/CharmingGroot/sparql-v12n/blob/main/docs/architecture.md
- Benchmark method and results — https://github.com/CharmingGroot/sparql-v12n/tree/main/bench
- Differential test cases — https://github.com/CharmingGroot/sparql-v12n/tree/main/tests/diff
- Catalog snapshot decision record (Discussion #187) — https://github.com/CharmingGroot/sparql-v12n/discussions/187
- SPARQL 1.1 Query Language — https://www.w3.org/TR/sparql11-query/
- SPARQL 1.1 Protocol — https://www.w3.org/TR/sparql11-protocol/
- SPARQL 1.1 Query Results JSON Format — https://www.w3.org/TR/sparql11-results-json/
- R2RML: RDB to RDF Mapping Language — https://www.w3.org/TR/r2rml/