简体   繁体   English

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

[英]How to check if PostgreSQL schema exists using SQLAlchemy?

I am using SQLAlchemy to generate tables in a specific schema in a PostgreSQL database.我正在使用 SQLAlchemy 在 PostgreSQL 数据库中的特定模式中生成表。 If the schema does not exist, I want to create it.如果架构不存在,我想创建它。 I know the PostgreSQL query to check for the existence of the schema:我知道 PostgreSQL 查询来检查模式是否存在:

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

but I want to know how I should handle this using SQLAlchemy.但我想知道我应该如何使用 SQLAlchemy 处理这个问题。

@javax's answer is almost correct; @javax 的回答几乎是正确的; 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;')

If you want to integrate it with SQLAlchemy you could use reflection but for an easier and quicker solution:如果您想将它与 SQLAlchemy 集成,您可以使用反射,但要获得更简单快捷的解决方案:

from sqlalchemy.sql import exists, select
exists(select([("schema_name")]).select_from("information_schema.schemata").
       where("schema_name == 'foo'"))

This will return True or False .这将返回TrueFalse

I've been using this with Postgres, though was surprised to learn that IF NOT EXISTS is not part of the SQL standard -我一直在 Postgres 中使用它,但很惊讶地发现IF NOT EXISTS不是 SQL 标准的一部分 -

engine.execute('CREATE SCHEMA IF NOT EXISTS foo;')

Apparently it's an extension for Postgres and MySQL - https://www.w3resource.com/sql/sql-basic/create-schema.php显然它是 Postgres 和 MySQL 的扩展 - https://www.w3resource.com/sql/sql-basic/create-schema.php

I'm using MySQL and this works for me (with sqlalchemy v1.4.1, python 3.9.1):我正在使用 MySQL,这对我有用(使用 sqlalchemy v1.4.1,python 3.9.1):

import sqlalchemy as sa

engine = sa.create_engine("mysql+pymysql://someuser:somepassword@somehost")
inspector = sa.inspect(engine)
myschema = "someschema"
if myschema in inspector.get_schema_names():
    print(f"{myschema} schema exists")

and if you want to create a schema if it doesn't exist:如果您想创建一个不存在的架构:

if myschema not in inspector.get_schema_names():
    engine.execute(sa.schema.CreateSchema(myschema))
    # optional. set the default schema to the new schema:
    engine.dialect.default_schema_name = myschema

This worked for me.这对我有用。 Finds if a schema exists using pure SqlAlchemy:使用纯 SqlAlchemy 查找模式是否存在:

from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy.schema import CreateSchema, DropSchema
...
engine = create_engine(dbstr)
meta = ModelBase()
...
if not engine.dialect.has_schema(engine, schema=schema_name):
    event.listen(meta.metadata, 'before_create', CreateSchema(schema_name))

meta.metadata.reflect(bind=engine, schema=schema_name)
meta.metadata.create_all(engine, checkfirst=True)

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

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