From b3131ba671cbef7bb2258ac0491ff72449025b3f Mon Sep 17 00:00:00 2001 From: Viktoriia Krasnovyd <114735598+vkrasnovyd@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:48:04 +0100 Subject: [PATCH] Fix renumbering of motions in categories (#3903) --- cli/generate_models.py | 24 +- data/example-data.json | 2 +- data/initial-data.json | 2 +- meta | 2 +- openslides_backend/action/action.py | 12 + .../actions/motion_category/number_motions.py | 12 + .../action/actions/user/base_merge_mixin.py | 3 +- .../mig_0103_update_indexes/indexes.py | 664 ++++++++++++++++++ .../mig_0103_update_indexes/migration.py | 145 ++++ .../migrations/sql_diff_generator.py | 11 + openslides_backend/models/models.py | 17 + .../services/database/database_writer.py | 28 +- .../shared/interfaces/write_request.py | 1 + .../motion_category/test_number_motions.py | 18 + .../system/migrations/base_migration_test.py | 34 + .../migrations/test_0103_update_indexes.py | 251 +++++++ 16 files changed, 1213 insertions(+), 13 deletions(-) create mode 100644 openslides_backend/migrations/migrations/mig_0103_update_indexes/indexes.py create mode 100644 openslides_backend/migrations/migrations/mig_0103_update_indexes/migration.py create mode 100644 tests/system/migrations/test_0103_update_indexes.py diff --git a/cli/generate_models.py b/cli/generate_models.py index 511d7dcca3..a60ba63afa 100644 --- a/cli/generate_models.py +++ b/cli/generate_models.py @@ -110,7 +110,14 @@ def main() -> None: for collection, data in InternalHelper.MODELS.items(): if collection.startswith("_"): continue - model = Model(collection, data["fields"]) + model = Model( + collection, + data["fields"], + [ + *data.get("unique_together", []), + *data.get("unique_together_strict", []), + ], + ) dest.write(model.get_code()) if args.check: @@ -137,11 +144,17 @@ class Model(Node): MODEL_TEMPLATE = string.Template(dedent(""" class ${class_name}(${base_classes}): collection = "${collection}" - verbose_name = "${verbose_name}" + verbose_name = "${verbose_name}"${unique_together_fields} """)) - def __init__(self, collection: str, fields: dict[str, dict[str, Any]]) -> None: + def __init__( + self, + collection: str, + fields: dict[str, dict[str, Any]], + unique_together_fields: list[str] | None = None, + ) -> None: self.collection = collection + self.unique_together_fields = unique_together_fields assert collection self.attributes = {} for field_name, field in fields.items(): @@ -165,6 +178,11 @@ def get_code(self) -> str: "base_classes": ", ".join(cls.__name__ for cls in base_classes), "collection": self.collection, "verbose_name": verbose_name, + "unique_together_fields": ( + f"\n unique_together_fields = {self.unique_together_fields}" + if self.unique_together_fields + else "" + ), } ) + "\n" diff --git a/data/example-data.json b/data/example-data.json index 66dc012b00..93f2a61fb7 100644 --- a/data/example-data.json +++ b/data/example-data.json @@ -1,5 +1,5 @@ { - "_migration_index": 102, + "_migration_index": 103, "gender":{ "1":{ "id": 1, diff --git a/data/initial-data.json b/data/initial-data.json index ae7213ea22..1111c5943e 100644 --- a/data/initial-data.json +++ b/data/initial-data.json @@ -1,5 +1,5 @@ { - "_migration_index": 102, + "_migration_index": 103, "gender":{ "1":{ "id": 1, diff --git a/meta b/meta index d5d8490b7d..cc2460c1e0 160000 --- a/meta +++ b/meta @@ -1 +1 @@ -Subproject commit d5d8490b7d8aac73901ed789aad199e7d1554825 +Subproject commit cc2460c1e0fb722856fecd56512452f3dc1c479f diff --git a/openslides_backend/action/action.py b/openslides_backend/action/action.py index 1d70e5afe5..8680d19b5c 100644 --- a/openslides_backend/action/action.py +++ b/openslides_backend/action/action.py @@ -441,6 +441,7 @@ def _build_write_request( self.apply_event(event) events_by_type[event["type"]].append(event) information = self.get_full_history_information() + write_request.defer_constraints = self.get_defer_constraints() if self.is_sub_call: write_request.information = information elif information: @@ -775,6 +776,17 @@ def get_post_edit_function(self) -> EditFunction | None: """ return None + def get_defer_constraints(self) -> list[str] | None: + """ + Returns a list of contraints that should be deferred in the transaction. + Can be used for unique indexes on: + - simple fields + - multiple fields (unique_together and unique_together_strict) + - relation to relation + - generic-relation to relation + """ + return None + def merge_history_informations( a: HistoryInformation | None, *other: HistoryInformation | None diff --git a/openslides_backend/action/actions/motion_category/number_motions.py b/openslides_backend/action/actions/motion_category/number_motions.py index f3ce832138..83045dfa5a 100644 --- a/openslides_backend/action/actions/motion_category/number_motions.py +++ b/openslides_backend/action/actions/motion_category/number_motions.py @@ -2,6 +2,9 @@ from datetime import datetime from zoneinfo import ZoneInfo +from meta.dev.src.generate_sql_schema import Helper +from meta.dev.src.helper_get_names import HelperGetNames + from ....models.models import Motion, MotionCategory from ....permissions.permissions import Permissions from ....services.database.commands import GetManyRequest @@ -193,3 +196,12 @@ def get_number( ) number = f"{prefix}{blank}{number_value_str}" return number, number_value_map[motion_id] + + def get_defer_constraints(self) -> list[str] | None: + assert "meeting_id, number" in self.model.unique_together_fields + return [ + HelperGetNames.get_unique_constraint_name( + self.model.collection, + Helper.split_unique_together_fields("meeting_id, number"), + ) + ] diff --git a/openslides_backend/action/actions/user/base_merge_mixin.py b/openslides_backend/action/actions/user/base_merge_mixin.py index 0d72a87d1f..f6f6c5826c 100644 --- a/openslides_backend/action/actions/user/base_merge_mixin.py +++ b/openslides_backend/action/actions/user/base_merge_mixin.py @@ -98,7 +98,8 @@ def add_collection_field_groups( self._all_collection_fields[collection] = [ i for i in Class.__dict__.keys() - if i[:1] != "_" and i not in ["collection", "verbose_name", "id"] + if i[:1] != "_" + and i not in ["collection", "verbose_name", "id", "unique_together_fields"] ] if back_field: self._collection_back_fields[collection] = back_field diff --git a/openslides_backend/migrations/migrations/mig_0103_update_indexes/indexes.py b/openslides_backend/migrations/migrations/mig_0103_update_indexes/indexes.py new file mode 100644 index 0000000000..245a4234a5 --- /dev/null +++ b/openslides_backend/migrations/migrations/mig_0103_update_indexes/indexes.py @@ -0,0 +1,664 @@ +from typing import Any + +""" +Indexes per table that existed in the relational schema at the time this migration was created. +Each index is a dictionary consisting of index name and data needed for creating it. + +3 types of indexes can be differentiated by the value in contype. +It matches the value in pg_constraint.contype for this index and defines the type of the constraint: + - u - unique constraint + - p - primary key + - None - not a constraint, is a regular index +""" + +schema_indexes: dict[str, dict[str, Any]] = { + "agenda_item_t": { + "unique_agenda_item_content_object_id_motion_id": { + "contype": "u", + "fields": "content_object_id_motion_id", + }, + "unique_agenda_item_content_object_id_motion_block_id": { + "contype": "u", + "fields": "content_object_id_motion_block_id", + }, + "unique_agenda_item_content_object_id_assignment_id": { + "contype": "u", + "fields": "content_object_id_assignment_id", + }, + "unique_agenda_item_content_object_id_topic_id": { + "contype": "u", + "fields": "content_object_id_topic_id", + }, + }, + "assignment_t": { + "unique_assignment_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + } + }, + "chat_group_t": { + "unique_chat_group_meeting_id_name": { + "contype": "u", + "fields": "meeting_id, name", + "strict": False, + } + }, + "nm_chat_group_read_group_ids_group_t": { + "pk_nm_chat_group_read_group_ids_group_t": { + "contype": "p", + "fields": "chat_group_id, group_id", + }, + "idx_nm_chat_group_read_group_ids_group_t_chat_group_id": { + "contype": None, + "field": "chat_group_id", + }, + "idx_nm_chat_group_read_group_ids_group_t_group_id": { + "contype": None, + "field": "group_id", + }, + }, + "nm_chat_group_write_group_ids_group_t": { + "pk_nm_chat_group_write_group_ids_group_t": { + "contype": "p", + "fields": "chat_group_id, group_id", + }, + "idx_nm_chat_group_write_group_ids_group_t_chat_group_id": { + "contype": None, + "field": "chat_group_id", + }, + "idx_nm_chat_group_write_group_ids_group_t_group_id": { + "contype": None, + "field": "group_id", + }, + }, + "committee_t": { + "unique_committee_external_id": {"contype": "u", "fields": "external_id"}, + "unique_committee_default_meeting_id": { + "contype": "u", + "fields": "default_meeting_id", + }, + }, + "nm_committee_manager_ids_user_t": { + "pk_nm_committee_manager_ids_user_t": { + "contype": "p", + "fields": "committee_id, user_id", + }, + "idx_nm_committee_manager_ids_user_t_committee_id": { + "contype": None, + "field": "committee_id", + }, + "idx_nm_committee_manager_ids_user_t_user_id": { + "contype": None, + "field": "user_id", + }, + }, + "nm_committee_all_child_ids_committee_t": { + "pk_nm_committee_all_child_ids_committee_t": { + "contype": "p", + "fields": "all_parent_id, all_child_id", + }, + "idx_nm_committee_all_child_ids_committee_t_all_parent_id": { + "contype": None, + "field": "all_parent_id", + }, + "idx_nm_committee_all_child_ids_committee_t_all_child_id": { + "contype": None, + "field": "all_child_id", + }, + }, + "nm_committee_forward_to_committee_ids_committee_t": { + "pk_nm_committee_forward_to_committee_ids_committee_t": { + "contype": "p", + "fields": "receive_forwardings_from_committee_id, forward_to_committee_id", + }, + "idx_nm_committee_forward_to_committee_ids_committee_t_re9215b1e": { + "contype": None, + "field": "receive_forwardings_from_committee_id", + }, + "idx_nm_committee_forward_to_committee_ids_committee_t_fo5507b60": { + "contype": None, + "field": "forward_to_committee_id", + }, + }, + "gender_t": {"unique_gender_name": {"contype": "u", "fields": "name"}}, + "group_t": { + "unique_group_meeting_id_external_id": { + "contype": "u", + "fields": "meeting_id, external_id", + "strict": False, + } + }, + "nm_group_meeting_user_ids_meeting_user_t": { + "pk_nm_group_meeting_user_ids_meeting_user_t": { + "contype": "p", + "fields": "group_id, meeting_user_id", + }, + "idx_nm_group_meeting_user_ids_meeting_user_t_group_id": { + "contype": None, + "field": "group_id", + }, + "idx_nm_group_meeting_user_ids_meeting_user_t_meeting_user_id": { + "contype": None, + "field": "meeting_user_id", + }, + }, + "nm_group_mmagi_meeting_mediafile_t": { + "pk_nm_group_mmagi_meeting_mediafile_t": { + "contype": "p", + "fields": "group_id, meeting_mediafile_id", + }, + "idx_nm_group_mmagi_meeting_mediafile_t_group_id": { + "contype": None, + "field": "group_id", + }, + "idx_nm_group_mmagi_meeting_mediafile_t_meeting_mediafile_id": { + "contype": None, + "field": "meeting_mediafile_id", + }, + }, + "nm_group_mmiagi_meeting_mediafile_t": { + "pk_nm_group_mmiagi_meeting_mediafile_t": { + "contype": "p", + "fields": "group_id, meeting_mediafile_id", + }, + "idx_nm_group_mmiagi_meeting_mediafile_t_group_id": { + "contype": None, + "field": "group_id", + }, + "idx_nm_group_mmiagi_meeting_mediafile_t_meeting_mediafile_id": { + "contype": None, + "field": "meeting_mediafile_id", + }, + }, + "nm_group_read_comment_section_ids_motion_comment_section_t": { + "pk_nm_group_read_comment_section_ids_motion_comment_section_t": { + "contype": "p", + "fields": "group_id, motion_comment_section_id", + }, + "idx_nm_group_read_comment_section_ids_motion_comment_secb9c23c0": { + "contype": None, + "field": "group_id", + }, + "idx_nm_group_read_comment_section_ids_motion_comment_sec520054a": { + "contype": None, + "field": "motion_comment_section_id", + }, + }, + "nm_group_write_comment_section_ids_motion_comment_section_t": { + "pk_nm_group_write_comment_section_ids_motion_comment_section_t": { + "contype": "p", + "fields": "group_id, motion_comment_section_id", + }, + "idx_nm_group_write_comment_section_ids_motion_comment_sed5732f3": { + "contype": None, + "field": "group_id", + }, + "idx_nm_group_write_comment_section_ids_motion_comment_se3ab0450": { + "contype": None, + "field": "motion_comment_section_id", + }, + }, + "nm_group_poll_ids_poll_t": { + "pk_nm_group_poll_ids_poll_t": {"contype": "p", "fields": "group_id, poll_id"}, + "idx_nm_group_poll_ids_poll_t_group_id": {"contype": None, "field": "group_id"}, + "idx_nm_group_poll_ids_poll_t_poll_id": {"contype": None, "field": "poll_id"}, + }, + "list_of_speakers_t": { + "unique_list_of_speakers_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + }, + "unique_list_of_speakers_content_object_id_motion_id": { + "contype": "u", + "fields": "content_object_id_motion_id", + }, + "unique_list_of_speakers_content_object_id_motion_block_id": { + "contype": "u", + "fields": "content_object_id_motion_block_id", + }, + "unique_list_of_speakers_content_object_id_assignment_id": { + "contype": "u", + "fields": "content_object_id_assignment_id", + }, + "unique_list_of_speakers_content_object_id_topic_id": { + "contype": "u", + "fields": "content_object_id_topic_id", + }, + "unique_list_of_speakers_content_object_id_meeting_mediafile_id": { + "contype": "u", + "fields": "content_object_id_meeting_mediafile_id", + }, + }, + "mediafile_t": { + "unique_mediafile_title_parent_id_owner_id": { + "contype": "u", + "fields": "title, parent_id, owner_id", + "strict": True, + }, + "unique_mediafile_token": {"contype": "u", "fields": "token"}, + }, + "meeting_t": { + "unique_meeting_external_id": {"contype": "u", "fields": "external_id"}, + "unique_meeting_motions_default_workflow_id": { + "contype": "u", + "fields": "motions_default_workflow_id", + }, + "unique_meeting_motions_default_amendment_workflow_id": { + "contype": "u", + "fields": "motions_default_amendment_workflow_id", + }, + "unique_meeting_logo_projector_main_id": { + "contype": "u", + "fields": "logo_projector_main_id", + }, + "unique_meeting_logo_projector_header_id": { + "contype": "u", + "fields": "logo_projector_header_id", + }, + "unique_meeting_logo_web_header_id": { + "contype": "u", + "fields": "logo_web_header_id", + }, + "unique_meeting_logo_pdf_header_l_id": { + "contype": "u", + "fields": "logo_pdf_header_l_id", + }, + "unique_meeting_logo_pdf_header_r_id": { + "contype": "u", + "fields": "logo_pdf_header_r_id", + }, + "unique_meeting_logo_pdf_footer_l_id": { + "contype": "u", + "fields": "logo_pdf_footer_l_id", + }, + "unique_meeting_logo_pdf_footer_r_id": { + "contype": "u", + "fields": "logo_pdf_footer_r_id", + }, + "unique_meeting_logo_pdf_ballot_paper_id": { + "contype": "u", + "fields": "logo_pdf_ballot_paper_id", + }, + "unique_meeting_font_regular_id": {"contype": "u", "fields": "font_regular_id"}, + "unique_meeting_font_italic_id": {"contype": "u", "fields": "font_italic_id"}, + "unique_meeting_font_bold_id": {"contype": "u", "fields": "font_bold_id"}, + "unique_meeting_font_bold_italic_id": { + "contype": "u", + "fields": "font_bold_italic_id", + }, + "unique_meeting_font_monospace_id": { + "contype": "u", + "fields": "font_monospace_id", + }, + "unique_meeting_font_chyron_speaker_name_id": { + "contype": "u", + "fields": "font_chyron_speaker_name_id", + }, + "unique_meeting_font_projector_h1_id": { + "contype": "u", + "fields": "font_projector_h1_id", + }, + "unique_meeting_font_projector_h2_id": { + "contype": "u", + "fields": "font_projector_h2_id", + }, + "unique_meeting_reference_projector_id": { + "contype": "u", + "fields": "reference_projector_id", + }, + "unique_meeting_list_of_speakers_countdown_id": { + "contype": "u", + "fields": "list_of_speakers_countdown_id", + }, + "unique_meeting_poll_countdown_id": { + "contype": "u", + "fields": "poll_countdown_id", + }, + "unique_meeting_default_group_id": { + "contype": "u", + "fields": "default_group_id", + }, + "unique_meeting_admin_group_id": {"contype": "u", "fields": "admin_group_id"}, + "unique_meeting_anonymous_group_id": { + "contype": "u", + "fields": "anonymous_group_id", + }, + }, + "nm_meeting_present_user_ids_user_t": { + "pk_nm_meeting_present_user_ids_user_t": { + "contype": "p", + "fields": "meeting_id, user_id", + }, + "idx_nm_meeting_present_user_ids_user_t_meeting_id": { + "contype": None, + "field": "meeting_id", + }, + "idx_nm_meeting_present_user_ids_user_t_user_id": { + "contype": None, + "field": "user_id", + }, + }, + "meeting_mediafile_t": { + "unique_meeting_mediafile_mediafile_id_meeting_id": { + "contype": "u", + "fields": "mediafile_id, meeting_id", + "strict": False, + } + }, + "gm_meeting_mediafile_attachment_ids_t": { + "unique_meeting_mediafile_id_attachment_id": { + "contype": "u", + "fields": "meeting_mediafile_id, attachment_id", + }, + "idx_gm_meeting_mediafile_attachment_ids_t_meeting_mediafile_id": { + "contype": None, + "field": "meeting_mediafile_id", + }, + "idx_gm_meeting_mediafile_attachment_ids_t_attachment_id": { + "contype": None, + "field": "attachment_id", + }, + "idx_gm_meeting_mediafile_attachment_ids_t_attachment_id_3c67b77": { + "contype": None, + "field": "attachment_id_motion_id", + }, + "idx_gm_meeting_mediafile_attachment_ids_t_attachment_id_8abf47a": { + "contype": None, + "field": "attachment_id_topic_id", + }, + "idx_gm_meeting_mediafile_attachment_ids_t_attachment_id_66fb18e": { + "contype": None, + "field": "attachment_id_assignment_id", + }, + }, + "meeting_user_t": { + "unique_meeting_user_meeting_id_user_id": { + "contype": "u", + "fields": "meeting_id, user_id", + "strict": False, + } + }, + "nm_meeting_user_structure_level_ids_structure_level_t": { + "pk_nm_meeting_user_structure_level_ids_structure_level_t": { + "contype": "p", + "fields": "meeting_user_id, structure_level_id", + }, + "idx_nm_meeting_user_structure_level_ids_structure_level_a842d49": { + "contype": None, + "field": "meeting_user_id", + }, + "idx_nm_meeting_user_structure_level_ids_structure_level_abd5dca": { + "contype": None, + "field": "structure_level_id", + }, + }, + "motion_t": { + "unique_motion_meeting_id_number": { + "contype": "u", + "fields": "meeting_id, number", + "strict": False, + }, + "unique_motion_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + }, + }, + "nm_motion_all_derived_motion_ids_motion_t": { + "pk_nm_motion_all_derived_motion_ids_motion_t": { + "contype": "p", + "fields": "all_origin_id, all_derived_motion_id", + }, + "idx_nm_motion_all_derived_motion_ids_motion_t_all_origin_id": { + "contype": None, + "field": "all_origin_id", + }, + "idx_nm_motion_all_derived_motion_ids_motion_t_all_derivee757fda": { + "contype": None, + "field": "all_derived_motion_id", + }, + }, + "nm_motion_identical_motion_ids_motion_t": { + "pk_nm_motion_identical_motion_ids_motion_t": { + "contype": "p", + "fields": "identical_motion_id_1, identical_motion_id_2", + }, + "idx_nm_motion_identical_motion_ids_motion_t_identical_mo6988270": { + "contype": None, + "field": "identical_motion_id_1", + }, + "idx_nm_motion_identical_motion_ids_motion_t_identical_moe0b67bf": { + "contype": None, + "field": "identical_motion_id_2", + }, + }, + "gm_motion_state_extension_reference_ids_t": { + "unique_motion_id_state_extension_reference_id": { + "contype": "u", + "fields": "motion_id, state_extension_reference_id", + }, + "idx_gm_motion_state_extension_reference_ids_t_motion_id": { + "contype": None, + "field": "motion_id", + }, + "idx_gm_motion_state_extension_reference_ids_t_state_exte869c61b": { + "contype": None, + "field": "state_extension_reference_id", + }, + "idx_gm_motion_state_extension_reference_ids_t_state_extee77cee3": { + "contype": None, + "field": "state_extension_reference_id_motion_id", + }, + }, + "gm_motion_recommendation_extension_reference_ids_t": { + "unique_motion_id_recommendation_extension_reference_id": { + "contype": "u", + "fields": "motion_id, recommendation_extension_reference_id", + }, + "idx_gm_motion_recommendation_extension_reference_ids_t_m81631d0": { + "contype": None, + "field": "motion_id", + }, + "idx_gm_motion_recommendation_extension_reference_ids_t_r6488b59": { + "contype": None, + "field": "recommendation_extension_reference_id", + }, + "idx_gm_motion_recommendation_extension_reference_ids_t_r1489537": { + "contype": None, + "field": "recommendation_extension_reference_id_motion_id", + }, + }, + "motion_block_t": { + "unique_motion_block_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + } + }, + "motion_category_t": { + "unique_motion_category_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + } + }, + "motion_comment_t": { + "unique_motion_comment_motion_id_section_id": { + "contype": "u", + "fields": "motion_id, section_id", + "strict": False, + } + }, + "motion_comment_section_t": { + "unique_motion_comment_section_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + } + }, + "motion_editor_t": { + "unique_motion_editor_meeting_user_id_motion_id": { + "contype": "u", + "fields": "meeting_user_id, motion_id", + "strict": False, + } + }, + "motion_state_t": { + "unique_motion_state_name_workflow_id": { + "contype": "u", + "fields": "name, workflow_id", + "strict": False, + } + }, + "nm_motion_state_next_state_ids_motion_state_t": { + "pk_nm_motion_state_next_state_ids_motion_state_t": { + "contype": "p", + "fields": "previous_state_id, next_state_id", + }, + "idx_nm_motion_state_next_state_ids_motion_state_t_previoa964ca1": { + "contype": None, + "field": "previous_state_id", + }, + "idx_nm_motion_state_next_state_ids_motion_state_t_next_state_id": { + "contype": None, + "field": "next_state_id", + }, + }, + "motion_submitter_t": { + "unique_motion_submitter_meeting_user_id_motion_id": { + "contype": "u", + "fields": "meeting_user_id, motion_id", + "strict": False, + } + }, + "motion_supporter_t": { + "unique_motion_supporter_meeting_user_id_motion_id": { + "contype": "u", + "fields": "meeting_user_id, motion_id", + "strict": False, + } + }, + "motion_workflow_t": { + "unique_motion_workflow_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + }, + "unique_motion_workflow_first_state_id": { + "contype": "u", + "fields": "first_state_id", + }, + }, + "motion_working_group_speaker_t": { + "unique_motion_working_group_speaker_meeting_user_id_motion_id": { + "contype": "u", + "fields": "meeting_user_id, motion_id", + "strict": False, + } + }, + "option_t": { + "unique_option_content_object_id_poll_id": { + "contype": "u", + "fields": "content_object_id, poll_id", + "strict": False, + }, + "unique_option_content_object_id_poll_candidate_list_id": { + "contype": "u", + "fields": "content_object_id_poll_candidate_list_id", + }, + }, + "organization_t": { + "unique_organization_theme_id": {"contype": "u", "fields": "theme_id"} + }, + "gm_organization_tag_tagged_ids_t": { + "unique_organization_tag_id_tagged_id": { + "contype": "u", + "fields": "organization_tag_id, tagged_id", + }, + "idx_gm_organization_tag_tagged_ids_t_organization_tag_id": { + "contype": None, + "field": "organization_tag_id", + }, + "idx_gm_organization_tag_tagged_ids_t_tagged_id": { + "contype": None, + "field": "tagged_id", + }, + "idx_gm_organization_tag_tagged_ids_t_tagged_id_committee_id": { + "contype": None, + "field": "tagged_id_committee_id", + }, + "idx_gm_organization_tag_tagged_ids_t_tagged_id_meeting_id": { + "contype": None, + "field": "tagged_id_meeting_id", + }, + }, + "personal_note_t": { + "unique_personal_note_meeting_user_id_content_object_id": { + "contype": "u", + "fields": "meeting_user_id, content_object_id", + "strict": False, + } + }, + "poll_t": { + "unique_poll_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + }, + "unique_poll_global_option_id": {"contype": "u", "fields": "global_option_id"}, + }, + "nm_poll_voted_ids_user_t": { + "pk_nm_poll_voted_ids_user_t": {"contype": "p", "fields": "poll_id, user_id"}, + "idx_nm_poll_voted_ids_user_t_poll_id": {"contype": None, "field": "poll_id"}, + "idx_nm_poll_voted_ids_user_t_user_id": {"contype": None, "field": "user_id"}, + }, + "projector_t": { + "unique_projector_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + } + }, + "projector_countdown_t": { + "unique_projector_countdown_meeting_id_title": { + "contype": "u", + "fields": "meeting_id, title", + "strict": False, + } + }, + "structure_level_t": { + "unique_structure_level_meeting_id_name": { + "contype": "u", + "fields": "meeting_id, name", + "strict": False, + } + }, + "structure_level_list_of_speakers_t": { + "unique_structure_level_list_of_speakers_meeting_id_struce047abe": { + "contype": "u", + "fields": "meeting_id, structure_level_id, list_of_speakers_id", + "strict": False, + } + }, + "gm_tag_tagged_ids_t": { + "unique_tag_id_tagged_id": {"contype": "u", "fields": "tag_id, tagged_id"}, + "idx_gm_tag_tagged_ids_t_tag_id": {"contype": None, "field": "tag_id"}, + "idx_gm_tag_tagged_ids_t_tagged_id": {"contype": None, "field": "tagged_id"}, + "idx_gm_tag_tagged_ids_t_tagged_id_agenda_item_id": { + "contype": None, + "field": "tagged_id_agenda_item_id", + }, + "idx_gm_tag_tagged_ids_t_tagged_id_assignment_id": { + "contype": None, + "field": "tagged_id_assignment_id", + }, + "idx_gm_tag_tagged_ids_t_tagged_id_motion_id": { + "contype": None, + "field": "tagged_id_motion_id", + }, + }, + "topic_t": { + "unique_topic_sequential_number_meeting_id": { + "contype": "u", + "fields": "sequential_number, meeting_id", + } + }, + "user_t": { + "unique_user_username": {"contype": "u", "fields": "username"}, + "unique_user_member_number": {"contype": "u", "fields": "member_number"}, + "unique_user_saml_id": {"contype": "u", "fields": "saml_id"}, + }, +} diff --git a/openslides_backend/migrations/migrations/mig_0103_update_indexes/migration.py b/openslides_backend/migrations/migrations/mig_0103_update_indexes/migration.py new file mode 100644 index 0000000000..6e8634c423 --- /dev/null +++ b/openslides_backend/migrations/migrations/mig_0103_update_indexes/migration.py @@ -0,0 +1,145 @@ +from collections import defaultdict +from typing import Any + +from psycopg import Cursor +from psycopg.rows import DictRow + +from openslides_backend.migrations.base import BaseMigration + +from .indexes import schema_indexes + + +class Migration(BaseMigration): + """ + Mitigates the effects of the initial implementation of Migration 100 + by dropping indexes and unique constraints not present in the schema + and creating new ones with the correct names. + Removes duplicated indexes according to new schema changes. + Makes unique constraints deferrable. + """ + + ORIGIN_COLLECTIONS = [ + "action_worker", + "agenda_item", + "assignment", + "assignment_candidate", + "chat_group", + "chat_message", + "committee", + "gender", + "group", + "history_entry", + "history_position", + "import_preview", + "list_of_speakers", + "mediafile", + "meeting", + "meeting_mediafile", + "meeting_user", + "motion", + "motion_block", + "motion_category", + "motion_change_recommendation", + "motion_comment", + "motion_comment_section", + "motion_editor", + "motion_state", + "motion_submitter", + "motion_supporter", + "motion_workflow", + "motion_working_group_speaker", + "option", + "organization", + "organization_tag", + "personal_note", + "point_of_order_category", + "poll", + "poll_candidate", + "poll_candidate_list", + "projection", + "projector", + "projector_countdown", + "projector_message", + "speaker", + "structure_level", + "structure_level_list_of_speakers", + "tag", + "theme", + "topic", + "user", + "vote", + ] + + @staticmethod + def data_definition(curs: Cursor[DictRow]) -> None: + # Fetch indexes from the database + curs.execute( + """ + SELECT + i.tablename, + jsonb_object_agg(i.indexname, c.contype) AS indexnames + FROM pg_indexes i + LEFT JOIN pg_constraint c + ON c.conname = i.indexname + WHERE ( + i.schemaname = 'public' + AND ( + i.tablename LIKE 'nm_%%' + OR i.tablename LIKE 'gm_%%' + OR (i.tablename = ANY(%s) AND c.contype IS DISTINCT FROM 'p') + ) + ) + GROUP BY i.tablename; + """, + [[f"{collection}_t" for collection in Migration.ORIGIN_COLLECTIONS]], + ) + database_indexes = { + row["tablename"]: row["indexnames"] for row in curs.fetchall() + } + + # Calculate diff + drop: dict[str, dict[str, str]] = defaultdict(dict) + create: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict) + for table_name, indexes in schema_indexes.items(): + if table_name not in database_indexes: + create[table_name] = indexes + else: + if missing := { + i: i_def + for i, i_def in indexes.items() + if i_def["contype"] == "u" + or i not in database_indexes.get(table_name, {}) + }: + create[table_name] = missing + if extra := { + i: contype + for i, contype in database_indexes.get(table_name, {}).items() + if contype == "u" or i not in indexes + }: + drop[table_name] = extra + for table_name in set(database_indexes) - set(schema_indexes): + drop[table_name] = database_indexes[table_name] + + # Process diff + for table_name, drop_indexes in drop.items(): + for name, contype in drop_indexes.items(): + if contype in ["u", "p"]: + curs.execute(f"ALTER TABLE {table_name} DROP CONSTRAINT {name};") + else: + curs.execute(f"DROP INDEX {name};") + for table_name, create_indexes in create.items(): + for name, attributes in create_indexes.items(): + if attributes["contype"] == "u": + strict = " NULLS NOT DISTINCT" if attributes.get("strict") else "" + deferrable = "" if table_name.startswith("gm_") else " DEFERRABLE" + curs.execute( + f"ALTER TABLE {table_name} ADD CONSTRAINT {name} UNIQUE{strict} ({attributes['fields']}){deferrable};" + ) + elif attributes["contype"] == "p": + curs.execute( + f"ALTER TABLE {table_name} ADD CONSTRAINT {name} PRIMARY KEY ({attributes['fields']});" + ) + else: + curs.execute( + f"CREATE INDEX {name} ON {table_name} ({attributes['field']});" + ) diff --git a/openslides_backend/migrations/sql_diff_generator.py b/openslides_backend/migrations/sql_diff_generator.py index 419fae13a0..f8f4d4916a 100644 --- a/openslides_backend/migrations/sql_diff_generator.py +++ b/openslides_backend/migrations/sql_diff_generator.py @@ -1613,6 +1613,17 @@ def handle_to_field_attribute( foreign_field.table, generic_plain_field_name, foreign_field.ref_column, + skip_idx=( + ( + field_def_new["type"] == "generic-relation" + and "list" not in foreign_field.field_def["type"] + ) + or ( + field_def_new["type"] + == foreign_field.field_def["type"] + == "relation" + ) + ), ) alter_views.add(foreign_field.table) recreate_triggers = True diff --git a/openslides_backend/models/models.py b/openslides_backend/models/models.py index 650a22af66..3a67c8a317 100644 --- a/openslides_backend/models/models.py +++ b/openslides_backend/models/models.py @@ -181,6 +181,7 @@ class AssignmentCandidate(Model): class ChatGroup(Model): collection = "chat_group" verbose_name = "chat group" + unique_together_fields = ["meeting_id, name"] id = fields.IntegerField(required=True, constant=True) name = fields.CharField(required=True) @@ -346,6 +347,7 @@ class Gender(Model): class Group(Model): collection = "group" verbose_name = "group" + unique_together_fields = ["meeting_id, external_id"] id = fields.IntegerField(required=True, constant=True) external_id = fields.CharField() @@ -619,6 +621,7 @@ class ListOfSpeakers(Model): class Mediafile(Model): collection = "mediafile" verbose_name = "mediafile" + unique_together_fields = ["title, parent_id, owner_id"] id = fields.IntegerField(required=True, constant=True) title = fields.CharField( @@ -1387,6 +1390,7 @@ class Meeting(Model, MeetingModelMixin): class MeetingMediafile(Model): collection = "meeting_mediafile" verbose_name = "meeting mediafile" + unique_together_fields = ["mediafile_id, meeting_id"] id = fields.IntegerField(required=True, constant=True) mediafile_id = fields.RelationField( @@ -1506,6 +1510,7 @@ class MeetingMediafile(Model): class MeetingUser(Model): collection = "meeting_user" verbose_name = "meeting user" + unique_together_fields = ["meeting_id, user_id"] id = fields.IntegerField(required=True, constant=True) comment = fields.HTMLStrictField() @@ -1578,6 +1583,7 @@ class MeetingUser(Model): class Motion(Model): collection = "motion" verbose_name = "motion" + unique_together_fields = ["meeting_id, number"] id = fields.IntegerField(required=True, constant=True) number = fields.CharField() @@ -1896,6 +1902,7 @@ class MotionChangeRecommendation(Model): class MotionComment(Model): collection = "motion_comment" verbose_name = "motion comment" + unique_together_fields = ["motion_id, section_id"] id = fields.IntegerField(required=True, constant=True) comment = fields.HTMLStrictField(required=True) @@ -1960,6 +1967,7 @@ class MotionCommentSection(Model): class MotionEditor(Model): collection = "motion_editor" verbose_name = "motion editor" + unique_together_fields = ["meeting_user_id, motion_id"] id = fields.IntegerField(required=True, constant=True) weight = fields.IntegerField() @@ -1975,6 +1983,7 @@ class MotionEditor(Model): class MotionState(Model): collection = "motion_state" verbose_name = "motion state" + unique_together_fields = ["name, workflow_id"] id = fields.IntegerField(required=True, constant=True) name = fields.CharField(required=True) @@ -2061,6 +2070,7 @@ class MotionState(Model): class MotionSubmitter(Model): collection = "motion_submitter" verbose_name = "motion submitter" + unique_together_fields = ["meeting_user_id, motion_id"] id = fields.IntegerField(required=True, constant=True) weight = fields.IntegerField() @@ -2076,6 +2086,7 @@ class MotionSubmitter(Model): class MotionSupporter(Model): collection = "motion_supporter" verbose_name = "motion supporter" + unique_together_fields = ["meeting_user_id, motion_id"] id = fields.IntegerField(required=True, constant=True) meeting_user_id = fields.RelationField(to={"meeting_user": "motion_supporter_ids"}) @@ -2124,6 +2135,7 @@ class MotionWorkflow(Model): class MotionWorkingGroupSpeaker(Model): collection = "motion_working_group_speaker" verbose_name = "motion working group speaker" + unique_together_fields = ["meeting_user_id, motion_id"] id = fields.IntegerField(required=True, constant=True) weight = fields.IntegerField() @@ -2141,6 +2153,7 @@ class MotionWorkingGroupSpeaker(Model): class Option(Model): collection = "option" verbose_name = "option" + unique_together_fields = ["content_object_id, poll_id"] id = fields.IntegerField(required=True, constant=True) weight = fields.IntegerField(default=10000) @@ -2286,6 +2299,7 @@ class OrganizationTag(Model): class PersonalNote(Model): collection = "personal_note" verbose_name = "personal note" + unique_together_fields = ["meeting_user_id, content_object_id"] id = fields.IntegerField(required=True, constant=True) note = fields.HTMLStrictField() @@ -2598,6 +2612,7 @@ class Projector(Model): class ProjectorCountdown(Model): collection = "projector_countdown" verbose_name = "projector countdown" + unique_together_fields = ["meeting_id, title"] id = fields.IntegerField(required=True, constant=True) title = fields.CharField(required=True) @@ -2680,6 +2695,7 @@ class Speaker(Model): class StructureLevel(Model): collection = "structure_level" verbose_name = "structure level" + unique_together_fields = ["meeting_id, name"] id = fields.IntegerField(required=True, constant=True) name = fields.CharField(required=True) @@ -2707,6 +2723,7 @@ class StructureLevel(Model): class StructureLevelListOfSpeakers(Model): collection = "structure_level_list_of_speakers" verbose_name = "structure level list of speakers" + unique_together_fields = ["meeting_id, structure_level_id, list_of_speakers_id"] id = fields.IntegerField(required=True, constant=True) structure_level_id = fields.RelationField( diff --git a/openslides_backend/services/database/database_writer.py b/openslides_backend/services/database/database_writer.py index 47146bdd02..9cbda65ff1 100644 --- a/openslides_backend/services/database/database_writer.py +++ b/openslides_backend/services/database/database_writer.py @@ -91,7 +91,9 @@ def write( for write_request in self.write_requests: with make_span(self.env, "write with database context"): - results = self.write_events(write_request.events) + results = self.write_events( + write_request.events, write_request.defer_constraints + ) for fqid, model in results.items(): modified_models[fqid].update(model) @@ -101,8 +103,7 @@ def get_request_name(self, event: WriteRequest) -> str: return type(event).__name__.replace("Request", "").replace("Event", "").upper() def write_events( - self, - events: list[Event], + self, events: list[Event], defer_constraints: list[str] | None ) -> dict[FullQualifiedId, dict[str, Any]]: if not events: raise BadCodingException("Events are needed.") @@ -134,7 +135,9 @@ def write_events( models_created_or_updated[fqid] = data case EventType.Update: assert id_ - fqid, data = self.update_model(event, collection, id_) + fqid, data = self.update_model( + event, collection, id_, defer_constraints + ) models_created_or_updated[fqid].update(data) case EventType.Delete: assert id_ @@ -190,7 +193,11 @@ def delete_model( ) def update_model( - self, event: Event, collection: Collection, id_: Id + self, + event: Event, + collection: Collection, + id_: Id, + defer_constraints: list[str] | None = None, ) -> tuple[FullQualifiedId, dict[str, Any]]: table = sql.Identifier(f"{collection}_t") statement = sql.SQL(""" @@ -275,7 +282,12 @@ def update_model( collection, id_, ), self.execute_sql( - statement, arguments, collection, id_, return_fields=event_return_fields + statement, + arguments, + collection, + id_, + return_fields=event_return_fields, + defer_constraints=defer_constraints, ) def is_primary_nm_relation(self, field: Field) -> bool: @@ -475,6 +487,7 @@ def execute_sql( collection: Collection, target_id: Id | None, return_fields: list[str] | None = ["id"], + defer_constraints: list[str] | None = None, ) -> dict[str, Any]: """ Used for write events; except for those parts writing on intermediate tables. @@ -488,6 +501,9 @@ def execute_sql( error_fqid = fqid_from_collection_and_id(collection, target_id or 0) try: with self.connection.cursor() as curs: + if defer_constraints: + for constraint in defer_constraints: + curs.execute(f"SET CONSTRAINTS {constraint} DEFERRED;") curs.execute(statement, arguments) if return_fields: result = curs.fetchone() diff --git a/openslides_backend/shared/interfaces/write_request.py b/openslides_backend/shared/interfaces/write_request.py index cb1ae65fab..56660c53b0 100644 --- a/openslides_backend/shared/interfaces/write_request.py +++ b/openslides_backend/shared/interfaces/write_request.py @@ -18,6 +18,7 @@ class WriteRequest: information: HistoryInformation | None = None user_id: int | None = None locked_fields: dict[str, CollectionFieldLock] = field(default_factory=dict) + defer_constraints: list[str] | None = None @dataclass diff --git a/tests/system/action/motion_category/test_number_motions.py b/tests/system/action/motion_category/test_number_motions.py index d7bf9fd23a..61d053e0b8 100644 --- a/tests/system/action/motion_category/test_number_motions.py +++ b/tests/system/action/motion_category/test_number_motions.py @@ -57,6 +57,24 @@ def test_two_motions(self) -> None: self.assert_model_exists("motion/78", {"number": "prefix_A 001"}) self.assert_model_exists("motion/85", {"number": "prefix_A 002"}) + def test_two_motions_swap_numbers(self) -> None: + self.create_motion_category(1, 111, {"prefix": "A"}) + self.create_motion( + 1, + 78, + motion_data={"category_id": 111, "number": "A01", "category_weight": 2}, + ) + self.create_motion( + 1, + 85, + motion_data={"category_id": 111, "number": "A02", "category_weight": 1}, + ) + + response = self.request("motion_category.number_motions", {"id": 111}) + self.assert_status_code(response, 200) + self.assert_model_exists("motion/78", {"number": "A02"}) + self.assert_model_exists("motion/85", {"number": "A01"}) + def test_check_amendments_error_case(self) -> None: self.create_motion_category(1, 111) self.create_motion_category(1, 78, {"parent_id": 111}) diff --git a/tests/system/migrations/base_migration_test.py b/tests/system/migrations/base_migration_test.py index 47fe5ed205..b039662aeb 100644 --- a/tests/system/migrations/base_migration_test.py +++ b/tests/system/migrations/base_migration_test.py @@ -231,6 +231,40 @@ def assert_trigger_not_exists( ) -> None: assert not self.get_trigger_exists(curs, trigger_name) + def get_table_constraint_exists( + self, curs: Cursor[DictRow], constraint_name: str + ) -> bool: + return cast( + dict[str, Any], + curs.execute( + f"SELECT EXISTS(SELECT 1 FROM information_schema.table_constraints WHERE constraint_name = '{constraint_name}') AS exists;" + ).fetchone(), + )["exists"] + + def assert_table_constraint_exists( + self, curs: Cursor[DictRow], constraint_name: str + ) -> None: + assert self.get_table_constraint_exists(curs, constraint_name) + + def assert_table_constraint_not_exists( + self, curs: Cursor[DictRow], constraint_name: str + ) -> None: + assert not self.get_table_constraint_exists(curs, constraint_name) + + def get_index_exists(self, curs: Cursor[DictRow], index_name: str) -> bool: + return cast( + dict[str, Any], + curs.execute( + f"SELECT EXISTS(SELECT 1 FROM pg_indexes WHERE indexname = '{index_name}') AS exists;" + ).fetchone(), + )["exists"] + + def assert_index_exists(self, curs: Cursor[DictRow], index_name: str) -> None: + assert self.get_index_exists(curs, index_name) + + def assert_index_not_exists(self, curs: Cursor[DictRow], index_name: str) -> None: + assert not self.get_index_exists(curs, index_name) + def assert_content_not_none( self, cur: Cursor[DictRow], diff --git a/tests/system/migrations/test_0103_update_indexes.py b/tests/system/migrations/test_0103_update_indexes.py new file mode 100644 index 0000000000..0b231ade37 --- /dev/null +++ b/tests/system/migrations/test_0103_update_indexes.py @@ -0,0 +1,251 @@ +from psycopg import sql + +from openslides_backend.migrations.migration_helper import MigrationState +from openslides_backend.services.postgresql.db_connection_handling import ( + get_new_os_conn, +) +from tests.system.migrations.base_migration_test import BaseMigrationTestCase + + +class TestMigration103(BaseMigrationTestCase): + migration_number = 103 + + def test_0103(self) -> None: + schema_and_corrupt_constraints = ( + ( + "meeting_t", + "unique_meeting_external_id", + "meeting_m_external_id_key", + "external_id", + ), + ( + "meeting_t", + "unique_meeting_default_group_id", + "meeting_m_default_group_id_key", + "default_group_id", + ), + ( + "meeting_mediafile_t", + "unique_meeting_mediafile_mediafile_id_meeting_id", + "meeting_mediafile_m_mediafile_id_meeting_id_key", + "mediafile_id, meeting_id", + ), + ( + "mediafile_t", + "unique_mediafile_title_parent_id_owner_id", + "mediafile_m_title_parent_id_owner_id_key", + "title, parent_id, owner_id", + ), + ( + "assignment_t", + "unique_assignment_sequential_number_meeting_id", + "assignment_m_sequential_number_meeting_id_key", + "sequential_number, meeting_id", + ), + ( + "gm_tag_tagged_ids_t", + "unique_tag_id_tagged_id", + "gm_tag_tagged_ids_m_tag_id_tagged_id_key", + "tag_id, tagged_id", + ), + ( + "nm_chat_group_read_group_ids_group_t", + "pk_nm_chat_group_read_group_ids_group_t", + "nm_chat_group_read_group_ids_group_m_pkey", + "chat_group_id, group_id", + ), + ) + schema_and_corrupt_indexes = ( + ( + "idx_nm_chat_group_read_group_ids_group_t_chat_group_id", + "nm_chat_group_read_group_ids_group_m_chat_group_id_idx", + ), + ( + "idx_nm_chat_group_read_group_ids_group_t_group_id", + "nm_chat_group_read_group_ids_group_m_group_id_idx", + ), + ( + "idx_gm_tag_tagged_ids_t_tagged_id_agenda_item_id", + "gm_tag_tagged_ids_m_tagged_id_agenda_item_id_idx", + ), + ) + removed_indexes = [ + "idx_agenda_item_t_content_object_id_motion_id", + "idx_agenda_item_t_content_object_id_motion_block_id", + "idx_agenda_item_t_content_object_id_assignment_id", + "idx_agenda_item_t_content_object_id_topic_id", + "idx_committee_t_default_meeting_id", + "idx_list_of_speakers_t_content_object_id_motion_id", + "idx_list_of_speakers_t_content_object_id_motion_block_id", + "idx_list_of_speakers_t_content_object_id_assignment_id", + "idx_list_of_speakers_t_content_object_id_topic_id", + "idx_list_of_speakers_t_content_object_id_meeting_mediafile_id", + "idx_meeting_t_motions_default_workflow_id", + "idx_meeting_t_motions_default_amendment_workflow_id", + "idx_meeting_t_logo_projector_main_id", + "idx_meeting_t_logo_projector_header_id", + "idx_meeting_t_logo_web_header_id", + "idx_meeting_t_logo_pdf_header_l_id", + "idx_meeting_t_logo_pdf_header_r_id", + "idx_meeting_t_logo_pdf_footer_l_id", + "idx_meeting_t_logo_pdf_footer_r_id", + "idx_meeting_t_logo_pdf_ballot_paper_id", + "idx_meeting_t_font_regular_id", + "idx_meeting_t_font_italic_id", + "idx_meeting_t_font_bold_id", + "idx_meeting_t_font_bold_italic_id", + "idx_meeting_t_font_monospace_id", + "idx_meeting_t_font_chyron_speaker_name_id", + "idx_meeting_t_font_projector_h1_id", + "idx_meeting_t_font_projector_h2_id", + "idx_meeting_t_reference_projector_id", + "idx_meeting_t_list_of_speakers_countdown_id", + "idx_meeting_t_poll_countdown_id", + "idx_meeting_t_default_group_id", + "idx_meeting_t_admin_group_id", + "idx_meeting_t_anonymous_group_id", + "idx_motion_workflow_t_first_state_id", + "idx_option_t_content_object_id_poll_candidate_list_id", + "idx_organization_t_theme_id", + "idx_poll_t_global_option_id", + ] + constraints_to_drop = [ + constraints[2] for constraints in schema_and_corrupt_constraints + ] + indexes_to_drop = ( + [constraints[1] for constraints in schema_and_corrupt_indexes] + + removed_indexes + + ["meeting_m_default_group_id_idx"] + ) + constraints_to_create = { + constraints[1]: constraints[3] + for constraints in schema_and_corrupt_constraints + } + indexes_to_create = [ + constraints[0] for constraints in schema_and_corrupt_indexes + ] + with get_new_os_conn() as conn: + with conn.cursor() as curs: + # Introduce some arbitrary changes to the triggers, to see if they're fully reverted to standard build by the migration + for ( + table, + schema_constraint, + corrupted_constraint, + _, + ) in schema_and_corrupt_constraints: + curs.execute( + sql.SQL( + "ALTER TABLE {table} RENAME CONSTRAINT {schema_constraint} TO {corrupted_constraint};" + ).format( + table=sql.Identifier(table), + schema_constraint=sql.Identifier(schema_constraint), + corrupted_constraint=sql.Identifier(corrupted_constraint), + ) + ) + curs.execute( + "CREATE INDEX meeting_m_default_group_id_idx ON meeting_t (default_group_id);" + ) + for schema_index, corrupted_index in schema_and_corrupt_indexes: + curs.execute( + sql.SQL( + "ALTER INDEX {schema_index} RENAME TO {corrupted_index};" + ).format( + schema_index=sql.Identifier(schema_index), + corrupted_index=sql.Identifier(corrupted_index), + ) + ) + for constraint in constraints_to_drop: + self.assert_table_constraint_exists(curs, constraint) + for constraint in constraints_to_create.keys(): + self.assert_table_constraint_not_exists(curs, constraint) + for index in indexes_to_drop: + self.assert_index_exists(curs, index) + for index in indexes_to_create: + self.assert_index_not_exists(curs, index) + + manager = self.create_migration_manager() + intermediate_result = self.make_migration_request(manager) + assert ( + intermediate_result["status"] != MigrationState.MIGRATION_FAILED + ), f"Migration failed with message: {intermediate_result['exception']}." + self.wait_for_migration_thread(self.MAX_WAIT) + self.assert_migration_finalized() + + with get_new_os_conn() as conn: + with conn.cursor() as curs: + for constraint in constraints_to_drop: + self.assert_table_constraint_not_exists(curs, constraint) + for index in indexes_to_drop: + self.assert_index_not_exists(curs, index) + + for constraint, on_columns in constraints_to_create.items(): + self.assert_table_constraint_exists(curs, constraint) + if constraint == "pk_nm_chat_group_read_group_ids_group_t": + continue + + # Check unique constraints recreated correctly + row = curs.execute(f""" + SELECT + split_part(split_part(i.indexdef, '(', 2), ')', 1 ) as on_columns, + c.nulls_distinct, + c.is_deferrable, + c.initially_deferred + FROM pg_indexes i + JOIN information_schema.table_constraints c + ON c.constraint_name = i.indexname + WHERE i.indexname = '{constraint}';""").fetchone() + assert row == { + "on_columns": on_columns, + "nulls_distinct": ( + "NO" + if constraint == "unique_mediafile_title_parent_id_owner_id" + else "YES" + ), + "is_deferrable": ( + "NO" if constraint == "unique_tag_id_tagged_id" else "YES" + ), + "initially_deferred": "NO", + } + + # Check unique constraints with correct names recreated with deferrable + for constraint in [ + "unique_chat_group_meeting_id_name", + "unique_gender_name", + "unique_meeting_logo_projector_header_id", + "unique_list_of_speakers_content_object_id_motion_block_id", + "unique_meeting_mediafile_id_attachment_id", + ]: + row = curs.execute(f""" + SELECT + is_deferrable, + initially_deferred + FROM information_schema.table_constraints + WHERE constraint_name = '{constraint}';""").fetchone() + assert row == { + "is_deferrable": ( + "NO" + if constraint == "unique_meeting_mediafile_id_attachment_id" + else "YES" + ), + "initially_deferred": "NO", + } + + # Check primary key recreated correctly + row = curs.execute(""" + SELECT + split_part(split_part(indexdef, '(', 2), ')', 1 ) as on_columns + FROM pg_indexes + WHERE indexname = 'pk_nm_chat_group_read_group_ids_group_t'; + """).fetchone() + assert row == {"on_columns": "chat_group_id, group_id"} + + # Check indexes recreated correctly + for index in indexes_to_create: + self.assert_index_exists(curs, index) + row = curs.execute(f""" + SELECT + split_part(split_part(indexdef, '(', 2), ')', 1 ) as on_columns + FROM pg_indexes + WHERE indexname = '{index}'; + """).fetchone() + assert row == {"on_columns": index.split("_t_")[1]}