如何使用SQLAlchemy检查PostgreSQL模式是否存在?

问题描述:

我正在使用SQLAlchemy在PostgreSQL数据库中的特定模式下生成表。如果该架构不存在,我想创建它。我知道PostgreSQL查询来检查架构是否存在:

I am using SQLAlchemy to generate tables in a specific schema in a PostgreSQL database. If the schema does not exist, I want to create it. I know the PostgreSQL query to check for the existence of the schema:

SELECT exists(select schema_name FROM information_schema.schemata WHERE schema_name = 'foo')

但我想知道如何使用SQLAlchemy处理该问题。

but I want to know how I should handle this using SQLAlchemy.

@javax的答案几乎是正确的;以下是一些澄清:

@javax's answer is almost correct; the following is a little clarification:

q = exists(select([("schema_name")]).select_from("information_schema.schemata")
    .where("schema_name = 'foo'"))
if not session.query(q).scalar():
    session.execute('CREATE SCHEMA foo;')