为 SQLAlchemy 提供自定义参数 table

Giving custom arguments to SQLAlchemy table

我想使用 SQLAlchemy declarative_base 中的 CockroachDB 列族。 我想我需要将其添加到 __table_args__,但我不知道如何添加。

问题基本上是:是否可以为从 SQLAlchemy 中创建 TABLE 提供自定义(底层方言不支持)选项?

一种可能是创建自定义编译扩展:

from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import ColumnCollectionConstraint
from sqlalchemy.sql.elements import quoted_name


class Family(ColumnCollectionConstraint):

    def __init__(self, name, *columns, **kwgs):
        name = quoted_name(name, kwgs.pop("quote", None))
        super().__init__(*columns, **kwgs)
        self.name = name


@compiles(Family)
def compile_family(element, ddlcompiler, **kwgs):
    name = ddlcompiler.preparer.quote(element.name)
    columns = ", ".join([
        ddlcompiler.sql_compiler.process(col, include_table=False, **kwgs)
        for col in element.columns
    ])
    return f"FAMILY {name} ({columns})"

扩展如下:

from sqlalchemy import Column, Integer
from sqlalchemy.schema import CreateTable
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Test(Base):
    __tablename__ = 'test'
    id = Column(Integer, primary_key=True)
    x = Column(Integer)
    __table_args__ = (Family('xs', x),)

print(CreateTable(Test.__table__))

输出:

CREATE TABLE test (
        id INTEGER NOT NULL, 
        x INTEGER, 
        PRIMARY KEY (id), 
        FAMILY xs (x)
)