cqrs_deleted_diff_master.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 dj_cqrs.registries import MasterRegistry
  6. class Command(BaseCommand):
  7. help = 'Diff of deleted CQRS models pks from master diff stream.'
  8. @classmethod
  9. def serialize_out(cls, package):
  10. return ujson.dumps(package)
  11. @classmethod
  12. def deserialize_in(cls, package_line):
  13. return set(ujson.loads(package_line))
  14. def handle(self, *args, **options):
  15. with sys.stdin as f:
  16. first_line = f.readline()
  17. model = self._get_model(first_line)
  18. self.stdout.write(first_line.strip())
  19. for package_line in f:
  20. master_data = self.deserialize_in(package_line)
  21. exist_pks = set(
  22. model.objects.filter(
  23. pk__in=master_data,
  24. ).values_list(
  25. 'pk',
  26. flat=True,
  27. ),
  28. )
  29. diff_ids = list(master_data - exist_pks)
  30. if diff_ids:
  31. self.stdout.write(self.serialize_out(diff_ids))
  32. self.stderr.write('PK to delete: {0}'.format(str(diff_ids)))
  33. @staticmethod
  34. def _get_model(first_line):
  35. cqrs_id = first_line.split(',')[0]
  36. model = MasterRegistry.get_model_by_cqrs_id(cqrs_id)
  37. if not model:
  38. raise CommandError('Wrong CQRS ID: {0}!'.format(cqrs_id))
  39. return model