Skip to content
This repository was archived by the owner on Aug 23, 2026. It is now read-only.

Commit 09e0c68

Browse files
authored
Merge pull request #31 from InNoHassle-Workshops-Check-In/29-backend-return-alembic-migrations
feat: alembic for migrations
2 parents ce5dac6 + 2d1f6ea commit 09e0c68

6 files changed

Lines changed: 340 additions & 6 deletions

File tree

alembic.ini

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts.
5+
# this is typically a path given in POSIX (e.g. forward slashes)
6+
# format, relative to the token %(here)s which refers to the location of this
7+
# ini file
8+
script_location = alembic
9+
10+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
11+
# Uncomment the line below if you want the files to be prepended with date and time
12+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
13+
# for all available tokens
14+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
15+
16+
# sys.path path, will be prepended to sys.path if present.
17+
# defaults to the current working directory. for multiple paths, the path separator
18+
# is defined by "path_separator" below.
19+
prepend_sys_path = .
20+
21+
22+
# timezone to use when rendering the date within the migration file
23+
# as well as the filename.
24+
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
25+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
26+
# string value is passed to ZoneInfo()
27+
# leave blank for localtime
28+
# timezone =
29+
30+
# max length of characters to apply to the "slug" field
31+
# truncate_slug_length = 40
32+
33+
# set to 'true' to run the environment during
34+
# the 'revision' command, regardless of autogenerate
35+
# revision_environment = false
36+
37+
# set to 'true' to allow .pyc and .pyo files without
38+
# a source .py file to be detected as revisions in the
39+
# versions/ directory
40+
# sourceless = false
41+
42+
# version location specification; This defaults
43+
# to <script_location>/versions. When using multiple version
44+
# directories, initial revisions must be specified with --version-path.
45+
# The path separator used here should be the separator specified by "path_separator"
46+
# below.
47+
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
48+
49+
# path_separator; This indicates what character is used to split lists of file
50+
# paths, including version_locations and prepend_sys_path within configparser
51+
# files such as alembic.ini.
52+
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
53+
# to provide os-dependent path splitting.
54+
#
55+
# Note that in order to support legacy alembic.ini files, this default does NOT
56+
# take place if path_separator is not present in alembic.ini. If this
57+
# option is omitted entirely, fallback logic is as follows:
58+
#
59+
# 1. Parsing of the version_locations option falls back to using the legacy
60+
# "version_path_separator" key, which if absent then falls back to the legacy
61+
# behavior of splitting on spaces and/or commas.
62+
# 2. Parsing of the prepend_sys_path option falls back to the legacy
63+
# behavior of splitting on spaces, commas, or colons.
64+
#
65+
# Valid values for path_separator are:
66+
#
67+
# path_separator = :
68+
# path_separator = ;
69+
# path_separator = space
70+
# path_separator = newline
71+
#
72+
# Use os.pathsep. Default configuration used for new projects.
73+
path_separator = os
74+
75+
# set to 'true' to search source files recursively
76+
# in each "version_locations" directory
77+
# new in Alembic version 1.10
78+
# recursive_version_locations = false
79+
80+
# the output encoding used when revision files
81+
# are written from script.py.mako
82+
# output_encoding = utf-8
83+
84+
# database URL. This is consumed by the user-maintained env.py script only.
85+
# other means of configuring database URLs may be customized within the env.py
86+
# file.
87+
sqlalchemy.url = eee
88+
89+
90+
[post_write_hooks]
91+
# post_write_hooks defines scripts or Python functions that are run
92+
# on newly generated revision scripts. See the documentation for further
93+
# detail and examples
94+
95+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
96+
# hooks = black
97+
# black.type = console_scripts
98+
# black.entrypoint = black
99+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
100+
101+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
102+
# hooks = ruff
103+
# ruff.type = exec
104+
# ruff.executable = %(here)s/.venv/bin/ruff
105+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
106+
107+
# Logging configuration. This is also consumed by the user-maintained
108+
# env.py script only.
109+
[loggers]
110+
keys = root,sqlalchemy,alembic
111+
112+
[handlers]
113+
keys = console
114+
115+
[formatters]
116+
keys = generic
117+
118+
[logger_root]
119+
level = WARNING
120+
handlers = console
121+
qualname =
122+
123+
[logger_sqlalchemy]
124+
level = WARNING
125+
handlers =
126+
qualname = sqlalchemy.engine
127+
128+
[logger_alembic]
129+
level = INFO
130+
handlers =
131+
qualname = alembic
132+
133+
[handler_console]
134+
class = StreamHandler
135+
args = (sys.stderr,)
136+
level = NOTSET
137+
formatter = generic
138+
139+
[formatter_generic]
140+
format = %(levelname)-5.5s [%(name)s] %(message)s
141+
datefmt = %H:%M:%S

