sparql-v12n: A Rust Engine for Querying Relational Databases with SPARQL

architecture18 min한국어

#sparql#r2rml#postgresql#rust#data-virtualization

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 Virtualization SPARQL query RDF store converted copy Convert and load (ETL) PostgreSQL Reload when the source changes SPARQL query v12n SQL from the R2RML mapping PostgreSQL one SQL rows The data stays in PostgreSQL
Materialization queries a copy; virtualization runs SQL on the source for every query.

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 v12n binary 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 PostgreSQL numeric value 12.50 becomes "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.

v12nOntop
Launch to first answer10 ms5.4 s
Resident memory at idle7.5 MiB344 MiB
Resident memory, peak11.9 MiB520 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 Dialect trait, 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:Employee returns only what the mapping states as ex:Employee. Even if the ontology makes ex:Manager a subclass of ex:Employee, resources mapped only as ex:Manager are 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.

SPARQL query Scope check planning and execution Run SQL return results Reject with an error HTTP 501, exit code 1 in scope out of scope
A query outside the supported scope is rejected with an error, not answered approximately.

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.

Done Basic SPARQL SELECT Runs on PostgreSQL Catalog-based optimization In progress SPARQL functions Operators, query forms Planned Aggregation Property paths RDFS, OWL 2 QL reasoning A second database Later MCP server for AI agents
From finished work to later plans. The planned items are in no particular order.

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.

Clients Core Adapter v12n-cli query, explain v12n-server HTTP /sparql v12n-difftest differential tests v12n-core Planner plan Engine execute Database-side ports (traits) Connector Backend SolutionStream Dialect No database driver or runtime v12n-postgres implements the ports PostgreSQL impl SQL
Every arrow points at v12n-core. v12n-postgres is the only crate that knows PostgreSQL.
PortDirectionRoleImplementation
Plannercalled by clientsPlans a query (SqlPlan) from the mapping and index. Needs no databasev12n-core
Engine<B>called by clientsCombines the shared Planner, the catalog and one database session to complete and run a planv12n-core
Connectorcalled by the coreOpens a session with a time limit and a row limitPostgresConnector
Backendcalled by the coreOne session: reading the catalog, execution, SQL dialectPostgresBackend
SolutionStreamcalled by the coreReads results row by row and reports whether the row limit cut themSolutions
Dialectcalled by the coreThe SQL syntax of a databasePostgresDialect

The ports keep all code that depends on PostgreSQL in one crate.

  • Server. The v12n-server code has no PostgreSQL types; it is generic over any type that implements the Connector trait.
  • CLI. PostgresConnector is chosen in a single function in main.rs.
  • Calls. Trait methods return impl Future + Send, so every call is statically dispatched, with no async-trait dependency and no boxing.
    Before Rust 1.75, traits could not define async fn, and the async-trait crate was the common workaround. It turns an async fn into a method returning Pin<Box<dyn Future + Send>>, so every call allocates the future on the heap and goes through a virtual function table (async-trait documentation). v12n returns impl Future + Send directly, so it calls the implementation chosen at compile time, with no extra crate and no heap allocation. Send is needed because the server handles requests on several threads. An async fn in a trait cannot require Send of the future it returns, and the Rust team recommends returning impl Future + Send in 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.

1 Validate format, size limit 2 Plan parse, unfold 3 Permit, session concurrency, pool 4 Complete plan catalog snapshot 5 Check, prepare fingerprint, prepare 6 Execute bind, read rows 7 To RDF terms decode, R2RML 8 Serialize, send JSON, chunks no database no database talks to PostgreSQL
Only the steps with a blue border talk to PostgreSQL.

4.1 Server initialization

Before it takes requests, v12n serve prepares three things.

  1. Mapping and index. It parses the R2RML mapping (Turtle) and builds a MappingIndex that finds, for each class and predicate, the triples maps that can produce that RDF term. The Planner that 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 through Arc.
    Arc is 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.
  2. 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.
  3. 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.
1 Mapping and index mapping.ttl <#CustomerMap> customers <#OrderMap> orders MappingIndex ex:Customer ex:name ex:tier ex:Order ex:amount ex:placedBy CustomerMap customers table OrderMap orders table 2 Session check v12n serve PostgreSQL one connection 30 s limit read only cancels after 30 s no data changes 3 Catalog snapshot PostgreSQL customers id PK; name, tier NOT NULL orders id PK, customer_id → customers.id read at start Catalog snapshot server memory customers fingerprint f0ffe12b… orders fingerprint 5cec70ce… Fingerprint: a hash of the table structure It changes when the structure changes
Server initialization with the examples/shop example.

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 Accept header 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 for POST and 414 for GET.
  • Dataset parameters. The mapping defines the graphs, so default-graph-uri and named-graph-uri give 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.

answer v12n-server handler after 4.2 validation Planner::plan v12n-core calls sparql::parse parse query unfold to SQL SqlPlan operator tree MappingIndex returns SqlPlan 4.4 Permit and session Error response 400 syntax, 501 unsupported
The server's request handler calls planning, and planning finishes without a database.

unfold turns the operator tree into a SQL plan by these rules.

  1. A triple pattern becomes a table scan. The MappingIndex finds the triples maps that match the predicate and class, and their logical table becomes the scan.
  2. 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.
  3. OPTIONAL becomes a LEFT JOIN; UNION and multiple triples maps become branches. A branch is one SELECT that the final SQL combines with UNION ALL or UNION. Each side of a SPARQL UNION becomes a branch, and they are combined with UNION ALL, which keeps duplicate results. When several triples maps match one triple pattern, each triples map gets a branch, and they are combined with UNION, 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 the customers and employees triples maps both define ex:name, the single pattern ?x ex:name ?n becomes two branches. Two such patterns combine into four branches.
  4. A constant becomes a bind parameter. "VIP" is not written into the SQL text; it is passed as $1.
