【问题标题】:Giving custom arguments to SQLAlchemy table为 SQLAlchemy 表提供自定义参数
【发布时间】:2019-02-20 10:08:56
【问题描述】:

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

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

【问题讨论】:

    标签: python sqlalchemy cockroachdb


    【解决方案1】:

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

    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)
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 2021-08-10
      • 1970-01-01
      • 2019-09-29
      相关资源
      最近更新 更多