Skip to content

Module 20: SQL with DuckDB and PostgreSQL

Learning objectives

By the end of this module, you can:

  • O1. Write a DDI file to DuckDB, in your own Python process, with SQLLens(duckdb.connect()), and say what each of the six ddigraph_* tables holds.
  • O2. Query the tables with lens.fetch and $1 parameters, and run a ddigraph.query with run, reading the SQL it sends with to_sql.
  • O3. Join DDI metadata with a table of your own.
  • O4. Do the same on PostgreSQL 18, under your own dataset ID, and purge what you wrote.
  • O5. Match the graph as SQL/PGQ with duckpgq: install and load the extension, make the property graph, and read the query to_pgq writes.

Prerequisites: Module 10

Time: 50 min self-paced / 65 min instructor-led.

Needs: No server for DuckDB. PostgreSQL 18 for Section 5 (Module 2 starts it in Docker). Section 6 needs DuckDB's duckpgq extension, which DuckDB downloads once. The duckdb and postgres extras.

New in this module: ddigraph.lens.sql.SQLLens, ddigraph.lens.sql.TABLES, lens.fetch, lens.purge, lens.dialect, ddigraph.query.to_sql, ddigraph.query.to_pgq, lens.property_graph, GRAPH_TABLE


1. The graph in six SQL tables

The SQL lens keeps the graph in plain tables. The same code runs on two databases:

  • DuckDB runs inside your Python process, as a library. It needs no server, and duckdb.connect() with no file name keeps the database in memory.
  • PostgreSQL is a server, the usual home of an organisation's data.

Use the lens when your other data already lives in SQL, or when you want to join DDI metadata with it. This module uses the course's sample survey, a Labour Force Survey of the third quarter of 2025. Give the lens a connection; it makes its tables the first time:

import duckdb

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

connection = duckdb.connect()  # a database in memory
lens = SQLLens(connection)
result = lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)
print(result.nodes, "nodes,", result.relationships, "relationships")

for table in TABLES:
    (count,) = connection.execute(f"SELECT count(*) FROM {table}").fetchone()
    print(f"{table}: {count}")

Expected output:

80 nodes, 48 relationships
ddigraph_nodes: 80
ddigraph_labels: 158
ddigraph_properties: 257
ddigraph_relationships: 48
ddigraph_relationship_properties: 0
ddigraph_memberships: 79

ir.parse reads the file as a stream of nodes and edges (Module 4), and lens.write stores it under the dataset ID you give. TABLES names the six tables, in the order the lens makes them. Each name starts with ddigraph_:

Table One row per What it holds
ddigraph_nodes node key, identity, and unresolved_reason on a stub
ddigraph_labels node, flavor and type key, flavor, type_label
ddigraph_properties node and property key, name, and the value in the column of its type
ddigraph_relationships edge start_key, type, end_key, ordinal, resolution
ddigraph_relationship_properties edge and property the edge's identity, name, and the value
ddigraph_memberships node and dataset dataset, key, source, flavor, line

There are 158 label rows for 80 nodes. Section 2 shows why. The PostgreSQL and DuckDB backend page details every column.

2. Ask the tables: lens.fetch and parameters

lens.fetch(sql, parameters) runs a statement in a transaction of its own, and returns its rows as tuples. Write each value you pass as $1, $2 and so on, and give the values in a list. Never paste a value into the SQL text yourself: a parameter keeps a quote in the value from breaking the statement, and works the same on both databases.

This block follows one variable, HOURS, through two tables:

import duckdb

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

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)

VARIABLE = "(SELECT key FROM ddigraph_properties WHERE name = 'name' AND string_value = $1)"
for row in lens.fetch(
    f"SELECT name, string_value, language FROM ddigraph_properties WHERE key = {VARIABLE} ORDER BY name",
    ["HOURS"],
):
    print(*row)
for row in lens.fetch(
    f"SELECT flavor, type_label FROM ddigraph_labels WHERE key = {VARIABLE} ORDER BY flavor",
    ["HOURS"],
):
    print(*row)

