Forward the lab 4 foundation and migrate the lab 5 pipeline to SQLAlchemy
This commit is contained in:
+102
@@ -0,0 +1,102 @@
|
||||
import asyncio
|
||||
|
||||
from alembic import context
|
||||
from alembic.script import ScriptDirectory
|
||||
from legacy import adopt_legacy
|
||||
from sqlalchemy import Connection, func, make_url, pool, select
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
AttachmentRow,
|
||||
JobEventRow,
|
||||
JobRow,
|
||||
OutboxRow,
|
||||
VariantRow,
|
||||
)
|
||||
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
|
||||
from messenger.messaging.infrastructure.postgres import (
|
||||
ChatMemberRow,
|
||||
ChatRow,
|
||||
IdempotencyKeyRow,
|
||||
MessageAttachmentRow,
|
||||
MessageRow,
|
||||
)
|
||||
from messenger.shared.config import PlatformSettings
|
||||
|
||||
LOCK_KEY = 20_260_002
|
||||
MODELS = (
|
||||
UserRow,
|
||||
SessionRow,
|
||||
ChatRow,
|
||||
ChatMemberRow,
|
||||
MessageRow,
|
||||
IdempotencyKeyRow,
|
||||
AttachmentRow,
|
||||
JobRow,
|
||||
OutboxRow,
|
||||
JobEventRow,
|
||||
VariantRow,
|
||||
MessageAttachmentRow,
|
||||
)
|
||||
target_metadata = UserRow.metadata
|
||||
config = context.config
|
||||
|
||||
|
||||
def include_object(_obj, name, _type, _reflected, _compare_to):
|
||||
return name != "schema_migrations"
|
||||
|
||||
|
||||
def run_migrations(connection: Connection) -> None:
|
||||
with connection.engine.connect() as lock:
|
||||
lock.execute(select(func.pg_advisory_lock(LOCK_KEY)))
|
||||
lock.commit()
|
||||
try:
|
||||
with connection.begin():
|
||||
adopt_legacy(connection, ScriptDirectory.from_config(config))
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
transaction_per_migration=True,
|
||||
compare_type=True,
|
||||
include_object=include_object,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
finally:
|
||||
lock.execute(select(func.pg_advisory_unlock(LOCK_KEY)))
|
||||
lock.commit()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
dsn = config.attributes.get("database_url")
|
||||
if dsn is None:
|
||||
dsn = PlatformSettings().database_url.get_secret_value()
|
||||
engine = create_async_engine(
|
||||
make_url(dsn).set(drivername="postgresql+asyncpg"),
|
||||
poolclass=pool.NullPool,
|
||||
hide_parameters=True,
|
||||
connect_args={
|
||||
"timeout": 10,
|
||||
"server_settings": {"lock_timeout": "10000", "statement_timeout": "60000"},
|
||||
},
|
||||
)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.run_sync(run_migrations)
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
context.configure(
|
||||
dialect_name="postgresql",
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
transaction_per_migration=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
elif config.attributes.get("connection") is not None:
|
||||
run_migrations(config.attributes["connection"])
|
||||
else:
|
||||
asyncio.run(run_async_migrations())
|
||||
@@ -0,0 +1,94 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from alembic.script import ScriptDirectory
|
||||
from sqlalchemy import Connection, MetaData, Table, func, inspect, select, text
|
||||
from sqlalchemy.schema import CreateSchema
|
||||
|
||||
LEGACY = {
|
||||
"0001_init": "9a13618f078ae9056431391e2e5197a31b981ae1fff047a9b3421ac750d3fd0d",
|
||||
"0002_idempotency_keys": "d9159a35553249a1e51af5f2e4e7c39b014e97593c49748e13f3799839063dd0",
|
||||
"0003_attachments": "c4417f560538a083efba1c67f660147dc94532fcbb2fa91f3f3e8258a0f01f2e",
|
||||
"0004_jobs": "c3887fa7a886ae8153a216aa43fd4c3c6190a2074e8ce20c3e77f29bfb01550e",
|
||||
"0005_failed_registry": "02b80061a08a6929feb092148c453ad970e3d001901c651b5a73b90b1e40f145",
|
||||
"0006_attachment_quarantine": (
|
||||
"541f5399d87fac3584c4102b4e0bf92c23cd372cc20a7d56dad03e771773202c"
|
||||
),
|
||||
}
|
||||
SNAPSHOT = text("""
|
||||
WITH relations AS (
|
||||
SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = :schema AND c.relkind IN ('r', 'p')
|
||||
AND c.relname NOT IN ('schema_migrations', 'alembic_version')
|
||||
)
|
||||
SELECT 'table' AS kind, c.relname AS name,
|
||||
concat_ws('|', c.relkind, c.relpersistence,
|
||||
c.relrowsecurity, c.relforcerowsecurity) AS definition
|
||||
FROM relations c
|
||||
UNION ALL
|
||||
SELECT 'column', c.relname || '.' || a.attname,
|
||||
concat_ws('|', a.attnum, format_type(a.atttypid, a.atttypmod), a.attnotnull,
|
||||
a.attidentity, a.attgenerated, a.attcollation::regcollation,
|
||||
pg_get_expr(d.adbin, d.adrelid))
|
||||
FROM relations c JOIN pg_attribute a ON a.attrelid = c.oid
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
|
||||
WHERE a.attnum > 0 AND NOT a.attisdropped
|
||||
UNION ALL
|
||||
SELECT 'constraint', c.relname || '.' || k.conname,
|
||||
concat_ws('|', pg_get_constraintdef(k.oid), k.convalidated)
|
||||
FROM relations c JOIN pg_constraint k ON k.conrelid = c.oid
|
||||
UNION ALL
|
||||
SELECT 'index', c.relname || '.' || x.relname,
|
||||
concat_ws('|', pg_get_indexdef(i.indexrelid), i.indisvalid, i.indisready)
|
||||
FROM relations c JOIN pg_index i ON i.indrelid = c.oid
|
||||
JOIN pg_class x ON x.oid = i.indexrelid
|
||||
UNION ALL
|
||||
SELECT 'trigger', c.relname || '.' || t.tgname,
|
||||
concat_ws('|', pg_get_triggerdef(t.oid), t.tgenabled)
|
||||
FROM relations c JOIN pg_trigger t ON t.tgrelid = c.oid WHERE NOT t.tgisinternal
|
||||
ORDER BY kind, name
|
||||
""")
|
||||
|
||||
|
||||
def snapshot(connection: Connection, schema: str) -> list[tuple[str, str, str]]:
|
||||
return [
|
||||
(kind, name, definition.replace(f"{schema}.", ""))
|
||||
for kind, name, definition in connection.execute(SNAPSHOT, {"schema": schema})
|
||||
]
|
||||
|
||||
|
||||
def adopt_legacy(connection: Connection, scripts: ScriptDirectory) -> None:
|
||||
migration = MigrationContext.configure(connection)
|
||||
if migration.get_current_heads():
|
||||
return
|
||||
tables = set(inspect(connection).get_table_names(schema="public"))
|
||||
if tables <= {"alembic_version"}:
|
||||
return
|
||||
if "schema_migrations" not in tables:
|
||||
raise RuntimeError("Existing schema has no legacy migration journal")
|
||||
journal = Table("schema_migrations", MetaData(), schema="public", autoload_with=connection)
|
||||
applied = dict(connection.execute(select(journal.c.version, journal.c.checksum)).tuples().all())
|
||||
expected = dict(list(LEGACY.items())[: len(applied)])
|
||||
if applied != expected:
|
||||
raise RuntimeError("Unknown or changed legacy migrations")
|
||||
if not applied:
|
||||
if tables - {"schema_migrations", "alembic_version"}:
|
||||
raise RuntimeError("Existing schema has an empty migration journal")
|
||||
return
|
||||
revision = list(expected)[-1]
|
||||
actual = snapshot(connection, "public")
|
||||
reference = f"alembic_verify_{uuid4().hex}"
|
||||
savepoint = connection.begin_nested()
|
||||
try:
|
||||
connection.execute(CreateSchema(reference))
|
||||
connection.execute(select(func.set_config("search_path", reference, True)))
|
||||
with Operations.context(MigrationContext.configure(connection)):
|
||||
for script in reversed(list(scripts.walk_revisions(base="base", head=revision))):
|
||||
script.module.upgrade()
|
||||
wanted = snapshot(connection, reference)
|
||||
finally:
|
||||
savepoint.rollback()
|
||||
if actual != wanted:
|
||||
raise RuntimeError("Legacy schema differs from the recorded migrations")
|
||||
migration.stamp(scripts, revision)
|
||||
@@ -0,0 +1,16 @@
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,87 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0001_init"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"users",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("username", sa.Text(), nullable=False),
|
||||
sa.Column("display_name", sa.Text(), nullable=False),
|
||||
sa.Column("password_hash", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("password_hash LIKE '$argon2id$%'", name="users_password_hash_check"),
|
||||
sa.CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="users_username_format"),
|
||||
sa.CheckConstraint(
|
||||
"char_length(display_name) BETWEEN 1 AND 100", name="users_display_name_check"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("username", name="users_username_key"),
|
||||
)
|
||||
op.create_table(
|
||||
"sessions",
|
||||
sa.Column("token_hash", sa.LargeBinary(), nullable=False),
|
||||
sa.Column("user_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("expires_at > created_at", name="sessions_check"),
|
||||
sa.CheckConstraint("octet_length(token_hash) = 32", name="sessions_token_hash_check"),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("token_hash"),
|
||||
)
|
||||
op.create_index("sessions_user_idx", "sessions", ["user_id"], unique=False)
|
||||
op.create_table(
|
||||
"chats",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("title", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("last_message_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="chats_title_check"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_table(
|
||||
"chat_members",
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("user_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("position", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("chat_created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("position BETWEEN 1 AND 100", name="chat_members_position_check"),
|
||||
sa.ForeignKeyConstraint(["chat_id"], ["chats.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"],
|
||||
["users.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("chat_id", "user_id"),
|
||||
)
|
||||
op.create_index(
|
||||
"chat_members_user_idx",
|
||||
"chat_members",
|
||||
["user_id", "chat_created_at", "chat_id"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_table(
|
||||
"messages",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("sender_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("text", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("char_length(text) BETWEEN 1 AND 4000", name="messages_text_check"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id", "sender_id"],
|
||||
["chat_members.chat_id", "chat_members.user_id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(
|
||||
"messages_history_idx", "messages", ["chat_id", "created_at", "id"], unique=False
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete application data")
|
||||
@@ -0,0 +1,33 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0002_idempotency_keys"
|
||||
down_revision = "0001_init"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"idempotency_keys",
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("user_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("key", sa.Text(), nullable=False),
|
||||
sa.Column("fingerprint", sa.LargeBinary(), nullable=False),
|
||||
sa.Column("message_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.CheckConstraint("key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="idempotency_keys_key_check"),
|
||||
sa.CheckConstraint(
|
||||
"octet_length(fingerprint) = 32", name="idempotency_keys_fingerprint_check"
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id", "user_id"],
|
||||
["chat_members.chat_id", "chat_members.user_id"],
|
||||
),
|
||||
sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("chat_id", "user_id", "key"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete application data")
|
||||
@@ -0,0 +1,77 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0003_attachments"
|
||||
down_revision = "0002_idempotency_keys"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_constraint("messages_text_check", "messages", type_="check")
|
||||
op.create_check_constraint("messages_text_check", "messages", "char_length(text) <= 4000")
|
||||
op.create_table(
|
||||
"attachments",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("owner_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("filename", sa.Text(), nullable=False),
|
||||
sa.Column("content_type", sa.Text(), nullable=False),
|
||||
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
|
||||
sa.Column("sha256", sa.Text(), nullable=False),
|
||||
sa.Column("width", sa.Integer(), nullable=False),
|
||||
sa.Column("height", sa.Integer(), nullable=False),
|
||||
sa.Column("object_key", sa.Text(collation="C"), nullable=False),
|
||||
sa.Column("status", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("object_key", name="attachments_object_key_key"),
|
||||
sa.UniqueConstraint("id", "chat_id", name="attachments_chat_key"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id", "owner_id"],
|
||||
["chat_members.chat_id", "chat_members.user_id"],
|
||||
name="attachments_owner_fkey",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"char_length(filename) BETWEEN 1 AND 255", name="attachments_filename_check"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"content_type IN ('image/png', 'image/jpeg')", name="attachments_content_type_check"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"size_bytes BETWEEN 1 AND 10485760", name="attachments_size_bytes_check"
|
||||
),
|
||||
sa.CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="attachments_sha256_check"),
|
||||
sa.CheckConstraint("width > 0", name="attachments_width_check"),
|
||||
sa.CheckConstraint("height > 0", name="attachments_height_check"),
|
||||
sa.CheckConstraint("status IN ('pending', 'ready')", name="attachments_status_check"),
|
||||
)
|
||||
op.create_index(
|
||||
"attachments_pending_idx",
|
||||
"attachments",
|
||||
["created_at"],
|
||||
postgresql_where=sa.text("status = 'pending'"),
|
||||
)
|
||||
op.create_table(
|
||||
"message_attachments",
|
||||
sa.Column("message_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("position", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("chat_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("attachment_id", sa.Uuid(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("message_id", "position"),
|
||||
sa.UniqueConstraint("message_id", "attachment_id"),
|
||||
sa.CheckConstraint("position BETWEEN 0 AND 9", name="message_attachments_position_check"),
|
||||
sa.ForeignKeyConstraint(["message_id"], ["messages.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(
|
||||
["attachment_id", "chat_id"],
|
||||
["attachments.id", "attachments.chat_id"],
|
||||
name="message_attachments_attachment_fkey",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
)
|
||||
op.create_index("message_attachments_attachment_idx", "message_attachments", ["attachment_id"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete application data")
|
||||
@@ -0,0 +1,146 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision = "0004_jobs"
|
||||
down_revision = "0003_attachments"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_constraint("attachments_status_check", "attachments", type_="check")
|
||||
op.create_check_constraint(
|
||||
"attachments_status_check",
|
||||
"attachments",
|
||||
"status IN ('pending', 'queued', 'processing', 'ready', 'failed')",
|
||||
)
|
||||
for name in ("staging_key", "original_key"):
|
||||
op.add_column("attachments", sa.Column(name, sa.Text(collation="C"), nullable=True))
|
||||
op.create_unique_constraint(f"attachments_{name}_key", "attachments", [name])
|
||||
op.add_column(
|
||||
"attachments",
|
||||
sa.Column("published_version", sa.Integer(), nullable=False, server_default="0"),
|
||||
)
|
||||
op.create_check_constraint(
|
||||
"attachments_published_version_check", "attachments", "published_version >= 0"
|
||||
)
|
||||
op.add_column("attachments", sa.Column("error_code", sa.Text(), nullable=True))
|
||||
op.create_check_constraint(
|
||||
"attachments_error_code_check",
|
||||
"attachments",
|
||||
"error_code IN ('invalid_image', 'processing_failed', 'retry_exhausted')",
|
||||
)
|
||||
op.alter_column("attachments", "object_key", nullable=True)
|
||||
attachments = sa.table(
|
||||
"attachments",
|
||||
sa.column("status"),
|
||||
sa.column("object_key"),
|
||||
sa.column("original_key"),
|
||||
sa.column("staging_key"),
|
||||
sa.column("published_version"),
|
||||
)
|
||||
op.execute(
|
||||
attachments.update()
|
||||
.where(attachments.c.status == "ready")
|
||||
.values(original_key=attachments.c.object_key, published_version=1)
|
||||
)
|
||||
op.execute(
|
||||
attachments.update()
|
||||
.where(attachments.c.status == "pending")
|
||||
.values(staging_key=attachments.c.object_key)
|
||||
)
|
||||
op.create_index(
|
||||
"attachments_staged_idx",
|
||||
"attachments",
|
||||
["updated_at"],
|
||||
postgresql_where=sa.column("staging_key").is_not(None),
|
||||
)
|
||||
op.create_table(
|
||||
"attachment_variants",
|
||||
sa.Column("attachment_id", sa.Uuid(), sa.ForeignKey("attachments.id"), nullable=False),
|
||||
sa.Column("pipeline_version", sa.Integer(), nullable=False),
|
||||
sa.Column("name", sa.Text(), nullable=False),
|
||||
sa.Column("object_key", sa.Text(collation="C"), nullable=False),
|
||||
sa.Column("content_type", sa.Text(), nullable=False),
|
||||
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
|
||||
sa.Column("width", sa.Integer(), nullable=False),
|
||||
sa.Column("height", sa.Integer(), nullable=False),
|
||||
sa.Column("sha256", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("attachment_id", "pipeline_version", "name"),
|
||||
sa.UniqueConstraint("object_key", name="attachment_variants_object_key_key"),
|
||||
sa.CheckConstraint(
|
||||
"pipeline_version >= 1", name="attachment_variants_pipeline_version_check"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"name IN ('thumbnail', 'crop', 'optimized')", name="attachment_variants_name_check"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"content_type IN ('image/jpeg', 'image/png', 'image/webp')",
|
||||
name="attachment_variants_content_type_check",
|
||||
),
|
||||
sa.CheckConstraint("size_bytes >= 1", name="attachment_variants_size_bytes_check"),
|
||||
sa.CheckConstraint("width >= 1", name="attachment_variants_width_check"),
|
||||
sa.CheckConstraint("height >= 1", name="attachment_variants_height_check"),
|
||||
sa.CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="attachment_variants_sha256_check"),
|
||||
)
|
||||
op.create_table(
|
||||
"jobs",
|
||||
sa.Column("job_id", sa.Uuid(), primary_key=True),
|
||||
sa.Column("attachment_id", sa.Uuid(), sa.ForeignKey("attachments.id"), nullable=False),
|
||||
sa.Column("pipeline_version", sa.Integer(), nullable=False),
|
||||
sa.Column("status", sa.Text(), nullable=False),
|
||||
sa.Column("attempt", sa.Integer(), nullable=False),
|
||||
sa.Column("claims", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("lease_token", sa.Uuid(), nullable=True),
|
||||
sa.Column("lease_until", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("next_attempt_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("last_error", sa.Text(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.UniqueConstraint("attachment_id", "pipeline_version", name="jobs_effect_key"),
|
||||
sa.CheckConstraint("pipeline_version >= 1", name="jobs_pipeline_version_check"),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('queued', 'processing', 'done', 'failed', 'superseded')",
|
||||
name="jobs_status_check",
|
||||
),
|
||||
sa.CheckConstraint("attempt >= 1", name="jobs_attempt_check"),
|
||||
sa.CheckConstraint("claims >= 0", name="jobs_claims_check"),
|
||||
)
|
||||
op.create_index(
|
||||
"jobs_lease_idx",
|
||||
"jobs",
|
||||
["lease_until"],
|
||||
postgresql_where=sa.column("status") == "processing",
|
||||
)
|
||||
op.create_table(
|
||||
"outbox",
|
||||
sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True),
|
||||
sa.Column("job_id", sa.Uuid(), sa.ForeignKey("jobs.job_id"), nullable=False),
|
||||
sa.Column("payload", postgresql.JSONB(), nullable=False),
|
||||
sa.Column("available_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("published_at", sa.DateTime(timezone=True), nullable=True),
|
||||
)
|
||||
op.create_index(
|
||||
"outbox_pending_idx",
|
||||
"outbox",
|
||||
["available_at", "id"],
|
||||
postgresql_where=sa.column("published_at").is_(None),
|
||||
)
|
||||
op.create_index("outbox_job_idx", "outbox", ["job_id"])
|
||||
op.create_table(
|
||||
"job_events",
|
||||
sa.Column("id", sa.BigInteger(), sa.Identity(always=True), primary_key=True),
|
||||
sa.Column("job_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("attachment_id", sa.Uuid(), nullable=False),
|
||||
sa.Column("kind", sa.Text(), nullable=False),
|
||||
sa.Column("attempt", sa.Integer(), nullable=True),
|
||||
sa.Column("detail", postgresql.JSONB(), nullable=False, server_default="{}"),
|
||||
sa.Column("at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index("job_events_attachment_idx", "job_events", ["attachment_id", "id"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete pipeline data")
|
||||
@@ -0,0 +1,20 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0005_failed_registry"
|
||||
down_revision = "0004_jobs"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_index(
|
||||
"jobs_failed_idx",
|
||||
"jobs",
|
||||
[sa.column("updated_at").desc()],
|
||||
postgresql_where=sa.column("status") == "failed",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("jobs_failed_idx", table_name="jobs")
|
||||
@@ -0,0 +1,28 @@
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0006_attachment_quarantine"
|
||||
down_revision = "0005_failed_registry"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("attachments", sa.Column("quarantine_reason", sa.Text(), nullable=True))
|
||||
op.create_check_constraint(
|
||||
"attachments_quarantine_reason_check",
|
||||
"attachments",
|
||||
"quarantine_reason IN ('missing', 'size_mismatch', 'sha_mismatch')",
|
||||
)
|
||||
op.add_column(
|
||||
"attachments", sa.Column("quarantined_at", sa.DateTime(timezone=True), nullable=True)
|
||||
)
|
||||
op.create_check_constraint(
|
||||
"attachments_quarantine_check",
|
||||
"attachments",
|
||||
"(quarantine_reason IS NULL) = (quarantined_at IS NULL)",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError("Downgrade would delete quarantine data")
|
||||
Reference in New Issue
Block a user