From ac8bab7ed0df172c09d2241874ac6ad1a0304486 Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Fri, 6 Mar 2026 14:43:56 -0800 Subject: [PATCH] Refactor: O(1) lookup table for CRYPT_FIELDS in per-record encryption Add CRYPT_FIELDS_BY_MODEL to CryptMixin, derived from CRYPT_FIELDS at class definition time. _encrypt_record_inline() now does a single dict lookup instead of a linear scan per record, eliminating the loop and break pattern. Co-Authored-By: Claude Sonnet 4.6 --- .../management/commands/document_exporter.py | 16 +++++++--------- src/documents/management/commands/mixins.py | 4 ++++ 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/documents/management/commands/document_exporter.py b/src/documents/management/commands/document_exporter.py index 6f7d9426e..01ec98dfd 100644 --- a/src/documents/management/commands/document_exporter.py +++ b/src/documents/management/commands/document_exporter.py @@ -605,15 +605,13 @@ class Command(CryptMixin, BaseCommand): """Encrypt sensitive fields in a single record, if passphrase is set.""" if not self.passphrase: return - model = record.get("model", "") - for cfg in self.CRYPT_FIELDS: - if model == cfg["model_name"]: - for field in cfg["fields"]: - if record["fields"].get(field): - record["fields"][field] = self.encrypt_string( - value=record["fields"][field], - ) - break + fields = self.CRYPT_FIELDS_BY_MODEL.get(record.get("model", "")) + if fields: + for field in fields: + if record["fields"].get(field): + record["fields"][field] = self.encrypt_string( + value=record["fields"][field], + ) def _write_split_manifest( self, diff --git a/src/documents/management/commands/mixins.py b/src/documents/management/commands/mixins.py index 785dca82a..b03e05956 100644 --- a/src/documents/management/commands/mixins.py +++ b/src/documents/management/commands/mixins.py @@ -89,6 +89,10 @@ class CryptMixin: ], }, ] + # O(1) lookup for per-record encryption; derived from CRYPT_FIELDS at class definition time + CRYPT_FIELDS_BY_MODEL: dict[str, list[str]] = { + cfg["model_name"]: cfg["fields"] for cfg in CRYPT_FIELDS + } def get_crypt_params(self) -> dict[str, dict[str, str | int]]: return {