Expected output:

dataset_id m20-codebook None
ddi_id V7 None
label Usual weekly hours in the main job None
name HOURS None
question_text How many hours a week do you usually work in your main job? None
codebook Variable
lifecycle Variable
lifecycle4 Variable

Two things to notice:

  • One row per property. Each value sits in the column of its type: string_value, integer_value, float_value, boolean_value, or list_value for a list, as JSON text. A text property keeps its language in language.
  • One label row per flavor. The label Variable exists in three flavors of DDI, so the node has a row for each. That is why there are more label rows than nodes. When you join labels, join through ddigraph_memberships on the key and the flavor. Each membership then finds the one label its dataset reads.

Here is a full query in that style: each variable of the survey with its concept. The tabs show the same question on Neo4j, in Cypher, for comparison. Pick a tab, and the site remembers it for every code box.

from neo4j import GraphDatabase

import ddigraph
from ddigraph.config import Settings
from ddigraph.lens.neo4j import Neo4jLens

ddigraph.load("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook", replace=True)

CONCEPTS = """
MATCH (v:Variable {dataset_id: 'm20-codebook'})-[:USES_CONCEPT]->(c:Concept)
RETURN v.name AS variable, c.label AS concept
ORDER BY variable
"""

settings = Settings()
auth = (settings.neo4j_user, settings.neo4j_password.get_secret_value())
with GraphDatabase.driver(settings.neo4j_uri, auth=auth) as driver:
    records, _, _ = driver.execute_query(CONCEPTS)
    Neo4jLens(driver).purge("m20-codebook")  # clean up

for record in records:
    print(" | ".join(record.values()))
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

One pattern does the work of four joins: the edge USES_CONCEPT and its two ends, with their name and label as properties.

import psycopg

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

CONCEPTS = """
SELECT variable.string_value, concept.string_value
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_relationships AS r ON r.start_key = m.key AND r.type = 'USES_CONCEPT'
LEFT JOIN ddigraph_properties AS variable ON variable.key = r.start_key AND variable.name = 'name'
LEFT JOIN ddigraph_properties AS concept ON concept.key = r.end_key AND concept.name = 'label'
WHERE m.dataset = $1 AND l.type_label = 'Variable'
ORDER BY 1
"""

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
        dataset_id="m20-codebook",
    )
    rows = lens.fetch(CONCEPTS, ["m20-codebook"])
    lens.purge("m20-codebook")  # clean up

for row in rows:
    print(" | ".join(row))
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

The same SQL as DuckDB. Section 5 explains the connection.

import duckdb

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

CONCEPTS = """
SELECT variable.string_value, concept.string_value
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_relationships AS r ON r.start_key = m.key AND r.type = 'USES_CONCEPT'
LEFT JOIN ddigraph_properties AS variable ON variable.key = r.start_key AND variable.name = 'name'
LEFT JOIN ddigraph_properties AS concept ON concept.key = r.end_key AND concept.name = 'label'
WHERE m.dataset = $1 AND l.type_label = 'Variable'
ORDER BY 1
"""

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)
for row in lens.fetch(CONCEPTS, ["m20-codebook"]):
    print(" | ".join(row))
AGE | Demographic characteristics
AGEGRP | Demographic characteristics
EDUC | Educational attainment
HOURS | Working time
ILOSTAT | Labour market status
REGION | Place of residence
SEX | Demographic characteristics

Read it join by join: the membership picks the dataset, the label keeps the variables, the relationship follows USES_CONCEPT, and each property join brings one value.

Three variables share the concept "Demographic characteristics". In a Codebook file, each of them holds its own copy of the concept, so the graph has three concept nodes with that label. The query does not mind: it matches on the label's text.

3. Write the query once: ddigraph.query

