Skip to content

Commit

Permalink
migration projects-jobs-metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
pcrespov committed Jun 27, 2023
1 parent d0d9bba commit 1f3186e
Showing 1 changed file with 98 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""new projects_jobs_metadata table
Revision ID: c02d277b0985
Revises: 6647bd56403a
Create Date: 2023-06-27 18:26:36.326140+00:00
"""
from typing import Final

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "c02d277b0985"
down_revision = "6647bd56403a"
branch_labels = None
depends_on = None

# auto-update modified
# TRIGGERS ------------------------
_TABLE_NAME: Final[str] = "projects_jobs_metadata"
_TRIGGER_NAME: Final[str] = "trigger_auto_update" # NOTE: scoped on table
_PROCEDURE_NAME: Final[
str
] = f"{_TABLE_NAME}_auto_update_modified()" # NOTE: scoped on database
modified_timestamp_trigger = sa.DDL(
f"""
DROP TRIGGER IF EXISTS {_TRIGGER_NAME} on {_TABLE_NAME};
CREATE TRIGGER {_TRIGGER_NAME}
BEFORE INSERT OR UPDATE ON {_TABLE_NAME}
FOR EACH ROW EXECUTE PROCEDURE {_PROCEDURE_NAME};
"""
)

# PROCEDURES ------------------------
update_modified_timestamp_procedure = sa.DDL(
f"""
CREATE OR REPLACE FUNCTION {_PROCEDURE_NAME}
RETURNS TRIGGER AS $$
BEGIN
NEW.modified := current_timestamp;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
"""
)


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
_TABLE_NAME,
sa.Column("project_uuid", sa.String(), nullable=False),
sa.Column("parent_name", sa.String(), nullable=False),
sa.Column(
"job_metadata",
postgresql.JSONB(astext_type=sa.Text()),
server_default=sa.text("'{}'::jsonb"),
nullable=True,
),
sa.Column(
"created",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column(
"modified",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.ForeignKeyConstraint(
["project_uuid"],
["projects.uuid"],
name="fk_projects_jobs_metadata_project_uuid",
onupdate="CASCADE",
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("project_uuid"),
)
# ### end Alembic commands ###

# custom
update_modified_timestamp_procedure.execute(bind=op.get_context().bind)
modified_timestamp_trigger.execute(bind=op.get_context().bind)


def downgrade():
# custom
op.execute(f"DROP TRIGGER IF EXISTS {_TRIGGER_NAME} on {_TABLE_NAME};")
op.execute(f"DROP FUNCTION {_PROCEDURE_NAME};")

# ### commands auto generated by Alembic - please adjust! ###
op.drop_table(_TABLE_NAME)
# ### end Alembic commands ###
# ### end Alembic commands ###

0 comments on commit 1f3186e

Please sign in to comment.