From da2f9d45cf9a3b659351266f34cdd98c5503a4b4 Mon Sep 17 00:00:00 2001 From: Marcos Prieto Date: Wed, 21 Aug 2024 15:32:34 +0200 Subject: [PATCH] Create index to find non empty titles for assignments A big time of the query time of get_assignments is spent finding assignments with not null titles. Create an index on that condition trying to speed it up. --- ...5_index_on_assignment_title_is_not_null.py | 32 +++++++++++++++++++ lms/models/assignment.py | 12 +++++-- 2 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 lms/migrations/versions/b39108c0cd35_index_on_assignment_title_is_not_null.py diff --git a/lms/migrations/versions/b39108c0cd35_index_on_assignment_title_is_not_null.py b/lms/migrations/versions/b39108c0cd35_index_on_assignment_title_is_not_null.py new file mode 100644 index 0000000000..91be061212 --- /dev/null +++ b/lms/migrations/versions/b39108c0cd35_index_on_assignment_title_is_not_null.py @@ -0,0 +1,32 @@ +"""Index on assignment.title is not null.""" + +import sqlalchemy as sa +from alembic import op + +revision = "b39108c0cd35" +down_revision = "3d0c022c716c" + + +def upgrade() -> None: + # CONCURRENTLY can't be used inside a transaction. Finish the current one. + op.execute("COMMIT") + + op.create_index( + "ix__assignment_title_is_not_null", + "assignment", + ["title"], + unique=False, + postgresql_where=sa.text("title IS NOT NULL"), + postgresql_concurrently=True, + ) + + +def downgrade() -> None: + op.execute("COMMIT") + + op.drop_index( + "ix__assignment_title_is_not_null", + table_name="assignment", + postgresql_where=sa.text("title IS NOT NULL"), + postgresql_concurrently=True, + ) diff --git a/lms/models/assignment.py b/lms/models/assignment.py index c3fa84c0a0..3e4917ac5a 100644 --- a/lms/models/assignment.py +++ b/lms/models/assignment.py @@ -25,9 +25,6 @@ class Assignment(CreatedUpdatedMixin, Base): """ __tablename__ = "assignment" - __table_args__ = ( - sa.UniqueConstraint("resource_link_id", "tool_consumer_instance_guid"), - ) id: Mapped[int] = mapped_column(autoincrement=True, primary_key=True) @@ -91,6 +88,15 @@ class Assignment(CreatedUpdatedMixin, Base): course: Mapped[Course | None] = relationship(Course) + __table_args__ = ( + sa.UniqueConstraint("resource_link_id", "tool_consumer_instance_guid"), + sa.Index( + "ix__assignment_title_is_not_null", + "title", + postgresql_where=title.is_not(None), + ), + ) + def get_canvas_mapped_file_id(self, file_id): return self.extra.get("canvas_file_mappings", {}).get(file_id, file_id)