Skip to content

Commit d773ad6

Browse files
committed
feat: implement database migration system with Alembic
- Added Alembic configuration and migration scripts to facilitate database schema changes. - Implemented a run_migrations function to execute migrations during application startup. - Created migration scripts to transfer data from the old public schema to the new pad_ws schema, ensuring data integrity and consistency. - Updated requirements.txt to include Alembic as a dependency for migration management.
1 parent d9620cc commit d773ad6

File tree

7 files changed

+496
-2
lines changed

7 files changed

+496
-2
lines changed

src/backend/database/alembic.ini

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

src/backend/database/database.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,17 @@
33
"""
44

55
import os
6+
import asyncio
67
from typing import AsyncGenerator
78
from urllib.parse import quote_plus as urlquote
9+
from pathlib import Path
810

911
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
1012
from sqlalchemy.orm import sessionmaker
1113
from sqlalchemy.schema import CreateSchema
1214
from fastapi import Depends
15+
from alembic.config import Config
16+
from alembic import command
1317

1418
from .models import Base, SCHEMA_NAME
1519

@@ -35,8 +39,41 @@
3539
engine, class_=AsyncSession, expire_on_commit=False
3640
)
3741

42+
async def run_migrations() -> None:
43+
"""Run database migrations using Alembic"""
44+
# Get the path to the alembic.ini file
45+
alembic_ini_path = Path(__file__).parent / "alembic.ini"
46+
47+
# Create Alembic configuration
48+
alembic_cfg = Config(str(alembic_ini_path))
49+
50+
# Set the script_location to the correct path
51+
# This ensures Alembic finds the migrations directory
52+
alembic_cfg.set_main_option('script_location', str(Path(__file__).parent / "migrations"))
53+
54+
# Define a function to run in a separate thread
55+
def run_upgrade():
56+
# Import the command module here to avoid import issues
57+
from alembic import command
58+
59+
# Set attributes that env.py might need
60+
import sys
61+
from pathlib import Path
62+
63+
# Add the database directory to sys.path
64+
db_dir = Path(__file__).parent
65+
if str(db_dir) not in sys.path:
66+
sys.path.insert(0, str(db_dir))
67+
68+
# Run the upgrade command
69+
command.upgrade(alembic_cfg, "head")
70+
71+
# Run the migrations in a separate thread to avoid blocking the event loop
72+
await asyncio.to_thread(run_upgrade)
73+
3874
async def init_db() -> None:
3975
"""Initialize the database with required tables"""
76+
# Create schema and tables
4077
async with engine.begin() as conn:
4178
await conn.execute(CreateSchema(SCHEMA_NAME, if_not_exists=True))
4279
await conn.run_sync(Base.metadata.create_all)
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
from logging.config import fileConfig
2+
import os
3+
import sys
4+
from pathlib import Path
5+
6+
from sqlalchemy import engine_from_config
7+
from sqlalchemy import pool
8+
from sqlalchemy.engine import URL
9+
10+
from alembic import context
11+
from dotenv import load_dotenv
12+
13+
# Add the parent directory to sys.path
14+
sys.path.append(str(Path(__file__).parent.parent.parent.parent))
15+
16+
# Load environment variables from .env file
17+
load_dotenv()
18+
19+
# this is the Alembic Config object, which provides
20+
# access to the values within the .ini file in use.
21+
config = context.config
22+
23+
# Interpret the config file for Python logging.
24+
# This line sets up loggers basically.
25+
if config.config_file_name is not None:
26+
fileConfig(config.config_file_name)
27+
28+
# Import the Base metadata from the models
29+
# We need to handle imports differently to avoid module not found errors
30+
import importlib.util
31+
import os
32+
33+
# Get the absolute path to the models module
34+
models_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "models", "__init__.py")
35+
36+
# Load the module dynamically
37+
spec = importlib.util.spec_from_file_location("models", models_path)
38+
models = importlib.util.module_from_spec(spec)
39+
spec.loader.exec_module(models)
40+
41+
# Get Base and SCHEMA_NAME from the loaded module
42+
Base = models.Base
43+
SCHEMA_NAME = models.SCHEMA_NAME
44+
target_metadata = Base.metadata
45+
46+
# other values from the config, defined by the needs of env.py,
47+
# can be acquired:
48+
# my_important_option = config.get_main_option("my_important_option")
49+
# ... etc.
50+
51+
52+
# Get database connection details from environment variables
53+
DB_USER = os.getenv('POSTGRES_USER', 'postgres')
54+
DB_PASSWORD = os.getenv('POSTGRES_PASSWORD', 'postgres')
55+
DB_NAME = os.getenv('POSTGRES_DB', 'pad')
56+
DB_HOST = os.getenv('POSTGRES_HOST', 'localhost')
57+
DB_PORT = os.getenv('POSTGRES_PORT', '5432')
58+
59+
# Override sqlalchemy.url in alembic.ini
60+
config.set_main_option('sqlalchemy.url', f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}")
61+
62+
def run_migrations_offline() -> None:
63+
"""Run migrations in 'offline' mode."""
64+
url = config.get_main_option("sqlalchemy.url")
65+
context.configure(
66+
url=url,
67+
target_metadata=target_metadata,
68+
literal_binds=True,
69+
dialect_opts={"paramstyle": "named"},
70+
include_schemas=True,
71+
version_table_schema=SCHEMA_NAME,
72+
)
73+
74+
with context.begin_transaction():
75+
context.run_migrations()
76+
77+
78+
def run_migrations_online() -> None:
79+
"""Run migrations in 'online' mode.
80+
81+
In this scenario we need to create an Engine
82+
and associate a connection with the context.
83+
84+
"""
85+
connectable = engine_from_config(
86+
config.get_section(config.config_ini_section, {}),
87+
prefix="sqlalchemy.",
88+
poolclass=pool.NullPool,
89+
)
90+
91+
with connectable.connect() as connection:
92+
context.configure(
93+
connection=connection,
94+
target_metadata=target_metadata,
95+
include_schemas=True,
96+
version_table_schema=SCHEMA_NAME
97+
)
98+
99+
with context.begin_transaction():
100+
context.run_migrations()
101+
102+
103+
if context.is_offline_mode():
104+
run_migrations_offline()
105+
else:
106+
run_migrations_online()
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"}

0 commit comments

Comments
 (0)