python - 如何在 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')
解决方案
根据 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'])
推荐阅读
- linux - 如何使用 grep 命令在 html 中的标签之间提取内容
- ios - 如何在 UIImageView 中使用索引颜色空间渲染 CIImage?
- asp.net-core - 如何使用声明式管道顺利运行 Dotnet 运行命令
- excel - 双击自动填充的右下角
- java - Java 二级泛型的奇怪行为
- python - 如何在定义为变量的路径中写入文件?
- python - 如何使用 .striptime() 方法解析日期时间数据?
- swift - 如果从未重新选择,TextField 返回 nil
- rust - dyn 在 rust 中的使用
- flutter - Stack里面如何在渲染键盘后垂直滚动,SingleChildScrollView不工作,FLutter?