如何在sqlalchemy中向表添加自定义的任意选项?

2024-06-01 13:13:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用sqlalchemy的declarative_base创建一个表,并希望添加cockroachdbINTERLEAVE IN PARENT选项:

CREATE TABLE orders (
    customer INT,
    id INT,
    total DECIMAL(20, 5),
    PRIMARY KEY (customer, id),
    CONSTRAINT fk_customer FOREIGN KEY (customer) REFERENCES customers
  ) INTERLEAVE IN PARENT customers (customer);

我怎样才能把它添加到DDL中呢?你知道吗


Tags: keyinidbasesqlalchemy选项createtable
1条回答
网友
1楼 · 发布于 2024-06-01 13:13:22

在cockroachdb方言正式实现之前,您可以自己扩展它来实现所需的选项:

from sqlalchemy import Table, util
from sqlalchemy.schema import CreateTable
from sqlalchemy.ext.compiler import compiles

Table.argument_for("cockroachdb", "interleave_in_parent", None)

@compiles(CreateTable, "cockroachdb")
def compile_create_table(create, compiler, **kw):
    preparer = compiler.preparer
    stmt = compiler.visit_create_table(create, **kw)
    cockroachdb_opts = create.element.dialect_options["cockroachdb"]
    interleave = cockroachdb_opts.get("interleave_in_parent")

    if interleave:
        p_tbl, c_cols = interleave

        parent_tbl = preparer.format_table(p_tbl)
        child_cols = ", ".join([ 
            preparer.quote(c)
            if isinstance(c, util.string_types) else
            preparer.format_column(c)
            for c in c_cols
        ])

        stmt = stmt.rstrip()  # Prettier output, remove newlines
        stmt = f"{stmt} INTERLEAVE IN PARENT {parent_tbl} ({child_cols})\n\n"

    return stmt

然后像这样使用:

class Customer(Base):
    ...

class Order(Base):
    customer = Column(...)
    ...
    __table_args__ = {
        "cockroachdb_interleave_in_parent": (Customer.__table__, [customer])
    }

相关问题 更多 >