Writing those joins by hand takes care. Module 10 showed ddigraph.query: you write a small graph query once, in Python, and run turns it into SQL, Cypher or SPARQL for the engine you give it. On the SQL lens, it writes SQL. to_sql(query, dialect) shows you that SQL, with its parameters.

This query asks which variables describe the person: those whose concept is "Demographic characteristics".

import duckdb

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

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)

query = Query(
    match=[node("v", "Variable"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
    where=compare(prop("c", "label"), "==", "Demographic characteristics"),
    returns=[prop("v", "name"), prop("v", "label")],
    order_by=[asc(prop("v", "name"))],
    dataset_id="m20-codebook",
)
for row in run(query, lens):
    print(row)

sql, parameters = to_sql(query, "duckdb")
print(parameters)
print(sql)

Expected output:

(Text(value='AGE', lang=None), Text(value='Age in completed years', lang=None))
(Text(value='AGEGRP', lang=None), Text(value='Age group', lang=None))
(Text(value='SEX', lang=None), Text(value='Sex of the person', lang=None))
['2d577bd9243ecad89f7c9db5b4dadfeb', 'm20-codebook', 'Demographic characteristics']
WITH RECURSIVE v0 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'Variable')
    AND key IN (SELECT key FROM ddigraph_memberships WHERE dataset = $2
      UNION ALL SELECT CAST($1 AS TEXT))
),
v1 (key) AS MATERIALIZED (
  SELECT key FROM ddigraph_nodes
  WHERE key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'Concept')
    AND key IN (SELECT key FROM ddigraph_memberships WHERE dataset = $2
      UNION ALL SELECT CAST($1 AS TEXT))
)
SELECT c0, c1, c2, c3
FROM (
SELECT p0.string_value AS c0, p0.language AS c1, p1.string_value AS c2, p1.language AS c3
FROM (
  SELECT n0.key AS n0, n1.key AS n1
  FROM v0 AS n0, v1 AS n1, ddigraph_relationships AS e0
  WHERE e0.start_key = n0.key AND e0.type = 'USES_CONCEPT' AND e0.end_key = n1.key
) AS m
LEFT JOIN ddigraph_properties AS p0
  ON p0.key = m.n0 AND p0.name = 'name'
LEFT JOIN ddigraph_properties AS p1
  ON p1.key = m.n0 AND p1.name = 'label'
LEFT JOIN ddigraph_properties AS p2
  ON p2.key = m.n1 AND p2.name = 'label'
WHERE (p2.string_value = $3)
) AS r
ORDER BY c0 ASC NULLS LAST, coalesce(lower(c1), '') ASC, coalesce(c1, '') ASC

Read the parts:

  • The rows. A name and a label are text properties, so run gives each as a Text, with its value and its language.
  • The parameters. Every literal is a parameter. $3 is 'Demographic characteristics'. $2 is the dataset ID, and $1 is the key of its Dataset node, which dataset_id= also lets through.
  • The CTEs. Each node pattern with a label is a small query of its own, v0 and v1, marked MATERIALIZED. So the database picks each pattern's nodes first, then joins them.
  • The joins. The edge is a row of ddigraph_relationships, and each property is a LEFT JOIN, so a missing value is NULL, not a lost row.

run(query, target) gives the same rows on Neo4j, PostgreSQL or the in-memory lens: ddigraph.query checks that on every engine. On PostgreSQL, to_sql(query, "postgres") adds COLLATE "C" to each string comparison, so text sorts by code point as it does in Python.

4. Join DDI metadata with your own table

The lens's tables are plain tables. So you can join them with your own, in the same database. Say you keep a table of how many of the survey's 10,412 respondents answered each question. A report that flags the variables with fewer than 10,000 answers needs both, and the variable's universe tells you why a count is low:

import duckdb

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

connection = duckdb.connect()
lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)

# Your own table: how many respondents answered each question
connection.execute("CREATE TABLE answered (variable VARCHAR, responses INTEGER)")
connection.execute(
    "INSERT INTO answered VALUES ('SEX', 10412), ('AGE', 10412), ('REGION', 10412),"
    " ('EDUC', 9891), ('HOURS', 6024)"
)

