PyArrow IPC 与 DuckDB Parquet 到 MatrixOne

路径与安装

本路径实际执行 PyArrow IPC 文件读写,以及 DuckDB SQL 转换、Parquet 写出和重新读取,再通过 DBAPI 写入 MatrixOne。它是显式 SQL 桥接,不是 MatrixOne 原生扫描所有湖格式的证明。参考 PyArrow 26.0.0、DuckDB 1.5.6。先完成共用连接,安装 pyarrow duckdb pymysql。

明确文件 schema

以下完整脚本先完成文件回环并逐字段比较,再加载样例 ID 201。选择微秒时间戳来覆盖 SQL DATETIME 范围,避免纳秒类型的范围限制。SQL TIME 是时长,文件中用带符号微秒数;decimal65 使用精确字符串时,必须同时保留精度、scale 元数据和目标 SQL 类型。SQL 中的 DECIMAL 上限不能当作 Iceberg 或 DuckDB 的原生 decimal 上限。

from decimal import Decimal
from pathlib import Path
import duckdb
import pyarrow as pa
import pyarrow.ipc as ipc
from mo_common import connect

schema = pa.schema([("id", pa.int64()), ("amount", pa.decimal128(38,18)),
                    ("payload", pa.binary()), ("label", pa.string()), ("rev", pa.int64())])
t = pa.Table.from_pylist([dict(id=201, amount=Decimal("12345678901234567890.123456789012345678"),
                              payload=b"\x00\xff\x80", label="文件😀", rev=0)], schema=schema)
with pa.OSFile("rows.arrow", "wb") as f:
    with ipc.new_file(f, t.schema) as writer:
        writer.write_table(t)
with pa.memory_map("rows.arrow", "r") as f:
    restored = ipc.open_file(f).read_all()
assert restored.to_pylist() == t.to_pylist()
with duckdb.connect() as d:
    d.execute("SET threads=1")
    d.register("input_rows", restored)
    transformed = d.execute("SELECT id,amount,payload,label||'→ETL' AS label,rev+1 AS rev FROM input_rows").fetch_arrow_table()
    d.register("export_rows", transformed)
    path = str(Path("rows.parquet").resolve())
    d.execute("COPY export_rows TO ? (FORMAT PARQUET)", [path])
    scanned = d.execute("SELECT * FROM read_parquet(?)", [path]).fetch_arrow_table()
assert scanned.to_pylist() == transformed.to_pylist()
rows = [[r[k] for k in ("id","amount","payload","label","rev")] for r in scanned.to_pylist()]
with connect() as d:
    try:
        with d.cursor() as c:
            c.executemany("INSERT INTO lake_demo(id,amount,payload,label,rev) VALUES(%s,%s,%s,%s,%s)", rows)
        d.commit()
    except Exception:
        d.rollback()
        raise

类型边界与恢复

Parquet/IPC 保留 schema;schema 文件和数据文件一起归档。UInt64 必须用 uint64 或足够精度的 decimal,不能经过 double。JSON、ENUM/SET、UUID 的字符串表示要说明域约束是否保留。对于 -1 微秒和超过24小时的 TIME,验收符号和总微秒数,不能只检查时分秒。

文件写出成功与 SQL 提交是两个独立的边界。保留文件哈希、批次 ID、目标键范围、SQL 提交凭证;提交结果未知时先回读再决定重放。增量文件不自动包含删除事件,应使用独立 tombstone 数据集并按键应用。Schema evolution 要同步文件 schema 和 SQL DDL。

两条桥接主计划各完成5000个组合,文件与 SQL 效果仍分别归属原生组件和适配器。历史映射问题:matrixone#29845。