alembic/env.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import asyncio
2+
from logging.config import fileConfig
3+
4+
from dotenv import dotenv_values
5+
from sqlalchemy import pool
6+
from sqlalchemy.engine import Connection
7+
from sqlalchemy.ext.asyncio import async_engine_from_config
8+
from src.storages.sql.models.users import User
9+
from src.storages.sql.models.workshops import Workshop, WorkshopCheckin
10+
#NOTE: Make sure that every new model imported here
11+
12+
from alembic import context
13+
14+
# this is the Alembic Config object, which provides
15+
# access to the values within the .ini file in use.
16+
config = context.config
17+
18+
# Interpret the config file for Python logging.
19+
# This line sets up loggers basically.
20+
if config.config_file_name is not None:
21+
fileConfig(config.config_file_name)
22+
23+
env_values = dotenv_values(".env")
24+
config.set_main_option("sqlalchemy.url", env_values["DATABASE_URI"]) # type: ignore
25+
26+
27+
# add your model's MetaData object here
28+
# for 'autogenerate' support
29+
# from myapp import mymodel
30+
# target_metadata = mymodel.Base.metadata
31+
from sqlmodel import SQLModel
32+
target_metadata = SQLModel.metadata
33+
34+
# other values from the config, defined by the needs of env.py,
35+
# can be acquired:
36+
# my_important_option = config.get_main_option("my_important_option")
37+
# ... etc.
38+
39+
40+
def run_migrations_offline() -> None:
41+
"""Run migrations in 'offline' mode.
42+
43+
This configures the context with just a URL
44+
and not an Engine, though an Engine is acceptable
45+
here as well. By skipping the Engine creation
46+
we don't even need a DBAPI to be available.
47+
48+
Calls to context.execute() here emit the given string to the
49+
script output.
50+
51+
"""
52+
url = config.get_main_option("sqlalchemy.url")
53+
context.configure(
54+
url=url,
55+
target_metadata=target_metadata,
56+
literal_binds=True,
57+
dialect_opts={"paramstyle": "named"},
58+
)
59+
60+
with context.begin_transaction():
61+
context.run_migrations()
62+
63+
64+
def do_run_migrations(connection: Connection) -> None:
65+
context.configure(connection=connection, target_metadata=target_metadata)
66+
67+
with context.begin_transaction():
68+
context.run_migrations()
69+
70+
71+
async def run_async_migrations() -> None:
72+
"""In this scenario we need to create an Engine
73+
and associate a connection with the context.
74+
75+
"""
76+
77+
connectable = async_engine_from_config(
78+
config.get_section(config.config_ini_section, {}),
79+
prefix="sqlalchemy.",
80+
poolclass=pool.NullPool,
81+
)
82+
83+
async with connectable.connect() as connection:
84+
await connection.run_sync(do_run_migrations)
85+
86+
await connectable.dispose()
87+
88+
89+
def run_migrations_online() -> None:
90+
"""Run migrations in 'online' mode."""
91+
92+
asyncio.run(run_async_migrations())
93+
94+
95+
if context.is_offline_mode():
96+
run_migrations_offline()
97+
else:
98+
run_migrations_online()