REPORT = """
SELECT name.string_value, a.responses, coalesce(universe.string_value, 'all respondents')
FROM ddigraph_memberships AS m
JOIN ddigraph_labels AS l ON l.key = m.key AND l.flavor = m.flavor
JOIN ddigraph_properties AS name ON name.key = m.key AND name.name = 'name'
JOIN answered AS a ON a.variable = name.string_value
LEFT JOIN ddigraph_relationships AS r ON r.start_key = m.key AND r.type = 'IN_UNIVERSE'
LEFT JOIN ddigraph_properties AS universe ON universe.key = r.end_key AND universe.name = 'label'
WHERE m.dataset = $1 AND l.type_label = 'Variable' AND a.responses < $2
ORDER BY a.responses
"""
for row in lens.fetch(REPORT, ["m20-codebook", 10000]):
    print(*row, sep=" | ")

Expected output:

HOURS | 6024 | Employed persons aged 15 and over
EDUC | 9891 | all respondents

The join key is the variable's name, the name your data files use for the column. $2 is a number, and the parameter keeps its type.

The report reads two ways. HOURS has few answers by design: its universe is the employed, so only they are asked. EDUC is asked of everyone, so its 521 missing answers are real non-response, worth a look. AGEGRP and ILOSTAT are not in your table: they are derived, so nobody answers them.

A write never touches a table, column or property the lens does not own. So your own table stays when you reload the file, and so does a property row you add yourself.

5. The same on PostgreSQL

PostgreSQL takes the same code, with a psycopg connection in place of the DuckDB one. The server Module 2 starts is at postgresql://postgres:postgres@localhost:5432/postgres. Other people's datasets may share that database. So this block works only in its own dataset, m20-codebook: the query keeps to it with dataset_id=, and the block purges it at the end:

import psycopg

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

URI = "postgresql://postgres:postgres@localhost:5432/postgres"

