Skip to content

Commit df3c8e7

Browse files
refactor: use one engine for database migrations and bot (#688)
1 parent 7aeb5cd commit df3c8e7

File tree

3 files changed

+19
-9
lines changed

3 files changed

+19
-9
lines changed

monty/__main__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import disnake
99
import redis
1010
import redis.asyncio
11+
from sqlalchemy.ext.asyncio import create_async_engine
1112

1213
from monty import constants, monkey_patches
1314
from monty.bot import Monty
@@ -56,19 +57,24 @@ async def main() -> None:
5657
constants.Client.config_prefix, session=redis_session, prefix=constants.Redis.prefix
5758
)
5859

60+
database_engine = create_async_engine(constants.Database.postgres_bind)
5961
# run alembic migrations
6062
if constants.Database.run_migrations:
6163
log.info(f"Running database migrations to target {constants.Database.migration_target}")
62-
await run_alembic()
64+
await run_alembic(database_engine)
6365
else:
6466
log.info("Skipping database migrations per environment settings.")
67+
# we still need to connect to the database to verify connection info is correct
68+
async with database_engine.connect():
69+
pass
6570

6671
# ping redis
6772
await redis_session.ping()
6873
log.debug("Successfully pinged redis server.")
6974

7075
bot = Monty(
7176
redis_session=redis_session,
77+
database_engine=database_engine,
7278
command_prefix=constants.Client.default_command_prefix,
7379
activity=constants.Client.activity,
7480
allowed_mentions=constants.Client.allowed_mentions,

monty/bot.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import redis.asyncio
1111
import sqlalchemy as sa
1212
from disnake.ext import commands
13-
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
13+
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
1414
from sqlalchemy.orm import selectinload
1515

1616
from monty import constants
@@ -50,7 +50,13 @@ class Monty(commands.Bot):
5050

5151
name = constants.Client.name
5252

53-
def __init__(self, redis_session: redis.asyncio.Redis, proxy: str | None = None, **kwargs) -> None:
53+
def __init__(
54+
self,
55+
redis_session: redis.asyncio.Redis,
56+
database_engine: AsyncEngine,
57+
proxy: str | None = None,
58+
**kwargs,
59+
) -> None:
5460
if TEST_GUILDS:
5561
kwargs["test_guilds"] = TEST_GUILDS
5662
log.warning("registering as test_guilds")
@@ -62,8 +68,8 @@ def __init__(self, redis_session: redis.asyncio.Redis, proxy: str | None = None,
6268

6369
self.create_http_session(proxy=proxy)
6470

65-
self.db_engine = engine = create_async_engine(constants.Database.postgres_bind)
66-
self.db_session = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
71+
self.db_engine = database_engine
72+
self.db_session = async_sessionmaker(database_engine, expire_on_commit=False, class_=AsyncSession)
6773

6874
self.guild_configs: dict[int, GuildConfig] = {}
6975
self.guild_db: dict[int, Guild] = {}
@@ -161,8 +167,6 @@ async def get_prefix(self, message: disnake.Message) -> list[str] | str | None:
161167

162168
async def _create_features(self) -> None:
163169
"""Update the database with all features defined immediately upon launch. No more lazy creation."""
164-
await self.wait_until_first_connect()
165-
166170
async with self._feature_db_lock, self.db.begin() as session:
167171
stmt = sa.select(Feature).options(selectinload(Feature.rollout))
168172
result = await session.scalars(stmt)

monty/migrations.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ async def run_async_upgrade(engine: AsyncEngine) -> None:
2323
await conn.run_sync(run_upgrade, alembic_cfg)
2424

2525

26-
async def run_alembic() -> None:
26+
async def run_alembic(engine: AsyncEngine | None = None) -> None:
2727
"""Run alembic migrations."""
28-
engine = create_async_engine(constants.Database.postgres_bind)
28+
engine = engine or create_async_engine(constants.Database.postgres_bind)
2929
await run_async_upgrade(engine)

0 commit comments

Comments
 (0)