Как соединить результат SQL-запроса со строками CSV-файла?
Заказы приходят CSV-файлом. Клиенты живут в базе данных. Нужен каждый заказ вместе с его клиентом и список заказов, для которых клиент не нашёлся.
В стандартной библиотеке нет пайпа для соединения, поэтому соединение — ваш собственный пайп: короткий скрипт на Python, который загружает результат запроса в словарь и ищет в нём каждую входящую запись. Сторона CSV в памяти не хранится.
Пайп — шаг обработки данных с объявленными входами и выходами; пайплайн соединяет пайпы.
Что понадобится
- Команда
openflange, релиз v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 python3вPATH. Используется только стандартная библиотека: через pip ничего ставить не нужно.- Пустой каталог. Создайте в нём файлы, приведённые ниже, точно под этими именами и выполняйте все команды из этого каталога.
- Ни учётной записи, ни ключа. Данные не покидают вашу машину.
Шаги
1. Создайте базу данных и CSV-файл
make-db.py записывает базу SQLite с четырьмя клиентами, один из которых неактивен. В orders.csv шесть заказов: два из них относятся к неактивному клиенту или к клиенту, которого нет.
#!/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. Напишите пайп для соединения
Манифест объявляет один вход, один выход, четыре параметра и разрешения, которые нужны скрипту: он запускает подпроцесс и читает один файл. Скрипт выполняет запрос один раз, а затем отвечает одной строкой на каждую запись.
---
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. Подключите его к CSV
Разобрать CSV, привести ключ к целому числу, чтобы он совпадал с ключом из базы, соединить, затем отделить найденные записи от ненайденных с помощью std:filter. Пайплайн в целом объявляет те же разрешения, что и пайп внутри него.
# 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. Проверьте и запустите
Два флага --grant — это согласие потребителя на то, о чём просит манифест. Они действуют на все узлы пайплайна.
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}У четырёх заказов есть клиент. Заказ 1004 относится к неактивному клиенту, а заказ 1005 — к неизвестному: запрос не вернул для них строки, поэтому они в unmatched.ndjson.
5. Посмотрите, что будет без разрешений
Ничего не запускается, раннер завершается с кодом 2. Недостающие разрешения он называет дважды: для пайплайна и для узла внутри него, путь которого записан относительно каталога этого пайпа. Используйте два флага из шага 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. Протестируйте
Один файл тестов для пайплайна, другой — для пайпа соединения отдельно. Обоим нужна база данных, созданная на шаге 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)Ограничения
- SQLite, а не DuckDB. На машине, где проверяются эти страницы, DuckDB не установлен, поэтому примеры с DuckDB из репозитория выполнить не удалось, и вывод DuckDB не показан. Пример с DuckDB SQL показывает SQL-запрос как пайп (агрегацию, а не это соединение) с выводом, взятым из репозитория.
- Результат запроса хранится в памяти, CSV — нет. Меньшую сторону кладите в запрос. Если велики обе стороны, выполняйте соединение внутри базы данных.
- Это соединение по равенству одного ключа. Ключ — первая колонка запроса; если ключ повторяется, побеждает последняя строка;
1не равно"1", поэтому сначала приведите тип. - Серверу баз данных (PostgreSQL, MySQL) нужен драйвер и разрешение
networkвместоfilesystem.read. Этот вариант не показан и не выполнялся. - Манифест может называть только пути внутри собственного пакета, поэтому
crm.dbлежит в каталоге пайпа. - Этот раннер не изолирует подпроцессы: разрешения проверяются до запуска, но не ограничивают процесс Python.
- Скрипт обменивается с раннером одной строкой на запись. Для миллионов строк объявите пакетный режим, чтобы он получал много записей в одной строке.
Связанные страницы
- Стандартные пайпы в этом рецепте:
std:csv-decode,std:cast,std:filter - Концепции, на которых он построен: Разрешения, Пайплайны, Порты
- Примеры из репозитория: Агрегация на DuckDB SQL
- Собираете это с помощью ИИ-агента? Дайте ему руководство для агентов: правила, раскладку файлов и команды, которыми он проверит собственную работу.
Все команды на этой странице выполнены в Linux с openflange 0.0.1 (go1.27.1 linux/amd64), собранным из коммита 11cf8cc5378d70858724b16aa937d7f3b98c085d репозитория openflange-go. Файлы и записанный вывод хранятся в репозитории сайта в каталоге sites/dev/test/fixtures/recipes/join-database-csv/, и тест побайтно сравнивает с ними эту страницу.