query = Query(
    match=[node("v", "Variable"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
    returns=[prop("v", "name"), prop("c", "label")],
    order_by=[asc(prop("v", "name"))],
    dataset_id="m20-codebook",
)

with psycopg.connect(URI) as connection:
    lens = SQLLens(connection)
    print("dialect:", lens.dialect)
    result = lens.write(
        ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
        dataset_id="m20-codebook",
    )
    print(result.nodes, "nodes,", result.relationships, "relationships")
    for name, concept in run(query, lens):
        print(name, "|", concept.value)
    print("purged:", lens.purge("m20-codebook"), "nodes")
    print(
        "left:",
        lens.fetch(
            "SELECT count(*) FROM ddigraph_memberships WHERE dataset = $1", ["m20-codebook"]
        ),
    )

Expected output:

dialect: postgres
80 nodes, 48 relationships
Text(value='AGE', lang=None) | Demographic characteristics
Text(value='AGEGRP', lang=None) | Demographic characteristics
Text(value='EDUC', lang=None) | Educational attainment
Text(value='HOURS', lang=None) | Working time
Text(value='ILOSTAT', lang=None) | Labour market status
Text(value='REGION', lang=None) | Place of residence
Text(value='SEX', lang=None) | Demographic characteristics
purged: 80 nodes
left: [(0,)]

What to know:

  • Transactions. The lens runs each write, read and purge in a transaction of its own, so the connection may be in autocommit mode or not.
  • Purge. lens.purge(dataset) removes a dataset, and returns how many nodes it deleted. It keeps a node that another dataset also holds. A Codebook's nodes belong to it alone, so all 80 go.
  • One writer. Run one write at a time on a database. Two writes at once can fail on a node that both add.
  • No NUL character. PostgreSQL text cannot hold the character U+0000, so psycopg refuses a value with one. DuckDB holds it.

The SQL lens has no ddigraph load command, no store marker and no repair. Those are Neo4j's, for now (Module 17).

6. SQL/PGQ with duckpgq

SQL/PGQ is the graph part of the SQL standard. It adds a GRAPH_TABLE clause that matches node and edge patterns, much as Cypher does, inside a SQL statement. duckpgq is a DuckDB extension that brings it to DuckDB.

The lens never installs or loads an extension itself. You do it once on the connection: INSTALL downloads the extension the first time, and LOAD turns it on. Then lens.property_graph() makes a property graph, ddigraph_graph, over the lens's tables: each row of ddigraph_nodes is a vertex, and each row of ddigraph_relationships an edge. From then on, run sends SQL/PGQ:

import duckdb

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

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

lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)
print("property graph:", lens.property_graph())

query = Query(
    match=[node("v", "Variable"), node("c", "Concept"), edge("v", "USES_CONCEPT", "c")],
    returns=[prop("v", "name"), prop("c", "label")],
    order_by=[asc(prop("v", "name"))],
)
for name, concept in run(query, lens):
    print(name, "|", concept.value)

text = to_pgq(query)
start = text.index("FROM GRAPH_TABLE")
print(text[start : text.index(") g", start) + 3])

Expected output:

property graph: True
Text(value='AGE', lang=None) | Demographic characteristics
Text(value='AGEGRP', lang=None) | Demographic characteristics
Text(value='EDUC', lang=None) | Educational attainment
Text(value='HOURS', lang=None) | Working time
Text(value='ILOSTAT', lang=None) | Labour market status
Text(value='REGION', lang=None) | Place of residence
Text(value='SEX', lang=None) | Demographic characteristics
FROM GRAPH_TABLE (ddigraph_graph
    MATCH (n0:ddigraph_node WHERE n0.key IN (SELECT key FROM v0))-[e0:ddigraph_relationship WHERE e0.type = 'USES_CONCEPT']->(n1:ddigraph_node WHERE n1.key IN (SELECT key FROM v1))
    COLUMNS (n0.key AS n0, n1.key AS n1)
  ) g

The rows are the same as with plain SQL. The block prints only the GRAPH_TABLE part of the text: the pattern (n0)-[e0]->(n1) reads like Cypher. Three parts stay plain SQL:

  • Labels. A type label is a row of ddigraph_labels, not a label of the property graph. So each vertex is tested with a WHERE, against the same CTEs to_sql makes.
  • Reaches. duckpgq's paths cannot keep each step to one relationship type, so a reach (hops=) stays a recursive SQL query.
  • Literals. duckpgq drops the parameters of a statement with a GRAPH_TABLE. So to_pgq writes each literal into the text, escaped, and returns no parameters.

You can write your own GRAPH_TABLE too. This one asks a question of the DDI-Lifecycle version of the survey: how many questions and variables use each code list?

import duckdb

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

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

lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m20-survey"),
    dataset_id="m20-survey",
)
lens.property_graph()

REUSE = """
SELECT label.string_value AS code_list, count(*) AS users
FROM GRAPH_TABLE (ddigraph_graph
  MATCH (a:ddigraph_node)-[e:ddigraph_relationship WHERE e.type = 'USES_CODELIST']->(l:ddigraph_node)
  COLUMNS (l.key AS l)
) g
JOIN ddigraph_properties AS label ON label.key = g.l AND label.name = 'label'
GROUP BY code_list
ORDER BY users DESC, code_list
"""
for row in connection.execute(REUSE).fetchall():
    print(*row)

Expected output:

Yes or no 3
Highest level of education 2
Region 2
Sex 2
Age group 1
Labour force status (ILO) 1

COLUMNS says what each match gives back, and the rest is ordinary SQL: a join for the code list's label, then GROUP BY. The answer shows how DDI-Lifecycle reuses a code list. "Yes or no" serves three questions, WORK, LOOK and AVAIL. Sex, Region and education each serve their question and their variable. Age group and Labour force status serve only a derived variable, which no question asks.