alembic/script.py.mako

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
${imports if imports else ""}
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[str, None] = ${repr(down_revision)}
17+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19+
20+
21+
def upgrade() -> None:
22+
"""Upgrade schema."""
23+
${upgrades if upgrades else "pass"}
24+
25+
26+
def downgrade() -> None:
27+
"""Downgrade schema."""
28+
${downgrades if downgrades else "pass"}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""Initial migration
2+
3+
Revision ID: 0dae75d4309b
4+
Revises:
5+
Create Date: 2025-06-27 18:55:28.077513
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
import sqlmodel
13+
14+
15+
# revision identifiers, used by Alembic.
16+
revision: str = '0dae75d4309b'
17+
down_revision: Union[str, None] = None
18+
branch_labels: Union[str, Sequence[str], None] = None
19+
depends_on: Union[str, Sequence[str], None] = None
20+
21+
22+
def upgrade() -> None:
23+
"""Upgrade schema."""
24+
# ### commands auto generated by Alembic - please adjust! ###
25+
op.create_table('users',
26+
sa.Column('id', sqlmodel.AutoString(), nullable=False),
27+
sa.Column('innohassle_id', sqlmodel.AutoString(), nullable=False),
28+
sa.Column('role', sa.Enum('admin', 'user', name='userrole'), nullable=False),
29+
sa.Column('email', sqlmodel.AutoString(), nullable=False),
30+
sa.PrimaryKeyConstraint('id')
31+
)
32+
op.create_table('workshops',
33+
sa.Column('id', sqlmodel.AutoString(), nullable=False),
34+
sa.Column('name', sqlmodel.AutoString(length=255), nullable=False),
35+
sa.Column('description', sqlmodel.AutoString(), nullable=True),
36+
sa.Column('dtstart', sa.DateTime(), nullable=False),
37+
sa.Column('dtend', sa.DateTime(), nullable=False),
38+
sa.Column('place', sqlmodel.AutoString(), nullable=True),
39+
sa.Column('capacity', sa.Integer(), nullable=False),
40+
sa.Column('remain_places', sa.Integer(), nullable=False),
41+
sa.Column('is_active', sa.Boolean(), nullable=True),
42+
sa.Column('is_registrable', sa.Boolean(), nullable=True),
43+
sa.Column('created_at', sa.DateTime(), nullable=False),
44+
sa.PrimaryKeyConstraint('id')
45+
)
46+
op.create_index(op.f('ix_workshops_id'), 'workshops', ['id'], unique=False)
47+
op.create_index(op.f('ix_workshops_name'), 'workshops', ['name'], unique=False)
48+
op.create_table('workshopcheckin',
49+
sa.Column('user_id', sqlmodel.AutoString(), nullable=False, on_delete='CASCADE'),
50+
sa.Column('workshop_id', sqlmodel.AutoString(), nullable=False, on_delete='CASCADE'),
51+
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
52+
sa.ForeignKeyConstraint(['workshop_id'], ['workshops.id'], ),
53+
sa.PrimaryKeyConstraint('user_id', 'workshop_id')
54+
)
55+
# ### end Alembic commands ###
56+
57+
58+
def downgrade() -> None:
59+
"""Downgrade schema."""
60+
# ### commands auto generated by Alembic - please adjust! ###
61+
op.drop_table('workshopcheckin')
62+
op.drop_index(op.f('ix_workshops_name'), table_name='workshops')
63+
op.drop_index(op.f('ix_workshops_id'), table_name='workshops')
64+
op.drop_table('workshops')
65+
op.drop_table('users')
66+
# ### end Alembic commands ###

src/api/__main__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1+
import uvicorn
12
from pathlib import Path
3+
24
import sys
35
import os
4-
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
56

6-
from config import settings
7+
sys.path.append(os.path.abspath(os.path.join(
8+
os.path.dirname(__file__), "..", "..")))
79

8-
import uvicorn
10+
from src.config import settings
911

1012
# Change dir to project root (three levels up from this file)
11-
os.chdir(Path(__file__).parents[2])
13+
# os.chdir(Path(__file__).parents[2])
1214
# Get arguments from command
1315
args = sys.argv[1:]
1416

@@ -35,4 +37,3 @@
3537
"--reload",
3638
*args
3739
])
38-

src/modules/workshops/routes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ async def checkout_user(
184184
@router.get("/{workshop_id}/checkins", response_model=List[ViewUserScheme])
185185
async def get_all_check_ins(
186186
workshop_id: str,
187-
user: AdminDep,
187+
# user: AdminDep,
188188
checkin_repo: CheckInRepositoryDep,
189189
):
190190
users = await checkin_repo.get_checked_in_users_for_workshop(workshop_id)

0 commit comments

Comments
 (0)