Skip to content

PostgreSQL and DuckDB Backend

The SQL lens keeps the graph in plain tables. The same code runs on PostgreSQL and on DuckDB. Use it when your data lives in a SQL database, or when you want to join DDI metadata with other tables.

The lens writes and reads the graph exactly as the other lenses do. What it reads back is the graph it was given, with each value of the same type. python -m ddigraph.conform checks this on every fixture.

New in 0.6.0

ddigraph.lens.sql is new in 0.6.0.

Dependencies

Each database is an optional extra:

pip install "ddigraph[postgres]"   # psycopg 3
pip install "ddigraph[duckdb]"     # DuckDB

The duckdb extra needs DuckDB 1.5 or later, below 2, since the duckpgq extension does not yet work on DuckDB 2. DuckDB 1.x has no wheel for Python 3.15, so pip builds it from source there. The all extra leaves DuckDB out on Python 3.15.

DuckDB runs inside Python, so it needs no server. PostgreSQL does. To try the lens, run one with Docker:

docker run -d --name ddigraph-postgres -p 5432:5432 \
    -e POSTGRES_PASSWORD=postgres postgres:18

Its address is then postgresql://postgres:postgres@localhost:5432/postgres.

Loading a File

Give the lens a DuckDB connection, or a psycopg one. The lens makes its tables when you make it, unless they are there already.

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

connection = duckdb.connect()  # a database in memory
lens = SQLLens(connection)
result = lens.write(ir.parse("survey.xml", dataset_id="survey"), dataset_id="survey")

print(result.nodes, "nodes,", result.relationships, "relationships")
print(connection.execute("SELECT count(*) FROM ddigraph_nodes").fetchone())

On PostgreSQL, pass a psycopg connection instead:

import psycopg

from ddigraph import ir
from ddigraph.lens.sql import SQLLens

with psycopg.connect("postgresql://user:password@localhost/ddi") as connection:
    lens = SQLLens(connection)
    lens.write(ir.parse("survey.xml", dataset_id="survey"), dataset_id="survey")

Each chunk of the file is written in a transaction of its own. If a chunk breaks a rule, such as a link to a node that does not exist, the write raises ValueError. That chunk writes nothing, and the chunks before it stay written. dry_run=True checks and counts the file, and writes nothing.

The Tables

Every name starts with ddigraph_. No name is a word that duckpgq keeps for itself, such as node, edge or label.

Table One row per Columns
ddigraph_nodes node key (the primary key), identity, unresolved_reason, and source, flavor, line for the Dataset node
ddigraph_labels node, flavor and type label key, flavor, type_label
ddigraph_properties node and property key, name, and the value columns
ddigraph_relationships relationship start_key, type, end_key, ordinal, resolution
ddigraph_relationship_properties relationship and property the relationship's four identity columns, name, and the value columns
ddigraph_memberships node and dataset dataset, key, source, flavor, line

A few details matter when you write your own SQL:

  • Keys. key is the node's key, 32 hex characters, the same in every backend. A relationship is known by its start, type, end and ordinal.
  • Labels. A node has one type label per flavor. A label that two flavors share, such as Category in Codebook and DDI-L, is a row for each flavor. So joining a membership to ddigraph_labels on key and flavor gives the label that dataset reads.
  • Values. Each property is one row, with its value in the column of its type: string_value, integer_value, float_value, boolean_value, or list_value. A text property keeps its string in string_value and its language in language. A list is JSON text.
  • Strings. Text compares and sorts by code point, as in Python. On PostgreSQL the columns use the "C" collation for this.
  • Your own data. A write never touches a property the spec does not own. So you can add your own rows to ddigraph_properties, or your own columns to ddigraph_nodes, and a reload keeps them.

Why a column per type, and not JSON? A typed column keeps the type with nothing to decode, and SQL compares, sorts and indexes it as that type. JSON would lose some types: PostgreSQL's jsonb stores a number as a decimal, so the float 1e+20 would come back as an integer.

Here is a query you could write yourself. It lists each variable's name and the dataset that holds it:

SELECT m.dataset, p.string_value AS name
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
LEFT JOIN ddigraph_properties AS p ON p.key = m.key AND p.name = 'name'
WHERE l.type_label = 'Variable'
ORDER BY m.dataset, name;

Reading Back, Purging and Deltas

lens.read(dataset_id="survey") gives the dataset back as IR chunks, and lens.read() gives everything. lens.purge("survey") removes a dataset. It keeps the nodes that another dataset also holds.

