Compare commits

...

2 Commits

Author SHA1 Message Date
stijndcl 37dd5ba3e8 Check current migration on startup 2022-06-11 01:26:19 +02:00
stijndcl 9518bbe168 Add db through docker, configure alembic & fix pylint warning 2022-06-11 01:15:05 +02:00
7 changed files with 154 additions and 13 deletions

1
alembic/README 100644
View File

@ -0,0 +1 @@
Generic single-database configuration.

71
alembic/env.py 100644
View File

@ -0,0 +1,71 @@
import asyncio
from logging.config import fileConfig
from alembic import context
from database.engine import engine
from database.models import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
render_as_batch=True,
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection):
context.configure(connection=connection, target_metadata=target_metadata, render_as_batch=True)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())

View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,26 @@
import logging
from alembic import config, script
from alembic.runtime import migration
from database.engine import engine
async def ensure_latest_migration():
"""Make sure we are currently on the latest revision, otherwise raise an exception"""
alembic_config = config.Config("alembic.ini")
alembic_script = script.ScriptDirectory.from_config(alembic_config)
async with engine.begin() as connection:
current_revision = await connection.run_sync(
lambda sync_connection: migration.MigrationContext.configure(sync_connection).get_current_revision()
)
alembic_head = alembic_script.get_current_head()
if current_revision != alembic_head:
error_message = (
f"Pending migrations (current revision is {current_revision}, while head is at {alembic_head})"
)
logging.error(error_message)
raise RuntimeError(error_message)

View File

@ -1,5 +1,4 @@
import discord
from discord import Message
from discord.ext import commands
from sqlalchemy.ext.asyncio import AsyncSession
@ -15,9 +14,14 @@ class Didier(commands.Bot):
activity = discord.Activity(type=discord.ActivityType.playing, name=settings.DISCORD_STATUS_MESSAGE)
status = discord.Status.online
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents = discord.Intents(
guilds=True,
members=True,
message_content=True,
emojis=True,
messages=True,
reactions=True,
)
super().__init__(
command_prefix=get_prefix, case_insensitive=True, intents=intents, activity=activity, status=status
@ -27,10 +31,3 @@ class Didier(commands.Bot):
def db_session(self) -> AsyncSession:
"""Obtain a database session"""
return DBSession()
async def on_ready(self):
"""Event triggered when the bot is ready"""
print(settings.DISCORD_READY_MESSAGE)
async def on_message(self, message: Message, /) -> None:
print(message.content)

16
docker-compose.yml 100644
View File

@ -0,0 +1,16 @@
version: '3.9'
services:
db:
image: postgres:14
container_name: didier
restart: always
environment:
- POSTGRES_DB=${DB_NAME:-didier_dev}
- POSTGRES_USER=${DB_USERNAME:-postgres}
- POSTGRES_PASSWORD=${DB_PASSWORD:-postgres}
ports:
- "${DB_PORT:-5432}:${DB_PORT:-5432}"
volumes:
- db:/var/lib/postgresql/data
volumes:
db:

10
main.py
View File

@ -4,6 +4,7 @@ from logging.handlers import RotatingFileHandler
import asyncio
import settings
from database.migrations import ensure_latest_migration
from didier import Didier
@ -28,7 +29,12 @@ def setup_logging():
logging.getLogger("discord").setLevel(logging.ERROR)
if __name__ == "__main__":
async def main():
"""Do some setup & checks, and then run the bot"""
setup_logging()
await ensure_latest_migration()
await run_bot()
asyncio.run(run_bot())
if __name__ == "__main__":
asyncio.run(main())