如何在 Sqlalchemy 中向 CREATE INDEX 添加自定义(方言)扩展? (sql 存储)
How can I add a custom (dialect) extension to CREATE INDEX in Sqlalchemy? (sql storing)
我有以下声明式 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')
根据 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'])
我有以下声明式 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')
根据 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'])