The duckdb extra pins DuckDB below version 2, since duckpgq has no build for DuckDB 2 yet. If INSTALL cannot reach the internet, it fails; the rest of the module works without duckpgq.


Exercises

Scenario

Your statistics office keeps its Labour Force Survey data in PostgreSQL, and its analysts use DuckDB on their laptops. They want the DDI metadata next to the data, in SQL.

Exercise 1 (O1). Write tests/fixtures/lfs_cdi.xml, the survey in DDI-CDI, to DuckDB in memory, as the dataset m20-cdi. Print the number of rows in each of the six tables.

Expected output:

ddigraph_nodes: 91
...
ddigraph_memberships: 90
Answer
import duckdb

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

connection = duckdb.connect()
lens = SQLLens(connection)
lens.write(ir.parse("tests/fixtures/lfs_cdi.xml", dataset_id="m20-cdi"), dataset_id="m20-cdi")
for table in TABLES:
    (count,) = connection.execute(f"SELECT count(*) FROM {table}").fetchone()
    print(f"{table}: {count}")
ddigraph_nodes: 91
ddigraph_labels: 181
ddigraph_properties: 493
ddigraph_relationships: 92
ddigraph_relationship_properties: 0
ddigraph_memberships: 90

91 nodes, but 90 memberships: the Dataset node keeps its own provenance and has no membership. Several CDI labels exist in more than one flavor, so there are more label rows than nodes.

Exercise 2 (O2). In the Codebook file, list the categories of the variable whose name you pass as $1, in their order, each with its code. Run it for AGEGRP.

Expected output:

1 15-24
2 25-34
...
6 65 and over
Answer
import duckdb

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

lens = SQLLens(duckdb.connect())
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)

CATEGORIES = """
SELECT code.string_value, category.string_value
FROM ddigraph_properties AS variable
JOIN ddigraph_relationships AS r ON r.start_key = variable.key AND r.type = 'USES_CATEGORY'
JOIN ddigraph_properties AS code ON code.key = r.end_key AND code.name = 'code'
JOIN ddigraph_properties AS category ON category.key = r.end_key AND category.name = 'label'
WHERE variable.name = 'name' AND variable.string_value = $1
ORDER BY r.ordinal
"""
for code, label in lens.fetch(CATEGORIES, ["AGEGRP"]):
    print(code, label)
1 15-24
2 25-34
3 35-44
4 45-54
5 55-64
6 65 and over

USES_CATEGORY is an ordered edge, so its ordinal gives the categories' order. A Codebook category keeps its code in the property code, so one more join brings it. The name is a parameter, so the same query serves any variable: try ILOSTAT.

Exercise 3 (O3). Make your own table stewards(concept, steward). The Demography team looks after "Demographic characteristics", the Education team after "Educational attainment", and the Labour team after "Labour market status" and "Working time". Print each variable's name, its concept, and the concept's steward, or nobody.

Expected output:

AGE | Demographic characteristics | Demography team
...
REGION | Place of residence | nobody
...
Answer
import duckdb

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

connection = duckdb.connect()
lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m20-codebook"),
    dataset_id="m20-codebook",
)

connection.execute("CREATE TABLE stewards (concept VARCHAR, steward VARCHAR)")
connection.execute(
    "INSERT INTO stewards VALUES ('Demographic characteristics', 'Demography team'),"
    " ('Educational attainment', 'Education team'),"
    " ('Labour market status', 'Labour team'), ('Working time', 'Labour team')"
)

OWNERS = """
SELECT variable.string_value, concept.string_value, coalesce(s.steward, 'nobody')
FROM ddigraph_relationships AS r
JOIN ddigraph_properties AS variable ON variable.key = r.start_key AND variable.name = 'name'
JOIN ddigraph_properties AS concept ON concept.key = r.end_key AND concept.name = 'label'
LEFT JOIN stewards AS s ON s.concept = concept.string_value
WHERE r.type = 'USES_CONCEPT'
ORDER BY 1
"""
for row in lens.fetch(OWNERS):
    print(*row, sep=" | ")