A node it keeps also keeps all its type labels, as in every lens. Say a DDI-L file and a CDI file both hold one category. After you purge the CDI dataset, a query for CDICategory still finds the node, on every engine. See Labels After a Purge.

lens.apply(rows, dataset_id=...) writes a delta of the store, as the Neo4j lens does. Give it Store.diff_rows, or Store.changes from 0 for a whole generation:

from ddigraph.store import Store

store = Store("~/.ddigraph/store")
lens.apply(store.changes("survey", 3), dataset_id="survey")

Querying with ddigraph.query

ddigraph.query.run runs a query on the lens, and gives the same rows as every other engine. See Queries Across Engines.

import duckdb

from ddigraph import ir
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, asc, edge, node, prop, run

lens = SQLLens(duckdb.connect())
lens.write(ir.parse("survey.xml", dataset_id="survey"), dataset_id="survey")

query = Query(
    match=[node("l", "CodeList"), node("c", "Category"), edge("l", "HAS_CATEGORY", "c")],
    returns=[prop("l", "label"), prop("c", "label")],
    order_by=[asc(prop("l", "label")), asc(prop("c", "label"))],
)
print(run(query, lens))

to_sql(query, "postgres") or to_sql(query, "duckdb") gives the SQL text and its parameters. Every literal is a parameter, written $1, $2 and so on. Each edge is a join, and a filter uses SQL's own rules for NULL, which are the rules of ddigraph.query. A reach is a recursive query that stops at its most steps. On PostgreSQL, each string comparison and sort says COLLATE "C".

A node with a label or a dataset is a small query of its own, run once: a MATERIALIZED CTE named v0, v1 and so on. So the database picks each node's rows first, and joins them after. It never joins every node of the graph four times over.

SQL/PGQ with duckpgq

duckpgq is a DuckDB extension for SQL/PGQ, the graph part of the SQL standard. Install it once, and load it on the connection. The lens never installs or loads an extension itself.

connection = duckdb.connect()
connection.execute("INSTALL duckpgq FROM community")
connection.execute("LOAD duckpgq")
lens = SQLLens(connection)

When duckpgq is loaded, run uses to_pgq(query). The lens first makes a property graph, ddigraph_graph, over its tables, once. Then the nodes and edges of the query are one GRAPH_TABLE match:

FROM GRAPH_TABLE (ddigraph_graph
  MATCH (n0:ddigraph_node WHERE n0.key IN (SELECT key FROM v0))
    -[e0:ddigraph_relationship WHERE e0.type = 'HAS_CATEGORY']->
    (n1:ddigraph_node WHERE n1.key IN (SELECT key FROM v1))
  COLUMNS (n0.key AS n0, n1.key AS n1)
) g

Some parts of a query stay plain SQL, inside the same statement:

  • Labels and datasets. A type label is a row of ddigraph_labels, not a label of the property graph. So a node with a label or a dataset is tested by a WHERE in the match, against its CTE, as in to_sql.
  • Reaches. duckpgq's paths cannot keep each step to one relationship type, and they find shortest paths, not walks of each length.
  • Literals. duckpgq drops the parameters of a statement with a GRAPH_TABLE. So to_pgq writes each literal into the text, escaped.

Checking It

conform run writes each file to the lens and compares what it reads back. conform query compares each engine's rows with the reference:

python -m ddigraph.conform run --corpus tests/fixtures --lens duckdb postgres \
    --postgres-uri postgresql://user:password@localhost/scratch
python -m ddigraph.conform query --corpus tests/fixtures --lens duckdb postgres \
    --postgres-uri postgresql://user:password@localhost/scratch

The postgres lens drops the lens's tables in its database first, so it runs only when you name it. DDIGRAPH_POSTGRES_URI can name the server instead of --postgres-uri. On DuckDB, conform query runs each query as SQL, and as SQL/PGQ too when duckpgq loads. --duckdb-extension-directory says where to find duckpgq.

What It Does Not Do

  • It has no ddigraph load command, no store marker and no repair. Those are Neo4j's for now.
  • A read holds the whole dataset in memory, as the in-memory lenses do.
  • Run one write at a time. The lens reads what is stored, then writes, so two writes at once can fail on a node that both add.
  • PostgreSQL text cannot hold the character U+0000, so psycopg refuses a value with one. DuckDB holds it.
  • A reach visits every walk of its relationship type, up to its most steps. On a large graph, keep reaches short.
  • duckpgq has no signed build for DuckDB 2 yet, so the duckdb extra stays on DuckDB 1.