feat: add Alembic database migrations

Replace create_all() startup approach with Alembic for proper schema
versioning. Includes initial migration for users and evotor_connections
tables, entrypoint script that runs migrations before starting uvicorn.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
mguschin
2026-03-06 12:26:41 +03:00
parent 865798967a
commit 9edb77efba
10 changed files with 195 additions and 8 deletions

View File

@@ -3,8 +3,6 @@ from fastapi.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
from web.config import settings
from web.database import engine, Base
from web.models import User, EvotorConnection # noqa: F401 — registers models with Base
from web.routes import auth, profile, reset, evotor
app = FastAPI(title="EvoSync — Личный кабинет")
@@ -16,8 +14,3 @@ app.include_router(auth.router)
app.include_router(profile.router)
app.include_router(reset.router)
app.include_router(evotor.router)
@app.on_event("startup")
def on_startup():
Base.metadata.create_all(bind=engine)

1
web/migrations/README Normal file
View File

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

54
web/migrations/env.py Normal file
View File

@@ -0,0 +1,54 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from web.config import settings
from web.database import Base
from web.models import User, EvotorConnection # noqa: F401 — register models with Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
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:
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()

View File

@@ -0,0 +1,26 @@
"""${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
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[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:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,60 @@
"""initial
Revision ID: 2c15000e752b
Revises:
Create Date: 2026-03-06 09:07:16.180639
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '2c15000e752b'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("first_name", sa.String(length=100), nullable=False),
sa.Column("last_name", sa.String(length=100), nullable=False),
sa.Column("email", sa.String(length=255), nullable=False),
sa.Column("phone", sa.String(length=20), nullable=False),
sa.Column("password_hash", sa.String(length=255), nullable=False),
sa.Column("is_email_confirmed", sa.Boolean(), nullable=False),
sa.Column("email_confirm_token", sa.String(length=255), nullable=True),
sa.Column("password_reset_token", sa.String(length=255), nullable=True),
sa.Column("password_reset_expires", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False),
sa.Column("updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)
op.create_index(op.f("ix_users_phone"), "users", ["phone"], unique=True)
op.create_table(
"evotor_connections",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("access_token", sa.Text(), nullable=False),
sa.Column("store_id", sa.String(length=255), nullable=True),
sa.Column("store_name", sa.String(length=255), nullable=True),
sa.Column("connected_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False),
sa.Column("updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("user_id"),
)
def downgrade() -> None:
op.drop_table("evotor_connections")
op.drop_index(op.f("ix_users_phone"), table_name="users")
op.drop_index(op.f("ix_users_email"), table_name="users")
op.drop_table("users")