AGE | Demographic characteristics | Demography team
AGEGRP | Demographic characteristics | Demography team
EDUC | Educational attainment | Education team
HOURS | Working time | Labour team
ILOSTAT | Labour market status | Labour team
REGION | Place of residence | nobody
SEX | Demographic characteristics | Demography team

The LEFT JOIN keeps REGION, whose concept has no steward yet, and coalesce fills the gap. The join runs inside the database: no data leaves it.

Exercise 4 (O4). On PostgreSQL, write tests/fixtures/lfs_lifecycle.xml as the dataset m20-survey. Count its nodes with a ddigraph.query that returns count() alone, purge the dataset, and count again.

Expected output:

before: [(87,)]
after: [(0,)]
Answer
import psycopg

from ddigraph import ir
from ddigraph.lens.sql import SQLLens
from ddigraph.query import Query, count, node, run

query = Query(match=[node("n")], returns=[count()], dataset_id="m20-survey")

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as connection:
    lens = SQLLens(connection)
    lens.write(
        ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m20-survey"),
        dataset_id="m20-survey",
    )
    print("before:", run(query, lens))
    lens.purge("m20-survey")
    print("after:", run(query, lens))
before: [(87,)]
after: [(0,)]

A node pattern with no label matches any node, and dataset_id= keeps the members of the dataset and its Dataset node: 87 in all. After the purge, nothing of m20-survey is left in the shared database.

Exercise 5 (O5). With duckpgq loaded, write a GRAPH_TABLE match over the DDI-L file: from the question EDUC, along USES_CODELIST to its code list, along CONTAINS to each code, then along HAS_CATEGORY to the code's category. Keep the first vertex to question items. Join ddigraph_properties to print the code list's label, each code's value and its category's label, in the order of the values.

Expected output:

Highest level of education | 1 | Primary or less (ISCED 0-1)
...
Highest level of education | 5 | Tertiary (ISCED 5-8)
Answer
import duckdb

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

connection = duckdb.connect()
connection.execute("INSTALL duckpgq FROM community")
connection.execute("LOAD duckpgq")
lens = SQLLens(connection)
lens.write(
    ir.parse("tests/fixtures/lfs_lifecycle.xml", dataset_id="m20-survey"),
    dataset_id="m20-survey",
)
lens.property_graph()

PATH = """
SELECT code_list.string_value, code.string_value, category.string_value
FROM GRAPH_TABLE (ddigraph_graph
  MATCH (q:ddigraph_node WHERE q.key IN (SELECT key FROM ddigraph_labels WHERE type_label = 'QuestionItem'))
        -[u:ddigraph_relationship WHERE u.type = 'USES_CODELIST']->(l:ddigraph_node)
        -[s:ddigraph_relationship WHERE s.type = 'CONTAINS']->(k:ddigraph_node)
        -[h:ddigraph_relationship WHERE h.type = 'HAS_CATEGORY']->(c:ddigraph_node)
  COLUMNS (q.key AS q, l.key AS l, k.key AS k, c.key AS c)
) g
JOIN ddigraph_properties AS question ON question.key = g.q AND question.name = 'name'
JOIN ddigraph_properties AS code_list ON code_list.key = g.l AND code_list.name = 'label'
JOIN ddigraph_properties AS code ON code.key = g.k AND code.name = 'value'
JOIN ddigraph_properties AS category ON category.key = g.c AND category.name = 'label'
WHERE question.string_value = 'EDUC'
ORDER BY code.string_value
"""
for row in connection.execute(PATH).fetchall():
    print(*row, sep=" | ")
Highest level of education | 1 | Primary or less (ISCED 0-1)
Highest level of education | 2 | Lower secondary (ISCED 2)
Highest level of education | 3 | Upper secondary (ISCED 3)
Highest level of education | 4 | Post-secondary non-tertiary (ISCED 4)
Highest level of education | 5 | Tertiary (ISCED 5-8)

