如何使用SQLAlchemy检查PostgreSQL模式是否存在? [英] How to check if PostgreSQL schema exists using SQLAlchemy?

查看:77
本文介绍了如何使用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;')

这篇关于如何使用SQLAlchemy检查PostgreSQL模式是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