You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.7 KiB

  1. # Copyright (C) 2019 Akretion
  2. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
  3. import logging
  4. import odoo
  5. from odoo import api, models
  6. from odoo.tools.safe_eval import safe_eval
  7. import datetime
  8. _logger = logging.getLogger(__name__)
  9. class AutovacuumMixin(models.AbstractModel):
  10. _name = "autovacuum.mixin"
  11. _description = "Mixin used to delete messages or attachments"
  12. @api.multi
  13. def batch_unlink(self):
  14. with api.Environment.manage():
  15. with odoo.registry(
  16. self.env.cr.dbname).cursor() as new_cr:
  17. new_env = api.Environment(new_cr, self.env.uid,
  18. self.env.context)
  19. try:
  20. while self:
  21. batch_delete = self[0:1000]
  22. self -= batch_delete
  23. # do not attach new env to self because it may be
  24. # huge, and the cache is cleaned after each unlink
  25. # so we do not want to much record is the env in
  26. # which we call unlink because odoo would prefetch
  27. # fields, cleared right after.
  28. batch_delete.with_env(new_env).unlink()
  29. new_env.cr.commit()
  30. except Exception as e:
  31. _logger.exception(
  32. "Failed to delete Ms : %s" % (self._name, str(e)))
  33. # Call by cron
  34. @api.model
  35. def autovacuum(self, ttype='message'):
  36. rules = self.env['vacuum.rule'].search([('ttype', '=', ttype)])
  37. for rule in rules:
  38. records = rule._search_autovacuum_records()
  39. records.batch_unlink()
  40. def _get_autovacuum_domain(self, rule):
  41. return []
  42. def _get_autovacuum_records(self, rule):
  43. if rule.model_id and rule.model_filter_domain:
  44. return self._get_autovacuum_records_model(rule)
  45. return self.search(self._get_autovacuum_domain(rule))
  46. def _get_autovacuum_records_model(self, rule):
  47. domain = self._get_autovacuum_domain(rule)
  48. record_domain = safe_eval(rule.model_filter_domain,
  49. locals_dict={'datetime': datetime})
  50. autovacuum_relation = self._autovacuum_relation
  51. for leaf in domain:
  52. if not isinstance(leaf, (tuple, list)):
  53. record_domain.append(leaf)
  54. continue
  55. field, operator, value = leaf
  56. record_domain.append(
  57. ('%s.%s' % (autovacuum_relation, field), operator, value))
  58. records = self.env[rule.model_id.model].search(record_domain)
  59. return self.search(
  60. domain + [('res_id', 'in', records.ids)]
  61. )