gpt4 book ai didi

SQLAlchemy - 带索引的建表语句

转载 作者:行者123 更新时间:2023-12-01 13:49:16 25 4
gpt4 key购买 nike

我正在尝试使用 postgresqlsqalchemy 生成一个 CREATE TABLE 语句。已正确创建列,但缺少索引。

我错过了什么?

这是我正在使用的代码片段...

    table = Table('test', metadata, 
Column('id', Integer),
Column('booking', Integer, index=True))
create_stmt = CreateTable(cls.table).compile(connection)
print(create_stmt)
# This print CREATE TABLE test ( id INTEGER, booking INTEGER)
# Index on column booking is missing

最佳答案

您需要对表的索引使用 CreateIndex

    from sqlalchemy import Table, MetaData
from sqlalchemy.schema import CreateTable

metadata=MetaData()

table = Table('test', metadata,
Column('id', Integer),
Column('booking', Integer, index=True))


create_stmt = CreateTable(table).compile(session.connection())
print(create_stmt)

CREATE TABLE test (
id INTEGER,
booking INTEGER
)


from sqlalchemy.schema import CreateIndex
for index in table.indexes:
create_stmt2 = CreateIndex(index).compile(session.connection())
print(create_stmt2)

CREATE INDEX ix_test_booking ON test (booking)

老实说,这个解决方案不是那么干净而且有点烦人,但我想知道您是否有任何理由不使用完整的模式创建,比如 Base.metadata.create_all(engine).

希望对您有所帮助。

关于SQLAlchemy - 带索引的建表语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33210117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com