Creating tables on Heroku server with FastAPI and SQLModel, Alembic and pgasync

56 Views Asked by At

I have seen simillar question asked here
but that didn answer my issue unfortunately. Im trying to update DATABASE_URL in my db.py file like this

DATABASE_URL = os.environ.get('DATABASE_URL').replace("postgres://", "postgresql+asyncpg://", 1)


# engine = AsyncEngine(create_engine(DATABASE_URL, echo=True, future=True))

engine = create_async_engine(DATABASE_URL, echo=True)
if os.environ.get('ENV') != 'PROD':
    DB_NAME = os.environ.get('DB_NAME')
    DB_USER = os.environ.get('DB_USER')
    DB_PASSWORD = os.environ.get('DB_PASSWORD')
    DATABASE_URL = f'postgresql+asyncpg://{DB_USER}:{DB_PASSWORD}@localhost:5432/{DB_NAME}'


async def init_db():
    async with engine.begin() as conn:
        # await conn.run_sync(SQLModel.metadata.drop_all)
        await conn.run_sync(SQLModel.metadata.create_all)


async def get_session() -> AsyncSession:
    async_session = sessionmaker(
        engine, class_=AsyncSession, expire_on_commit=False
    )
    async with async_session() as session:
        yield session

also in my migrations/env.py file

i have it pointed like this and also at this point im duplicating code


DB_NAME = os.environ.get('DB_NAME')
DB_USER = os.environ.get('DB_USER')
DB_PASSWORD = os.environ.get('DB_PASSWORD')
DATABASE_URL = f'postgresql+asyncpg://{DB_USER}:{DB_PASSWORD}@localhost:5432/{DB_NAME}'

if os.environ.get('ENV') == 'PROD':
    DATABASE_URL = os.environ.get('DATABASE_URL')

config.set_main_option('sqlalchemy.url', DATABASE_URL)

and when im deploying to heroku and trying to run a basic select query it throws an exception

sqlalchemy.exc.ProgrammingError: (sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError) <class 'asyncpg.exceptions.UndefinedTableError'>: relation "customers" does not exist

which means the tables were not created and moreover running heroku pg:psql and then running \dt command shows that tables were not created.

0

There are 0 best solutions below