How to check if PostgreSQL schema exists using SQLAlchemy?

后端 未结 4 1252
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 15:07

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 che

相关标签:
4条回答
  • 2021-01-12 15:39

    I've been using this with Postgres, though was surprised to learn that IF NOT EXISTS is not part of the SQL standard -

    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

    0 讨论(0)
  • 2021-01-12 15:46

    This worked for me. Finds if a schema exists using pure 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)
    
    0 讨论(0)
  • 2021-01-12 15:47

    @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;')
    
    0 讨论(0)
  • 2021-01-12 15:56

    If you want to integrate it with SQLAlchemy you could use reflection but for an easier and quicker solution:

    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.

    0 讨论(0)
提交回复
热议问题