Triple pattern Scan in SqlPlan Shared variable → join ?customer a ex:Customer ?customer ex:tier "VIP" ?order ex:placedBy ?customer ?order ex:amount ?amount t0 customers tier = $1 t1 orders t2 orders shared ?customer t1.customer_id = t0.id shared ?order t2.id = t1.id
Triple patterns become table scans, and shared variables become join conditions.

?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.

Triple pattern Matching triples maps SQL ?x ex:name ?n customers defines ex:name employees defines ex:name UNION Branch 1 SELECT … FROM customers Branch 2 SELECT … FROM employees Over 64: rejected with 400
Two matching triples maps give two SELECTs, combined with a duplicate-removing UNION.

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 UNION branches and how RDF terms are compared. Every query needs this step.
  • Optimization. Based on primary keys, unique indexes and NOT NULL constraints, 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, with DISTINCT to remove duplicates.

The example query gets three optimizations.

SQL built without a database SQL after the catalog SELECT DISTINCT t0.id, t1.id, t2.amount 2 FROM customers t0 JOIN orders t1 ON t1.customer_id = t0.id JOIN orders t2 ON t2.id = t1.id 1 WHERE t0.tier = $1 AND t2.amount IS NOT NULL 3 SELECT t1.id, t1.amount FROM customers t0 JOIN orders t1 ON t1.customer_id = t0.id WHERE t0.tier = $1 1 orders.id primary key merge t2 into t1 2 order key in result drop DISTINCT 3 amount NOT NULL drop IS NOT NULL
The highlighted lines on the left go away with the catalog. Quotes, aliases and the outer SELECT are omitted.
  • Merging scans of the same row. orders.id is a NOT NULL primary key and t2.id = t1.id, so t2 is the same row as t1. The two scans become one.
  • Dropping DISTINCT. The result includes the order key id, and each order belongs to one customer, so the result cannot have duplicates.
  • Dropping IS NOT NULL. The amount column has a NOT NULL constraint, 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.

HTTP client v12n serve PostgreSQL At start session setup: timeout, read only read catalog: fingerprints, columns, keys catalog snapshot Request POST /sparql plan and complete no database trip 1: check fingerprints, prepare trip 2: bind, execute 3 rows 200, JSON chunks
Two round trips to PostgreSQL per request. The catalog is read at start; each request only checks fingerprints.
  1. 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).
  2. 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.

Read row tokio-postgres id: 1001 amount: 120000 Decode Decoder Integer(1001) Integer(120000) To RDF term SolutionBuilder <…/order/1001> "120000"^^xsd:integer Serialize ResultsWriter "type": "uri" "type": "literal" id: IRI from the template amount: integer → xsd:integer
Values are read by a decoder for their PostgreSQL type and become RDF terms by the R2RML rules.
  1. Reading a row. Solutions::try_next reads one row from the connection. On the first row, it records from the count(*) OVER () value whether the result was cut.
  2. Decoding. A decoder for the column’s PostgreSQL type reads the binary value as a SqlValue.
    For example, an integer column becomes Integer(i64).
  3. Conversion to RDF terms. SolutionBuilder builds RDF terms by the R2RML rules.
    For example, id becomes an IRI through the template http://example.org/order/{id}, and amount becomes "120000"^^xsd:integer following its column type integer (Natural Mapping of SQL Values).
  4. Serialization. ResultsWriter turns 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.

Validation 406, 413, 414, 415 Planning 400 syntax error, 501 unsupported Permit 503, Retry-After Check and prepare 503 catalog changed again Execution, before row 1 503 timeout, 500 database error After the first row abort; status 200 already sent
A failure before the first row shows as a status code; after it, as an aborted response.
  • 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.

Server (v12n serve) CLI (v12n query) Catalog Read once at start fingerprint check per query Read fresh on every run needed tables only, no check Connection Session pool reuse, concurrency limit One connection closed when the run ends Output HTTP response body streamed row by row Standard output table collects every row first exit code 5 if truncated Planner and Engine the same planning and execution
Planning and execution are the same; when the catalog is read, the number of connections and the output differ.
  • 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 table format 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”.

Test Checks Against Unit tests Function output parse, unfold, render, format Expected values in the test code vs SQL snapshots Generated SQL SQL text per query Snapshot files 72 insta files vs PostgreSQL tests Database code catalog queries, keys, decoding Real PostgreSQL its actual answers vs Differential tests Query results 319 queries, 39 W3C cases Ontop results same mapping, data, query vs
Each kind of test checks something different against a different reference.
  • 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.

QueryWhat it doesRowsv12n (ms)Ontop (ms)Factor
q01Lookup by primary key11.23.22.7
q02Join through a template IRI2,0005.215.83.0
q03Two properties of one table2,0002.613.05.0
q04OPTIONAL10,0008.160.67.5
q05Integer comparison in FILTER10,0007.259.18.2
q06UNION14,5008.654.96.4
q07ORDER BY and LIMIT 1001002.612.34.7
q08DISTINCT on a table without a key5,00021.429.21.4
q09Duplicate rows in a table without a key4,00015.931.01.9

Closing

Thank you for reading this long post.

References