我正在使用alembic
,当我运行alembic升级头
它返回:sqlalchemy.exc.OperationalError:(psycopg2.OperationalError)致命:数据库“my_db”不存在
我的配置文件具有以下网址:
sqlalchemy.url = redshift+psycopg2://user:pwd@MY_REDSHIFT_HOSTNAME:5439/my_db'
我修改了 run_migrations_online
函数以允许 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()
最佳答案
正如 @zzzeek 所解释的在 this issue ,alembic 不处理数据库的创建。但是,由于不知道您的项目结构,我想说解决您的问题的最简单方法是:
将以下代码添加到您的 base.py
文件(您在其中定义了 SQLAlchemy engine
和 declarative_base
):
from sqlalchemy_utils import create_database, database_exists
def validate_database():
if not database_exists(engine.url):
create_database(engine.url)
请注意,您需要使用以下命令安装 sqlalchemy_utils
软件包:
pip install sqlalchemy-utils
现在,在您的 env.py
模块中,导入新创建的 validate_database
函数并调用它:
from my_app.db_models.base import validate_database
validate_database()
希望这能解决您的问题!
附注我借用了this answer也是如此。
关于python-3.x - Alembic 在线模式 FATAL : database does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62832560/