2

I am using alembic and when I run alembic upgrade head

It returns: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: database "my_db'" does not exist

My config file has the following url:

sqlalchemy.url = redshift+psycopg2://user:pwd@MY_REDSHIFT_HOSTNAME:5439/my_db'

I modified my run_migrations_online function to allow ssl:

def run_migrations_online():
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""
connectable = engine_from_config(
    config.get_section(config.config_ini_section),
    prefix="sqlalchemy.",
    poolclass=pool.NullPool,
    connect_args={'sslmode': 'prefer'}
)

with connectable.connect() as connection:
    context.configure(
        connection=connection, target_metadata=target_metadata
    )

    with context.begin_transaction():
        context.run_migrations()
mrc
  • 2,845
  • 8
  • 39
  • 73

1 Answers1

2

As explained by @zzzeek in this issue, alembic does not handle the creation of the database. However, not knowing your project structure, I'd say the easiest way to solve your problem would be this:

Add the following code to your base.py file (where you have defined the SQLAlchemy engine and declarative_base):

from sqlalchemy_utils import create_database, database_exists

def validate_database():
    if not database_exists(engine.url):
        create_database(engine.url)

Note that you'll need to install the sqlalchemy_utils package using:

pip install sqlalchemy-utils

Now, in your env.py module, import the newly created validate_database function and call it:

from my_app.db_models.base import validate_database

validate_database()

Hope this solves your problem!

P.S. I've borrowed from this answer as well.

pmsoltani
  • 976
  • 8
  • 13