I'm using alembic and sqlalchemy.
if you want to alembic automatic create your db if not exists, you can edit alembic/env.py and add a method that check if db exists:
from sqlalchemy import create_engine, exc
def create_db_if_not_exists():
# create database if not exists
db_uri = os.getenv('SQLALCHEMY_DATABASE_URI')
database = db_uri.split('/')[-1]
db_postgres = "/".join(db_uri.split('/')[0:-1])+"/postgres"
try:
engine = create_engine(db_uri)
# Attempt to connect to the database
with engine.connect() as conn:
print(f'Database {database} already exists.')
except exc.OperationalError:
#raise Exception
print(f'Database {database} does not exist. Creating now.')
engine = create_engine(db_postgres) #using postgres db to connect
## Attempt to connect to the database
with engine.connect() as conn:
conn.execute("commit")
conn.execute(f'CREATE DATABASE {database};')
then call it before execute migration:
def run_migrations_online() -> None:
create_db_if_not_exists()
...