How do I join the result of a SQL query with rows from a CSV file?
The orders arrive as a CSV file. The customers live in a database. You need each order with its customer attached, and a list of the orders whose customer was not found.
There is no join pipe in the standard library, so the join is a pipe of your own: a short Python script that loads the query result into a dictionary and looks every incoming record up in it. The CSV side is never held in memory.
A pipe is a data-processing step with declared inputs and outputs; a pipeline connects pipes.
What you need
- The
openflangecommand, release v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 python3onPATH. Only the standard library is used: nothing to install with pip.- An empty directory. Create the files below in it under exactly these names and run every command from that directory.
- No account and no key. Nothing leaves your machine.
Steps
1. Create the database and the CSV file
make-db.py writes a SQLite database with four customers, one of them inactive. orders.csv has six orders: two for the inactive customer or for a customer that does not exist.
#!/usr/bin/env python3
"""Creates the SQLite database this recipe queries, beside the pipe that reads it. Standard library only."""
import os
import sqlite3
PATH = "pipes/join-customers/crm.db"
if os.path.exists(PATH):
os.remove(PATH)
db = sqlite3.connect(PATH)
db.executescript("""
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, segment TEXT NOT NULL, active INTEGER NOT NULL);
INSERT INTO customers VALUES
(1, 'Ada Lovelace', 'enterprise', 1),
(2, 'Bo Li', 'startup', 1),
(3, 'Grace Hopper', 'enterprise', 0),
(4, 'Linus', 'startup', 1);
""")
db.commit()
db.close()
print(PATH + ": 4 customers")order_id,customer_id,amount_cents
1001,1,12000
1002,2,800
1003,1,4300
1004,3,1500
1005,9,600
1006,2,2100python3 make-db.pypipes/join-customers/crm.db: 4 customers2. Write the join pipe
The manifest declares one input, one output, the four parameters and the permissions the script needs: it starts a subprocess and reads one file. The script runs the query once, then answers one line per record.
---
spec: openflange.org/pipe/v0.1
id: join-customers
version: 0.1.0
title: Join with a database query (Python, SQLite)
description: Adds the columns of a SQL query result to every record whose key matches; records without a match get `null`.
license: Apache-2.0
keywords: [join, lookup, sql, sqlite, python, recipe]
maturity: experimental
scope: record
cardinality: one-to-one
inputs:
records:
description: 'Records with the member named by `on`, e.g. {"order_id": 1001, "customer_id": 1}.'
outputs:
records:
description: The same records, in order, with the member `as` added - the matching row of the query as an object, or null.
parameters:
database:
type: string
default: crm.db
description: Path of the SQLite database file, absolute or relative to this pipe's directory. Opened read-only.
query:
type: string
default: "SELECT id, name, segment FROM customers WHERE active = 1"
description: The query. Its first column is the join key; its whole result is held in memory.
on:
type: string
default: customer_id
description: Member of the input record that is compared with the first column of the query.
as:
type: string
default: customer
description: Member that receives the matching row.
implementation:
type: script
language: python
path: join.py
permissions:
subprocess: true
filesystem:
read: ["crm.db"]
---
# Join with a database query (Python, SQLite)
Implements the [OpenFlange](https://openflange.org/) specification.
A left join of a stream with a query result (a hash join): the query runs
once, before the first record, and its rows are kept in a dictionary by their
first column; the stream is then read one record at a time.
- **The query result is held in memory**, the stream is not. Put the small
side in the database.
- Keys are compared as SQLite returns them: cast the stream's key first
(`std:cast`) so that `1` meets `1`, not `"1"`.
- If the query returns the same key twice, the last row wins.
- Permissions: `subprocess` (it starts `python3`) and `filesystem.read` for
`crm.db` in this directory - a manifest can only name paths inside its own
package. Python standard library only; no network.#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""join-customers: left join of the input stream with the result of a SQL query (SQLite).
NDJSON records in, NDJSON records out, one per input record, in order.
"""
import json
import os
import sqlite3
import sys
with open(os.environ["OPENFLANGE_CONFIG"], encoding="utf-8") as f:
PARAMS = json.load(f)["parameters"]
def load():
"""Runs the query once; returns {key: row} keyed by the first column."""
path = os.path.abspath(PARAMS["database"])
db = sqlite3.connect(f"file:{path}?mode=ro", uri=True) # read-only: a missing file is an error, not a new database
db.row_factory = sqlite3.Row
try:
return {row[0]: dict(row) for row in db.execute(PARAMS["query"])}
finally:
db.close()
def main() -> int:
try:
rows = load()
except sqlite3.Error as error:
print(f"join-customers: {error}", file=sys.stderr)
return 1
key, member = PARAMS["on"], PARAMS["as"]
for n, line in enumerate(sys.stdin, 1):
record = json.loads(line)
if not isinstance(record, dict) or key not in record:
print(f"join-customers: item {n} has no member {key!r}", file=sys.stderr)
return 1
record[member] = rows.get(record[key])
sys.stdout.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
sys.stdout.flush()
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except BrokenPipeError:
sys.exit(0)3. Connect it to the CSV
Decode the CSV, cast the key to an integer so that it equals the key the database returns, join, then split matched from unmatched with std:filter. The pipeline as a whole declares the same permissions as the pipe inside it.
# csv ─▶ decode ─▶ typed ─▶ join (SQL query on crm.db) ─▶ matched ─┬─▶ joined
# └─▶ unmatched
spec: openflange.org/pipeline/v0.1
nodes:
decode:
pipe: std:csv-decode
inputs:
in: {from: inputs.csv}
typed:
pipe: std:cast # the join key must have the type the database returns
inputs:
in: {from: decode.outputs.out}
parameters:
fields: {order_id: integer, customer_id: integer, amount_cents: integer}
join:
pipe: ./pipes/join-customers # needs subprocess and filesystem.read: granted on the command line
inputs:
records: {from: typed.outputs.out}
matched:
pipe: std:filter # rows without a customer go to `unmatched`
inputs:
in: {from: join.outputs.records}
parameters:
expr: 'item["customer"] != None'
outputs:
joined: {from: matched.outputs.out}
unmatched: {from: matched.outputs.rejected}---
spec: openflange.org/pipe/v0.1
id: join-database-csv
version: 0.1.0
title: Join a database query with a CSV
description: Reads an orders CSV and adds to every order the customer row returned by a SQL query on a SQLite database; orders without a matching customer are routed to `unmatched`.
license: Apache-2.0
keywords: [join, csv, sql, sqlite, lookup, recipe]
maturity: experimental
scope: record
inputs:
csv:
kind: text
mediaTypes: [text/csv]
description: 'Orders with a header row: order_id,customer_id,amount_cents.'
outputs:
joined:
description: 'Orders with a matching active customer: {"order_id", "customer_id", "amount_cents", "customer": {"id", "name", "segment"}}.'
unmatched:
required: false
description: Orders whose customer the query did not return, with "customer" null. If not connected they are dropped.
implementation:
type: pipeline
path: pipeline.yaml
permissions:
subprocess: true
filesystem:
read: ["pipes/join-customers/crm.db"]
---
# Join a database query with a CSV
Implements the [OpenFlange](https://openflange.org/) specification.
The CSV is streamed; the query result is loaded once and held in memory by
the `join` node. Needs `python3` and the database file
`pipes/join-customers/crm.db` (`python3 make-db.py` creates it).4. Validate and run
The two --grant flags are the consumer saying yes to what the manifest asks for. They apply to every node of the pipeline.
openflange validate .valid: . (4 nodes, 6 edges)openflange run . --grant subprocess --grant filesystem.read=pipes/join-customers/crm.db --input csv=orders.csv --output joined=joined.ndjson --output unmatched=unmatched.ndjsoncompleted in 22ms — joined: 4 records, unmatched: 2 records{"order_id":1001,"customer_id":1,"amount_cents":12000,"customer":{"id":1,"name":"Ada Lovelace","segment":"enterprise"}}
{"order_id":1002,"customer_id":2,"amount_cents":800,"customer":{"id":2,"name":"Bo Li","segment":"startup"}}
{"order_id":1003,"customer_id":1,"amount_cents":4300,"customer":{"id":1,"name":"Ada Lovelace","segment":"enterprise"}}
{"order_id":1006,"customer_id":2,"amount_cents":2100,"customer":{"id":2,"name":"Bo Li","segment":"startup"}}{"order_id":1004,"customer_id":3,"amount_cents":1500,"customer":null}
{"order_id":1005,"customer_id":9,"amount_cents":600,"customer":null}Four orders have a customer. Order 1004 belongs to an inactive customer and order 1005 to an unknown one: the query returned no row for them, so they are in unmatched.ndjson.
5. See what happens without the grants
Nothing runs, and the runner exits with status 2. It names the missing permissions twice: for the pipeline, and for the node inside it, whose path is written relative to the directory of that pipe. Use the two flags of step 4.
openflange run . --input csv=orders.csvOPENFLANGE.md
E_PERMISSION: pipe "join-database-csv" needs permissions that were not granted: filesystem.read: pipes/join-customers/crm.db; subprocess (OPENFLANGE.md, at permissions)
hint: grant it with `--grant filesystem.read=pipes/join-customers/crm.db --grant subprocess` (or `grants:` on the node), or run with `--trusted`
pipeline.yaml
E_PERMISSION: node "join": pipe "join-customers" needs permissions that were not granted: filesystem.read: crm.db; subprocess (pipeline.yaml:15:3, at nodes.join)
|
15 | join:
| ^
hint: grant it with `--grant filesystem.read=crm.db --grant subprocess` (or `grants:` on the node), or run with `--trusted`
E_PERMISSION: node "join": pipe "join-customers" runs a subprocess, which was not granted (pipeline.yaml:15:3, at nodes.join)
|
15 | join:
| ^
hint: grant it with `--grant subprocess` (or `grants: {subprocess: true}` on the node), or run with `--trusted`
3 errors in 2 files6. Test it
One test file for the pipeline, one for the join pipe on its own. Both need the database created in step 1.
# requires: python3, and pipes/join-customers/crm.db (run `python3 make-db.py` first)
spec: openflange.org/test/v0.1
pipe: ..
tests:
- name: every order gets its customer; inactive and unknown customers are routed to unmatched
grants: {subprocess: true, filesystem: {read: ["../pipes/join-customers/crm.db"]}}
inputs:
csv:
text: |
order_id,customer_id,amount_cents
1001,1,12000
1004,3,1500
1005,9,600
1006,2,2100
expect:
outputs:
joined:
values:
- {order_id: 1001, customer_id: 1, amount_cents: 12000, customer: {id: 1, name: Ada Lovelace, segment: enterprise}}
- {order_id: 1006, customer_id: 2, amount_cents: 2100, customer: {id: 2, name: Bo Li, segment: startup}}
unmatched:
values:
- {order_id: 1004, customer_id: 3, amount_cents: 1500, customer: null}
- {order_id: 1005, customer_id: 9, amount_cents: 600, customer: null}
- name: a header row alone gives no output
grants: {subprocess: true, filesystem: {read: ["../pipes/join-customers/crm.db"]}}
inputs:
csv: {text: "order_id,customer_id,amount_cents\n"}
expect:
outputs:
joined: {count: 0}
unmatched: {count: 0}
- name: a key that is not a number is refused by the cast, before the join
grants: {subprocess: true, filesystem: {read: ["../pipes/join-customers/crm.db"]}}
inputs:
csv: {text: "order_id,customer_id,amount_cents\n1001,one,12000\n"}
expect:
status: failed
error: {code: E_RUNTIME}
- name: without the grants the pipeline is refused before anything runs
inputs:
csv: {text: "order_id,customer_id,amount_cents\n"}
expect:
status: failed
error: {code: E_PERMISSION}# requires: python3, and ../crm.db (run `python3 make-db.py` in the recipe directory first)
spec: openflange.org/test/v0.1
tests:
- name: the matching row of the query is added; no match gives null
grants: {subprocess: true, filesystem: {read: ["../crm.db"]}}
inputs:
records:
values:
- {order_id: 1, customer_id: 2}
- {order_id: 2, customer_id: 9}
expect:
outputs:
records:
values:
- {order_id: 1, customer_id: 2, customer: {id: 2, name: Bo Li, segment: startup}}
- {order_id: 2, customer_id: 9, customer: null}
- name: the query, the key and the target member are parameters
grants: {subprocess: true, filesystem: {read: ["../crm.db"]}}
parameters:
query: "SELECT name, id FROM customers"
on: who
as: match
inputs:
records:
values: [{who: Grace Hopper}]
expect:
outputs:
records:
values: [{who: Grace Hopper, match: {name: Grace Hopper, id: 3}}]
- name: a query that does not run fails the run
grants: {subprocess: true, filesystem: {read: ["../crm.db"]}}
parameters: {query: "SELECT id FROM no_such_table"}
inputs:
records:
values: [{customer_id: 1}]
expect:
status: failed
error: {code: E_RUNTIME}
- name: a record without the key fails the run
grants: {subprocess: true, filesystem: {read: ["../crm.db"]}}
inputs:
records:
values: [{order_id: 1}]
expect:
status: failed
error: {code: E_RUNTIME}openflange test . ./pipes/join-customerstests/join-database-csv.test.yaml
ok every order gets its customer; inactive and unknown customers are routed to unmatched
ok a header row alone gives no output
ok a key that is not a number is refused by the cast, before the join
ok without the grants the pipeline is refused before anything runs
pipes/join-customers/tests/join-customers.test.yaml
ok the matching row of the query is added; no match gives null
ok the query, the key and the target member are parameters
ok a query that does not run fails the run
ok a record without the key fails the run
ok 8 tests passed in 2 files (184ms)Limits
- SQLite, not DuckDB. DuckDB is not installed on the machine where these pages are verified, so the DuckDB examples of the repository could not be run and no DuckDB output is shown. The DuckDB SQL example shows a SQL query as a pipe (an aggregation, not this join), with output taken from the repository.
- The query result is held in memory; the CSV is not. Put the small side in the query. If both sides are large, do the join inside the database.
- It is an equality join on one key. The first column of the query is the key, the last row wins when a key repeats, and
1does not equal"1": cast first. - A database server (PostgreSQL, MySQL) needs a driver and a
networkpermission instead offilesystem.read. That variant is not shown and was not run. - A manifest can only name paths inside its own package, which is why
crm.dbsits in the directory of the pipe. - A subprocess is not sandboxed by this runner: the grants are checked before the run, they do not confine the Python process.
- The script exchanges one line per record with the runner. For millions of rows declare batch mode so that it receives many records per line.
Related pages
- Standard pipes used here:
std:csv-decode,std:cast,std:filter - Concepts behind it: Permissions, Pipelines, Ports
- Examples from the repository: Aggregate with DuckDB SQL
- Building this with an AI agent? Give it the guide for agents: the rules, the file layout and the commands to check its own work.
Every command on this page was run on Linux with openflange 0.0.1 (go1.27.1 linux/amd64), built from openflange-go commit 11cf8cc5378d70858724b16aa937d7f3b98c085d. The files and the recorded output are kept in the site repository under sites/dev/test/fixtures/recipes/join-database-csv/, and a test compares this page with them byte for byte.