pandas、PETL、Polars 和 Dask 批量写入

路径与前置条件

先完成连接与样例。验证实际调用了 pandas to_sql、PETL appenddb、Polars write_database、Dask to_sql,并使用原生转换 API。更新、删除、重放和 DDL 是测试里的 SQL 效果适配,并非这些批量 API 自动提供 CDC。参考 pandas 3.0.6、Polars 2.0.0、SQLAlchemy 2.1.4、PyMySQL 1.2.3;参考 PETL 1.7.29、Dask 2026.8.0,固定依赖。

安装 pandas petl polars dask[dataframe] pyarrow sqlalchemy pymysql。下面四段是四条替代加载路径,分别保存执行;每次写不同样例 ID,追加写重复执行会触发主键冲突。不要使用 if_exists="replace" 覆盖已有业务表。

pandas:显式 dtype 和事务

小数使用 Decimal,DataFrame 保留 object;整数列明确 int64。预建表决定最终 SQL 类型,dtype 指定绑定类型。写入与其他 SQL 效果需要同一事务时,把事务连接传给 to_sql。

from decimal import Decimal
import pandas as pd
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from mo_common import engine

frame = pd.DataFrame({
    "id": pd.Series([101], dtype="int64"),
    "amount": pd.Series([Decimal("12345678901234567890.123456789012345678")], dtype=object),
    "payload": pd.Series([b"\x00\xff\x80"], dtype=object),
    "label": ["pandas中文😀"], "rev": pd.Series([0], dtype="int64")})
frame["label"] = frame["label"] + "→ETL"
types = dict(id=sa.BigInteger(), amount=mysql.DECIMAL(38, 18),
             payload=mysql.VARBINARY(256), label=sa.String(256), rev=sa.BigInteger())
e = engine()
try:
    with e.begin() as c:
        frame.to_sql("lake_demo", c, if_exists="append", index=False, chunksize=31, dtype=types)
finally:
    e.dispose()

PETL:DBAPI 与引号模式

PETL 的数据库写入会使用双引号引用标识符。本验证在独立连接中启用 ANSI_QUOTES,保留原 sql_mode 的其他项;不要改变全局模式。

from decimal import Decimal
import petl as etl
from mo_common import connect

t = etl.wrap([("id", "amount", "payload", "label", "rev"),
              (102, Decimal("0.000000000000000001"), b"", "PETL😀", 0)])
t = t.convert("label", lambda value: value + "→ETL")
with connect() as d:
    with d.cursor() as c:
        c.execute("SELECT @@sql_mode")
        modes = [x for x in c.fetchone()[0].split(",") if x]
        if "ANSI_QUOTES" not in modes:
            modes.append("ANSI_QUOTES")
        c.execute("SET SESSION sql_mode=%s", (",".join(modes),))
    try:
        etl.appenddb(t, d, "lake_demo", commit=True)
    except Exception:
        d.rollback()
        raise

Polars:Arrow 类型和 SQLAlchemy 写入

Arrow decimal128 保留 38 位精度。负 TIME 等 duration 列在 SQL 写入前转换为明确的 SQL 时间字符串;不要让它被当成当天时间或普通整数。

from decimal import Decimal
import pyarrow as pa
import polars as pl
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from mo_common import engine

schema = pa.schema([("id", pa.int64()), ("amount", pa.decimal128(38,18)),
                    ("payload", pa.binary()), ("label", pa.string()), ("rev", pa.int64())])
t = pl.from_arrow(pa.Table.from_pylist([dict(id=103, amount=Decimal("0.000000000000000001"),
                                           payload=b"", label="Polars😀", rev=0)], schema=schema))
t = t.with_columns((pl.col("label") + pl.lit("→ETL")).alias("label"))
e = engine()
try:
    t.write_database("lake_demo", e, if_table_exists="append", engine="sqlalchemy",
                     engine_options={"chunksize":31, "dtype":{"amount":mysql.DECIMAL(38,18),
                       "payload":mysql.VARBINARY(256), "id":sa.BigInteger(), "rev":sa.BigInteger()}})
finally:
    e.dispose()

Dask:分区不是全局事务

关闭自动字符串转换,避免 Decimal 或 bytes 被转换成字符串。即使 parallel=False,各分区可能在不同事务中提交;不能将一次 to_sql 当成全局回滚边界。下面用 pandas 加载器相同的 frame、types,先把 ID 改为104;读取共用 engine() 的 URL 和连接参数。

import dask
import dask.dataframe as dd
from mo_common import engine, options

dask.config.set({"dataframe.convert-string": False})
frame["id"] = 104
e = engine()
try:
    kw = options()
    args = {k:kw[k] for k in ("charset", "connect_timeout", "read_timeout", "write_timeout")}
    import os
    if os.environ.get("MO_SSL_CA"):
        args.update(ssl={"ca":os.environ["MO_SSL_CA"]}, ssl_verify_cert=True, ssl_verify_identity=True)
    parts = dd.from_pandas(frame, npartitions=2, sort=False)
    parts.to_sql("lake_demo", e.url.render_as_string(hide_password=False),
                 if_exists="append", index=False, chunksize=31, dtype=types,
                 parallel=False, engine_kwargs={"pool_size":2,"max_overflow":0,"connect_args":args})
finally:
    e.dispose()

回读、重放与负载

用新连接回读 ID 101–104,检查 Decimal 的完整字符串、HEX、Unicode 标签和 rev。frame 与 URL 中的秘密不得输出到日志。任务中途失败时,先确认已写入哪些分区;以批次 ID 的暂存表和显式合并恢复,不要再次盲目追加全部分区。

从批大小31、低并行开始,记录实际连接数量,再逐步加压。本轮每工具主计划覆盖5000个场景组合,包含原生转换和显式 SQL 效果;这不表示每种 DataFrame API 原生实现了更新、删除、模式演进或 exactly-once。