diff --git a/backend/app/main.py b/backend/app/main.py index 2a964cb9..d5d77783 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -7,6 +7,7 @@ import sentry_sdk from app.core.db import engine from app.core.config import settings +from app.models import Document if settings.ENVIRONMENT == "production": sentry_sdk.init( @@ -53,3 +54,22 @@ async def db_is_alive(session: Session = Depends(get_session)): raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="DB is unreachable" ) + + +@app.post("/create_document") +async def create_document(session: Session = Depends(get_session)): + doc = Document() + session.add(doc) + session.commit() + session.refresh(doc) + document_id = doc.document_id + # poor man's trigger because I couldnt get SQLAchemy DDL to work with a dynamic table name + session.execute( + text( + f""" + CREATE TABLE assignments_{document_id} PARTITION OF assignments + VALUES IN ('{document_id}') + """ + ) + ) + return doc diff --git a/backend/app/models.py b/backend/app/models.py index fa8ce2d5..ea2285b2 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,8 +1,6 @@ from datetime import datetime from typing import Optional from sqlmodel import Field, SQLModel, UUID, TIMESTAMP, text, Column -from sqlalchemy.schema import DDL -from sqlalchemy import event class UUIDType(UUID): @@ -41,7 +39,7 @@ class GerryDBTable(GerryDBTableBase, table=True): class Document(TimeStampMixin, SQLModel): - document_id: str = Field(sa_column=Column(UUIDType), unique=True) + document_id: str | None = Field(sa_column=Column(UUIDType), unique=True) class AssignmentsMixin(SQLModel): @@ -57,16 +55,19 @@ class Assignments(AssignmentsMixin, table=True): __table_args__ = {"postgres_partition_by": "document_id"} -# one time, create the trigger that creates new assignments partitions -create_partition_trigger = DDL( - """ - CREATE TRIGGER create_assignment_partition AFTER INSERT ON document - - BEGIN - CREATE TABLE assignments_{document_id} PARTITION OF assignments - VALUES IN (new.document_id) - END - """ -) -# do it when the document table is created -event.listen(Document.__table, "after_create", create_partition_trigger) +# In a better world, we'd create the partition on assignments via trigger +# so that it happens even if a document is created outside the API. +# +# # one time, create the trigger that creates new assignments partitions +# create_partition_trigger = DDL( +# """ +# CREATE TRIGGER create_assignment_partition AFTER INSERT ON document + +# BEGIN +# CREATE TABLE assignments_{document_id} PARTITION OF assignments +# VALUES IN (new.document_id) +# END +# """ +# ) +# # do it when the document table is created +# event.listen(Document.__table, "after_create", create_partition_trigger)