简体   繁体   English

aiopg + sqlalchemy:如何在没有原始 sql 的情况下“删除表(如果存在)”?

[英]aiopg + sqlalchemy: how to "drop table if exists" without raw sql?

I am looking at examples of aiopg usage with sqlalchemy and these lines scare me:我正在查看使用 sqlalchemy 的 aiopg 使用示例,这些行吓到我了:

async def create_table(conn):
    await conn.execute('DROP TABLE IF EXISTS tbl')
    await conn.execute(CreateTable(tbl))

I do not want to execute raw sql queries when using sqlalchemy.我不想在使用 sqlalchemy 时执行原始 sql 查询。 However I can't find any other way to implement the same logic.但是我找不到任何其他方法来实现相同的逻辑。 My attempts were:我的尝试是:

1) 1)

await conn.execute(tbl.drop(checkfirst=True))

This raises:这提出了:

sqlalchemy.exc.UnboundExecutionError: Table object 'tbl' is not bound to an Engine or Connection. sqlalchemy.exc.UnboundExecutionError:表 object 'tbl' 未绑定到引擎或连接。 Execution can not proceed without a database to execute against.如果没有要执行的数据库,则无法继续执行。

Also I can't find a way to bind the table to engine because aiopg doesn't support metadata.create_all我也找不到将表绑定到引擎的方法,因为aiopg 不支持 metadata.create_all

2) 2)

await conn.execute(DropTable(tbl))

This raises:这提出了:

psycopg2.errors.UndefinedTable: table "tbl" does not exist psycopg2.errors.UndefinedTable:表“tbl”不存在

Seems like DropTable construct doesn't support IF EXISTS part in any way.似乎DropTable构造不以任何方式支持IF EXISTS部分。

So, the question is, is there any way to rewrite await conn.execute('DROP TABLE IF EXISTS tbl') statement into something without raw sql when using aiopg + sqlalchemy?所以,问题是,有没有办法在使用 aiopg + sqlalchemy 时将await conn.execute('DROP TABLE IF EXISTS tbl')语句重写为没有原始 sql 的东西?

This question was posted when the latest version was SQLAlchemy 1.3.11.这个问题是在最新版本为 SQLAlchemy 1.3.11 时发布的。

As of SQLAlchemy 1.4.0, DropTable supports if_exists=True .从 SQLAlchemy 1.4.0 开始, DropTable支持if_exists=True

await conn.execute(DropTable(tbl, if_exists=True))

Reference: https://docs.sqlalchemy.org/en/14/core/ddl.html#sqlalchemy.schema.DropTable参考: https://docs.sqlalchemy.org/en/14/core/ddl.html#sqlalchemy.schema.DropTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM