繁体   English   中英

SQLAlchemy:“如果不存在则创建架构”

[英]SQLAlchemy: "create schema if not exists"

我想在 SQLAlchemy 中执行“CREATE SCHEMA IF NOT EXISTS”查询。 有没有比这更好的方法:

    engine = sqlalchemy.create_engine(connstr)

    schema_name = config.get_config_value('db', 'schema_name')

    #Create schema; if it already exists, skip this
    try:
        engine.execute(CreateSchema(schema_name))
    except sqlalchemy.exc.ProgrammingError:
        pass

我正在使用 Python 3.5。

我有同样的问题,我找到的答案是:

if not engine.dialect.has_schema(engine, schema_name):
    engine.execute(sqlalchemy.schema.CreateSchema(schema_name))

我们也可以在没有引擎实例的情况下检查模式,但使用连接

conn = engine.connect()
if conn.dialect.has_schema(conn, schema_name):
    ...

对于 MS Sql 用户,没有has_schema()但这似乎有效:

if schemaname not in conn.dialect.get_schema_names(conn):
   conn.execute(schema.CreateSchema(schemaname))

您可以使用出色的sqlalchemy_utils包以非常简洁的方式做到这一点。

首先,安装软件包:

pip install sqlalchemy_utils

然后像这样使用它:

from sqlalchemy_utils.functions import database_exists, create_database

engin_uri = 'postgres://postgres@localhost/name'

if not database_exists(engin_uri):
    create_database(engin_uri)

官方文档中的示例使用了 PostgreSQL,我个人在 MySQL 8 上使用过它。

我完成这项任务的首选方式:

from sqlalchemy import inspect
<You might need a few more SQLAlchemy imports

def setup_schemas(engine, metadata):
    inspector = inspect(engine)
    all_schemas = inspector.get_schema_names()
    for schema in metadata._schemas:
        if schema not in all_schemas:
            _create_schema(engine, schema)
    
def _create_schema(engine, schema) -> None:
    stmt = text(f"CREATE SCHEMA {schema}")
    with engine.connect() as conn:
        conn.execute(stmt)
        conn.commit()

暂无
暂无

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

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