From 4105c3b777e82cb4b6dadf27c109dd21010ad8ce Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Wed, 1 Jul 2026 23:06:39 +0200 Subject: Added db support --- db/__init__.py | 0 db/migrations/README | 1 + db/migrations/env.py | 82 ++++++++++++++++++++++ db/migrations/script.py.mako | 29 ++++++++ .../versions/202607012255-40e20fbf63c9_.py | 35 +++++++++ .../versions/202607012255-6ebaa6ab0f48_.py | 39 ++++++++++ db/models.py | 13 ++++ db/session.py | 21 ++++++ 8 files changed, 220 insertions(+) create mode 100644 db/__init__.py create mode 100644 db/migrations/README create mode 100644 db/migrations/env.py create mode 100644 db/migrations/script.py.mako create mode 100644 db/migrations/versions/202607012255-40e20fbf63c9_.py create mode 100644 db/migrations/versions/202607012255-6ebaa6ab0f48_.py create mode 100644 db/models.py create mode 100644 db/session.py (limited to 'db') diff --git a/db/__init__.py b/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/db/migrations/README b/db/migrations/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/db/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/db/migrations/env.py b/db/migrations/env.py new file mode 100644 index 0000000..f1b3156 --- /dev/null +++ b/db/migrations/env.py @@ -0,0 +1,82 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +from conf import DATABASE_URL +from db.models import * + +# 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) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = SQLModel.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. +config.set_main_option('sqlalchemy.url', DATABASE_URL) + + +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"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +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_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/db/migrations/script.py.mako b/db/migrations/script.py.mako new file mode 100644 index 0000000..697cf67 --- /dev/null +++ b/db/migrations/script.py.mako @@ -0,0 +1,29 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/db/migrations/versions/202607012255-40e20fbf63c9_.py b/db/migrations/versions/202607012255-40e20fbf63c9_.py new file mode 100644 index 0000000..a32131a --- /dev/null +++ b/db/migrations/versions/202607012255-40e20fbf63c9_.py @@ -0,0 +1,35 @@ +"""empty message + +Revision ID: 40e20fbf63c9 +Revises: 6ebaa6ab0f48 +Create Date: 2026-07-01 22:55:55.017591 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel + + +# revision identifiers, used by Alembic. +revision: str = '40e20fbf63c9' +down_revision: Union[str, Sequence[str], None] = '6ebaa6ab0f48' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('user', sa.Column('external_id', sa.Uuid(), nullable=False, server_default=sa.text('gen_random_uuid()'))) + op.create_index(op.f('ix_user_external_id'), 'user', ['external_id'], unique=True) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_user_external_id'), table_name='user') + op.drop_column('user', 'external_id') + # ### end Alembic commands ### diff --git a/db/migrations/versions/202607012255-6ebaa6ab0f48_.py b/db/migrations/versions/202607012255-6ebaa6ab0f48_.py new file mode 100644 index 0000000..9d4daa2 --- /dev/null +++ b/db/migrations/versions/202607012255-6ebaa6ab0f48_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 6ebaa6ab0f48 +Revises: +Create Date: 2026-07-01 22:55:14.146711 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +import sqlmodel + + +# revision identifiers, used by Alembic. +revision: str = '6ebaa6ab0f48' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('user', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('username', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_user_username'), table_name='user') + op.drop_table('user') + # ### end Alembic commands ### diff --git a/db/models.py b/db/models.py new file mode 100644 index 0000000..b66f5bc --- /dev/null +++ b/db/models.py @@ -0,0 +1,13 @@ +from uuid import uuid4, UUID + +from sqlmodel import SQLModel, Field + + +class BaseModel(SQLModel): + id: int | None = Field(primary_key=True, default=None) + +class ExternalModelMixin: + external_id: UUID = Field(index=True, unique=True, default_factory=uuid4) + +class User(BaseModel, ExternalModelMixin, table=True): + username: str = Field(unique=True, index=True) diff --git a/db/session.py b/db/session.py new file mode 100644 index 0000000..4d83649 --- /dev/null +++ b/db/session.py @@ -0,0 +1,21 @@ +from contextlib import contextmanager + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker, scoped_session +from sqlmodel import Session + +from conf import DATABASE_URL +from utils.json import json_serializer + + +engine = create_engine(DATABASE_URL, echo=True, future=True, json_serializer=json_serializer, pool_size=100, pool_recycle=3600) +session_factory = sessionmaker(engine, class_=Session) +ScopedSession = scoped_session(session_factory=session_factory) + +def get_session(): + with ScopedSession() as session: + yield session + +@contextmanager +def get_session_context(): + yield from get_session() -- cgit v1.2.3