cqrs_deleted_sync_replica.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Copyright © 2023 Ingram Micro Inc. All rights reserved.
  2. import sys
  3. import ujson
  4. from django.core.management.base import BaseCommand, CommandError
  5. from django.db import DatabaseError
  6. from dj_cqrs.registries import ReplicaRegistry
  7. class Command(BaseCommand):
  8. help = 'Diff for deleted objects synchronizer from CQRS master stream.'
  9. @classmethod
  10. def deserialize_in(cls, package_line):
  11. return ujson.loads(package_line)
  12. def handle(self, *args, **options):
  13. with sys.stdin as f:
  14. first_line = f.readline().strip()
  15. model = self._get_model(first_line)
  16. for pks_line in f:
  17. try:
  18. model._default_manager.filter(
  19. pk__in=self.deserialize_in(pks_line.strip()),
  20. ).delete()
  21. except DatabaseError as e:
  22. print(str(e), file=sys.stderr)
  23. @staticmethod
  24. def _get_model(first_line):
  25. cqrs_id = first_line.split(',')[0]
  26. model = ReplicaRegistry.get_model_by_cqrs_id(cqrs_id)
  27. if not model:
  28. raise CommandError('Wrong CQRS ID: {0}!'.format(cqrs_id))
  29. return model