首页 > 解决方案 > 如何在 Sqlalchemy 中向 CREATE INDEX 添加自定义(方言)扩展?(sql存储)

问题描述

我有以下声明性 Sqlalchemy 架构:

class Locations(Base):
    __tablename__ = 'locations'
    group = Column(Integer, primary_key=True)
    id = Column(String, primary_key=True)
    shelf = Column(Integer, primary_key=True)
    start = Column(Integer, nullable=False)
    end = Column(Integer, nullable=False)

我想创建以下索引:

CREATE INDEX ixloc ON locations (shelf, "end" DESC) storing (start);

我怎么能添加呢?

存储是 CockroachDB 的 CREATE INDEX 的扩展,它将给定的列存储在索引中以便更快地检索。

我已经尝试过但没有成功:

Index.argument_for("cockroachdb", "storing", None)
Index('ixloc', Locations.shelf, Locations.end.desc(), cockroachdb_storing='start')

标签: pythonsqlsqlalchemycockroachdb

解决方案


根据 Ilja 的回答,解决方案是:

from sqlalchemy import Index
from sqlalchemy.schema import CreateIndex

Index.argument_for("cockroachdb", "storing", None)

@compiles(CreateIndex, "cockroachdb")
def compile_create_index(create, compiler, **kw):
    stmt = compiler.visit_create_index(create, **kw)
    cockroachdb_opts = create.element.dialect_options["cockroachdb"]
    storing = cockroachdb_opts.get("storing")

    if storing:
        child_cols = ", ".join([compiler.preparer.quote(c) for c in storing])
        stmt = stmt.rstrip()
        stmt = f"{stmt} STORING ({child_cols})\n\n"
    return stmt

Index('ixloc', Locations.shelf, Locations.end.desc(), cockroachdb_storing=['start'])

推荐阅读