Added Alembic for migrations

This commit is contained in:
Donkie
2023-05-27 23:14:06 +02:00
parent adda3e6f25
commit de1bf05922
14 changed files with 346 additions and 47 deletions

1
migrations/README Normal file
View File

@@ -0,0 +1 @@
Generic single-database configuration with an async dbapi.

1
migrations/__init__.py Normal file
View File

@@ -0,0 +1 @@
"""Database migrations system."""

68
migrations/env.py Normal file
View File

@@ -0,0 +1,68 @@
"""Alembic environment file."""
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy.engine import Connection
from spoolman.database.database import Database, get_connection_url
from spoolman.database.models import Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
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.
"""
context.configure(
url=get_connection_url(),
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
"""Run migrations in 'online' mode."""
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine and associate a connection with the context."""
db = Database(get_connection_url())
db.connect()
if db.engine is None:
raise RuntimeError("Engine not created.")
async with db.engine.connect() as connection:
await connection.run_sync(do_run_migrations)
await db.engine.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_async_migrations())

25
migrations/script.py.mako Normal file
View File

@@ -0,0 +1,25 @@
"""${message}-
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
import sqlalchemy as sa
from alembic import op
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
"""Perform the upgrade."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Perform the downgrade."""
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,83 @@
"""initial.
Revision ID: 684d32cf7e4d
Create Date: 2023-05-27 21:46:24.361353
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = "684d32cf7e4d"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
"""Perform the upgrade."""
conn = op.get_bind()
inspector = Inspector.from_engine(conn) # type: ignore[arg-type]
tables = inspector.get_table_names()
if "vendor" in tables:
# If the vendor table exists, we assume that the initial migration has already been performed.
return
op.create_table(
"vendor",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("registered", sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.Column("name", sa.String(length=64), nullable=False),
sa.Column("comment", sa.String(length=1024), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_vendor_id"), "vendor", ["id"], unique=False)
op.create_table(
"filament",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("registered", sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.Column("name", sa.String(length=64), nullable=True),
sa.Column("vendor_id", sa.Integer(), nullable=True),
sa.Column("material", sa.String(length=64), nullable=True),
sa.Column("price", sa.Float(), nullable=True),
sa.Column("density", sa.Float(), nullable=False),
sa.Column("diameter", sa.Float(), nullable=False),
sa.Column("weight", sa.Float(), nullable=True, comment="The filament weight of a full spool (net weight)."),
sa.Column("spool_weight", sa.Float(), nullable=True, comment="The weight of an empty spool."),
sa.Column("article_number", sa.String(length=64), nullable=True),
sa.Column("comment", sa.String(length=1024), nullable=True),
sa.ForeignKeyConstraint(
["vendor_id"],
["vendor.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_filament_id"), "filament", ["id"], unique=False)
op.create_table(
"spool",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("registered", sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.Column("first_used", sa.DateTime(), nullable=True),
sa.Column("last_used", sa.DateTime(), nullable=True),
sa.Column("filament_id", sa.Integer(), nullable=False),
sa.Column("used_weight", sa.Float(), nullable=False),
sa.Column("location", sa.String(length=64), nullable=True),
sa.Column("lot_nr", sa.String(length=64), nullable=True),
sa.Column("comment", sa.String(length=1024), nullable=True),
sa.ForeignKeyConstraint(
["filament_id"],
["filament.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_spool_id"), "spool", ["id"], unique=False)
def downgrade() -> None:
"""Perform the downgrade."""
op.drop_index(op.f("ix_spool_id"), table_name="spool")
op.drop_table("spool")
op.drop_index(op.f("ix_filament_id"), table_name="filament")
op.drop_table("filament")
op.drop_index(op.f("ix_vendor_id"), table_name="vendor")
op.drop_table("vendor")

View File

@@ -0,0 +1 @@
"""Database migration versions."""