The three edges are one pattern in MATCH, as in Cypher. Each edge's type is a column of the edge, so a WHERE inside the brackets picks it. The variable EDUC uses the same code list as the question, so without the QuestionItem test each row would come twice. In DDI-Lifecycle each code has an ID of its own, so the path needs the CONTAINS step between the list and its categories.


Quiz

Question 1 (O1): Why does the lens keep one row per property in ddigraph_properties, with a column per type, and not one JSON column per node?

A. DuckDB cannot store JSON.

B. A typed column keeps each value's type with nothing to decode, and SQL compares, sorts and indexes it as that type.

C. JSON would take more disk space.

D. It is the only layout PostgreSQL allows.

Answer

B. JSON would not keep every type: PostgreSQL's jsonb stores a number as a decimal, so a float could come back as an integer. A and D are false: both databases hold JSON well.

Question 2 (O1): The Codebook file of the survey has 80 nodes but 158 rows in ddigraph_labels. Why?

A. Some nodes were written twice.

B. The table also holds the edges' types.

C. A label that several flavors share, such as Variable, is a row for each flavor. Join it through a membership, on the key and the flavor.

D. Each stub has two labels.

Answer

C. A join on the key alone would give a variable three times. Joining ddigraph_memberships to ddigraph_labels on key and flavor gives each membership the one label its dataset reads.

Question 3 (O2): Why pass a value to lens.fetch as $1, with a list, rather than paste it into the SQL text?

A. A parameter keeps a quote or other character in the value from breaking, or changing, the statement, and the same text runs on DuckDB and PostgreSQL.

B. Pasted values are slower to type.

C. lens.fetch refuses any SQL without parameters.

D. Parameters are only needed on PostgreSQL.

Answer

A. A value such as O'Brien would end a pasted string early. With a parameter, the database never reads the value as SQL. C is false: Exercise 3's query has no parameter at all.

Question 4 (O3): You add your own table answered to the database, then reload the DDI file with lens.write. What happens to answered?

A. The lens drops every table that is not its own.

B. It stays. A write never touches a table, column or property the lens does not own.

C. The lens adds its rows to ddigraph_properties.

D. The reload fails until you drop it.

Answer

B. The lens only writes its own six tables, and in them, only what the mapping spec owns. Your own property rows and columns stay too.

Question 5 (O4): Several people use the same PostgreSQL database. Which habit keeps your work from touching theirs?

A. Drop the ddigraph_* tables before each write.

B. Use a dataset ID of your own, keep queries to it with dataset_id=, and lens.purge it when you are done.

C. Run every write twice.

D. Use DuckDB's SQL on PostgreSQL.

Answer

B. The tables are shared, but each row belongs to a dataset. A purge removes only what no other dataset holds. A would delete everyone's data.

Question 6 (O5): lens.property_graph() returns False on a DuckDB connection. What is the likely cause?

A. The file has no edges.

B. The property graph only works on PostgreSQL.

C. The lens installs duckpgq itself, and the download failed.

D. duckpgq is not loaded on that connection. The lens never installs or loads an extension: run INSTALL duckpgq FROM community and LOAD duckpgq first.

Answer

D. Without duckpgq, property_graph() returns False and run falls back to plain SQL, with the same rows. B is backwards: PostgreSQL has no duckpgq, so there it always returns False.


Check yourself

  • I can write a DDI file to DuckDB with SQLLens(duckdb.connect()), and say what each of the six ddigraph_* tables holds. (O1)
  • I can query the tables with lens.fetch and $1 parameters, and run a ddigraph.query with run, reading its SQL with to_sql. (O2)
  • I can join DDI metadata with a table of my own. (O3)
  • I can do the same on PostgreSQL 18, under my own dataset ID, and purge what I wrote. (O4)
  • I can match the graph as SQL/PGQ with duckpgq, and read the query to_pgq writes. (O5)

Next: Module 21: RDF and SPARQL with Oxigraph