SQLAlchemy: "create schema if not exists"

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):
    ...

For MS Sql users, there's no has_schema() but this seems to work:

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

You can use the excellent sqlalchemy_utils package to do just that, in a very neat way.

First, install the package:

pip install sqlalchemy_utils

Then use it like this:

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)

The example from the official docs has used PostgreSQL and I have personally used it on MySQL 8.