From 5bb701d82154b5df8818e6ea10da06d27fbfd07a Mon Sep 17 00:00:00 2001 From: Bahram Aghaei Date: Wed, 12 Jun 2024 14:30:29 +0200 Subject: [PATCH] Sync django query and postgres query (#653) * run postgres query for rows that changes is null for them and there is value for changes_text * add a test case to make when changes has value it wont be overwritten by changes_text --- .../management/commands/auditlogmigratejson.py | 8 +++++++- auditlog_tests/test_two_step_json_migration.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/auditlog/management/commands/auditlogmigratejson.py b/auditlog/management/commands/auditlogmigratejson.py index 44871a8..86caf25 100644 --- a/auditlog/management/commands/auditlogmigratejson.py +++ b/auditlog/management/commands/auditlogmigratejson.py @@ -125,7 +125,13 @@ class Command(BaseCommand): def postgres(): with connection.cursor() as cursor: cursor.execute( - 'UPDATE auditlog_logentry SET changes="changes_text"::jsonb' + """ + UPDATE auditlog_logentry + SET changes="changes_text"::jsonb + WHERE changes_text IS NOT NULL + AND changes_text <> '' + AND changes IS NULL + """ ) return cursor.cursor.rowcount diff --git a/auditlog_tests/test_two_step_json_migration.py b/auditlog_tests/test_two_step_json_migration.py index 5beb560..0b3bfff 100644 --- a/auditlog_tests/test_two_step_json_migration.py +++ b/auditlog_tests/test_two_step_json_migration.py @@ -135,6 +135,21 @@ class AuditlogMigrateJsonTest(TestCase): self.assertEqual(errbuf, "") self.assertIsNotNone(log_entry.changes) + def test_native_postgres_changes_not_overwritten(self): + # Arrange + log_entry = self.make_logentry() + log_entry.changes = original_changes = {"key": "value"} + log_entry.changes_text = '{"key": "new value"}' + log_entry.save() + + # Act + outbuf, errbuf = self.call_command("-d=postgres") + log_entry.refresh_from_db() + + # Assert + self.assertEqual(errbuf, "") + self.assertEqual(log_entry.changes, original_changes) + def test_native_unsupported(self): # Arrange log_entry = self.make_logentry()