Search code examples
pythonsqldatabasepython-3.xsqlalchemy

SQLAlchemy: "create schema if not exists"


I want to do the "CREATE SCHEMA IF NOT EXISTS" query in SQLAlchemy. Is there a better way than this:

    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

I am using Python 3.5.


Solution

  • I had the same question and the answer, which I found, is:

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

    We can also check schema without engine instance, but using connection

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