Add alembic to manage data migrations

This commit is contained in:
Nick Touran 2026-01-05 12:05:32 -05:00
parent 8c73123862
commit e69b80b52c
6 changed files with 466 additions and 0 deletions

1
alembic/README Normal file
View file

@ -0,0 +1 @@
pyproject configuration, based on the generic configuration.

80
alembic/env.py Normal file
View file

@ -0,0 +1,80 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from sqlmodel import SQLModel
from alembic import context
from nrsk.db import get_engine
from nrsk.models import Document, User
# 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
# allow autogeneration of models
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.
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,
# )
connectable = get_engine()
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()

29
alembic/script.py.mako Normal file
View file

@ -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"}

View file

@ -0,0 +1,192 @@
"""initial_setup
Revision ID: 3791144a7ad2
Revises:
Create Date: 2026-01-05 10:24:53.993818
"""
from typing import Sequence, Union
import sqlalchemy as sa
import sqlmodel
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "3791144a7ad2"
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(
"informationtype",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("abbrev", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("examples", sa.JSON(), nullable=True),
sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("retention", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("record", sa.Boolean(), nullable=False),
sa.Column("use_cases", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("notes", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("parent_id", sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
["parent_id"],
["informationtype.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"organization",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("abbreviation", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("website", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("is_active", sa.Boolean(), nullable=False),
sa.Column("parent_id", sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
["parent_id"],
["organization.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_organization_abbreviation"),
"organization",
["abbreviation"],
unique=False,
)
op.create_index(
op.f("ix_organization_name"), "organization", ["name"], unique=False
)
op.create_table(
"user",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("given_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("family_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("preferred_name", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("previous_name", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("joined_on", sa.DateTime(), nullable=True),
sa.Column("deactivated_on", sa.DateTime(), nullable=True),
sa.Column("organization", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("title", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"document",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("number", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("title", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("revision", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("originating_organization_id", sa.Integer(), nullable=True),
sa.Column(
"originator_number", sqlmodel.sql.sqltypes.AutoString(), nullable=True
),
sa.Column(
"originator_revision", sqlmodel.sql.sqltypes.AutoString(), nullable=True
),
sa.Column("type_id", sa.Integer(), nullable=False),
sa.Column(
"revision_comment", sqlmodel.sql.sqltypes.AutoString(), nullable=True
),
sa.Column(
"status",
sa.Enum(
"RESERVED",
"IN_PROGRESS",
"IN_REVIEW",
"REJECTED",
"AUTHORIZED",
"REFERENCE",
"NATIVE",
"APPROVED",
"QUARANTINED",
"SUPERSEDED",
"REVISED",
"VOIDED",
"CLOSED",
name="status",
),
nullable=False,
),
sa.Column(
"usage",
sa.Enum(
"FOR_INFORMATION",
"FOR_STAGE_APPROVAL",
"FOR_BID",
"FOR_CONSTRUCTION",
"FOR_OPERATION",
"AS_BUILT",
name="usage",
),
nullable=False,
),
sa.Column(
"retention_plan", sa.Enum("LIFETIME", name="retention"), nullable=False
),
sa.Column(
"restriction_codes", sqlmodel.sql.sqltypes.AutoString(), nullable=False
),
sa.Column("actual_reviewed_date", sa.DateTime(), nullable=True),
sa.Column("actual_approved_date", sa.DateTime(), nullable=True),
sa.Column(
"filenames", sa.JSON(), server_default=sa.text("'[]'"), nullable=False
),
sa.Column(
"file_notes", sa.JSON(), server_default=sa.text("'[]'"), nullable=False
),
sa.Column(
"checksums", sa.JSON(), server_default=sa.text("'[]'"), nullable=False
),
sa.Column(
"physical_location", sqlmodel.sql.sqltypes.AutoString(), nullable=True
),
sa.Column("notes", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.ForeignKeyConstraint(
["originating_organization_id"],
["organization.id"],
),
sa.ForeignKeyConstraint(
["type_id"],
["informationtype.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"documentuserlink",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("position", sa.Integer(), nullable=False),
sa.Column("role_note", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("document_id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["document_id"],
["document.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["user.id"],
),
sa.PrimaryKeyConstraint("id", "document_id", "user_id"),
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("documentuserlink")
op.drop_table("document")
op.drop_table("user")
op.drop_index(op.f("ix_organization_name"), table_name="organization")
op.drop_index(op.f("ix_organization_abbreviation"), table_name="organization")
op.drop_table("organization")
op.drop_table("informationtype")
# ### end Alembic commands ###