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.

270 lines
9.7 KiB

7 years ago
7 years ago
Remove RowExclusiveLock on exception_rule The goal of the modified method is to create or remove the relationship (in the M2m relation tabel) between the tested model (such as sale_order) and the exception rules. When the ORM writes on ExceptionRule.sale_ids (using the example of sale_exception), it will first proceeds with these updates: * an UPDATE on exception_rule to set the write_date * INSERT or DELETE on the relation table * but then, as "write" is called on the exception rule, the ORM will trigger the api.depends to recompute all the "main_exception_ids" of the records (sales, ...) related to it, leading to an UPDATE for each sale order We end up with RowExclusiveLock on such records: * All the records of the relation table added / deleted for the current sale order * All the records of exception_rule matching the current sale order * All the records of sale_order related to the exception rules matching the current sale order The first one is expected, the next 2 are not. We can remove the lock on the exception_rule table by removing `_log_access`, however in any case, the main_exception_ids computed field will continue to lock many sale orders, effectively preventing 2 sales orders with the same exception to be confirmed at the same time. Reversing the write by writing on SaleOrder instead of ExceptionRule fixes the 2 unexpected locks. It should not result in more queries: the "to remove" part generates a DELETE on the relation table for the rule to remove and the "to add" part generates an INSERT for the rule to add, both will be exactly the same in both cases. Related to #1642 Replaces #1638
5 years ago
Remove RowExclusiveLock on exception_rule The goal of the modified method is to create or remove the relationship (in the M2m relation tabel) between the tested model (such as sale_order) and the exception rules. When the ORM writes on ExceptionRule.sale_ids (using the example of sale_exception), it will first proceeds with these updates: * an UPDATE on exception_rule to set the write_date * INSERT or DELETE on the relation table * but then, as "write" is called on the exception rule, the ORM will trigger the api.depends to recompute all the "main_exception_ids" of the records (sales, ...) related to it, leading to an UPDATE for each sale order We end up with RowExclusiveLock on such records: * All the records of the relation table added / deleted for the current sale order * All the records of exception_rule matching the current sale order * All the records of sale_order related to the exception rules matching the current sale order The first one is expected, the next 2 are not. We can remove the lock on the exception_rule table by removing `_log_access`, however in any case, the main_exception_ids computed field will continue to lock many sale orders, effectively preventing 2 sales orders with the same exception to be confirmed at the same time. Reversing the write by writing on SaleOrder instead of ExceptionRule fixes the 2 unexpected locks. It should not result in more queries: the "to remove" part generates a DELETE on the relation table for the rule to remove and the "to add" part generates an INSERT for the rule to add, both will be exactly the same in both cases. Related to #1642 Replaces #1638
5 years ago
Remove RowExclusiveLock on exception_rule The goal of the modified method is to create or remove the relationship (in the M2m relation tabel) between the tested model (such as sale_order) and the exception rules. When the ORM writes on ExceptionRule.sale_ids (using the example of sale_exception), it will first proceeds with these updates: * an UPDATE on exception_rule to set the write_date * INSERT or DELETE on the relation table * but then, as "write" is called on the exception rule, the ORM will trigger the api.depends to recompute all the "main_exception_ids" of the records (sales, ...) related to it, leading to an UPDATE for each sale order We end up with RowExclusiveLock on such records: * All the records of the relation table added / deleted for the current sale order * All the records of exception_rule matching the current sale order * All the records of sale_order related to the exception rules matching the current sale order The first one is expected, the next 2 are not. We can remove the lock on the exception_rule table by removing `_log_access`, however in any case, the main_exception_ids computed field will continue to lock many sale orders, effectively preventing 2 sales orders with the same exception to be confirmed at the same time. Reversing the write by writing on SaleOrder instead of ExceptionRule fixes the 2 unexpected locks. It should not result in more queries: the "to remove" part generates a DELETE on the relation table for the rule to remove and the "to add" part generates an INSERT for the rule to add, both will be exactly the same in both cases. Related to #1642 Replaces #1638
5 years ago
  1. # Copyright 2011 Raphaël Valyi, Renato Lima, Guewen Baconnier, Sodexis
  2. # Copyright 2017 Akretion (http://www.akretion.com)
  3. # Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
  4. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  5. import time
  6. import html
  7. from odoo import api, fields, models, _
  8. from odoo.exceptions import UserError, ValidationError
  9. from odoo.tools.safe_eval import safe_eval
  10. from odoo import osv
  11. class ExceptionRule(models.Model):
  12. _name = 'exception.rule'
  13. _description = 'Exception Rule'
  14. _order = 'active desc, sequence asc'
  15. name = fields.Char('Exception Name', required=True, translate=True)
  16. description = fields.Text('Description', translate=True)
  17. sequence = fields.Integer(
  18. string='Sequence',
  19. help="Gives the sequence order when applying the test",
  20. )
  21. model = fields.Selection(selection=[], string='Apply on', required=True)
  22. exception_type = fields.Selection(
  23. selection=[('by_domain', 'By domain'),
  24. ('by_py_code', 'By python code')],
  25. string='Exception Type', required=True, default='by_py_code',
  26. help="By python code: allow to define any arbitrary check\n"
  27. "By domain: limited to a selection by an odoo domain:\n"
  28. " performance can be better when exceptions "
  29. " are evaluated with several records")
  30. domain = fields.Char('Domain')
  31. active = fields.Boolean('Active', default=True)
  32. code = fields.Text(
  33. 'Python Code',
  34. help="Python code executed to check if the exception apply or "
  35. "not. Use failed = True to block the exception",
  36. )
  37. @api.constrains('exception_type', 'domain', 'code')
  38. def check_exception_type_consistency(self):
  39. for rule in self:
  40. if ((rule.exception_type == 'by_py_code' and not rule.code) or
  41. (rule.exception_type == 'by_domain' and not rule.domain)):
  42. raise ValidationError(
  43. _("There is a problem of configuration, python code or "
  44. "domain is missing to match the exception type.")
  45. )
  46. @api.multi
  47. def _get_domain(self):
  48. """ override me to customize domains according exceptions cases """
  49. self.ensure_one()
  50. return safe_eval(self.domain)
  51. class BaseExceptionMethod(models.AbstractModel):
  52. _name = 'base.exception.method'
  53. _description = 'Exception Rule Methods'
  54. @api.multi
  55. def _get_main_records(self):
  56. """
  57. Used in case we check exceptions on a record but write these
  58. exceptions on a parent record. Typical example is with
  59. sale.order.line. We check exceptions on some sale order lines but
  60. write these exceptions on the sale order, so they are visible.
  61. """
  62. return self
  63. @api.multi
  64. def _reverse_field(self):
  65. raise NotImplementedError()
  66. def _rule_domain(self):
  67. """Filter exception.rules.
  68. By default, only the rules with the correct model
  69. will be used.
  70. """
  71. return [('model', '=', self._name)]
  72. @api.multi
  73. def detect_exceptions(self):
  74. """List all exception_ids applied on self
  75. Exception ids are also written on records
  76. """
  77. rules = self.env['exception.rule'].sudo().search(
  78. self._rule_domain())
  79. all_exception_ids = []
  80. rules_to_remove = {}
  81. rules_to_add = {}
  82. for rule in rules:
  83. records_with_exception = self._detect_exceptions(rule)
  84. reverse_field = self._reverse_field()
  85. main_records = self._get_main_records()
  86. commons = main_records & rule[reverse_field]
  87. to_remove = commons - records_with_exception
  88. to_add = records_with_exception - commons
  89. # we expect to always work on the same model type
  90. rules_to_remove.setdefault(
  91. rule.id, main_records.browse()
  92. ).update(to_remove)
  93. rules_to_add.setdefault(
  94. rule.id, main_records.browse()
  95. ).update(to_add)
  96. if records_with_exception:
  97. all_exception_ids.append(rule.id)
  98. # Cumulate all the records to attach to the rule
  99. # before linking. We don't want to call "rule.write()"
  100. # which would:
  101. # * write on write_date so lock the expection.rule
  102. # * trigger the recomputation of "main_exception_id" on
  103. # all the sale orders related to the rule, locking them all
  104. # and preventing concurrent writes
  105. # Reversing the write by writing on SaleOrder instead of
  106. # ExceptionRule fixes the 2 kinds of unexpected locks.
  107. # It should not result in more queries than writing on ExceptionRule:
  108. # the "to remove" part generates one DELETE per rule on the relation
  109. # table
  110. # and the "to add" part generates one INSERT (with unnest) per rule.
  111. for rule_id, records in rules_to_remove.items():
  112. records.write({'exception_ids': [(3, rule_id,)]})
  113. for rule_id, records in rules_to_add.items():
  114. records.write(({'exception_ids': [(4, rule_id,)]}))
  115. return all_exception_ids
  116. @api.model
  117. def _exception_rule_eval_context(self, rec):
  118. return {
  119. 'time': time,
  120. 'self': rec,
  121. # object, obj: deprecated.
  122. # should be removed in future migrations
  123. 'object': rec,
  124. 'obj': rec,
  125. # copy context to prevent side-effects of eval
  126. # should be deprecated too, accesible through self.
  127. 'context': self.env.context.copy()
  128. }
  129. @api.model
  130. def _rule_eval(self, rule, rec):
  131. expr = rule.code
  132. space = self._exception_rule_eval_context(rec)
  133. try:
  134. safe_eval(expr,
  135. space,
  136. mode='exec',
  137. nocopy=True) # nocopy allows to return 'result'
  138. except Exception as e:
  139. raise UserError(
  140. _('Error when evaluating the exception.rule '
  141. 'rule:\n %s \n(%s)') % (rule.name, e))
  142. return space.get('failed', False)
  143. @api.multi
  144. def _detect_exceptions(self, rule):
  145. if rule.exception_type == 'by_py_code':
  146. return self._detect_exceptions_by_py_code(rule)
  147. elif rule.exception_type == 'by_domain':
  148. return self._detect_exceptions_by_domain(rule)
  149. @api.multi
  150. def _get_base_domain(self):
  151. return [('ignore_exception', '=', False), ('id', 'in', self.ids)]
  152. @api.multi
  153. def _detect_exceptions_by_py_code(self, rule):
  154. """
  155. Find exceptions found on self.
  156. """
  157. domain = self._get_base_domain()
  158. records = self.search(domain)
  159. records_with_exception = self.env[self._name]
  160. for record in records:
  161. if self._rule_eval(rule, record):
  162. records_with_exception |= record
  163. return records_with_exception
  164. @api.multi
  165. def _detect_exceptions_by_domain(self, rule):
  166. """
  167. Find exceptions found on self.
  168. """
  169. base_domain = self._get_base_domain()
  170. rule_domain = rule._get_domain()
  171. domain = osv.expression.AND([base_domain, rule_domain])
  172. return self.search(domain)
  173. class BaseException(models.AbstractModel):
  174. _inherit = 'base.exception.method'
  175. _name = 'base.exception'
  176. _order = 'main_exception_id asc'
  177. _description = 'Exception'
  178. main_exception_id = fields.Many2one(
  179. 'exception.rule',
  180. compute='_compute_main_error',
  181. string='Main Exception',
  182. store=True,
  183. )
  184. exceptions_summary = fields.Html(
  185. 'Exceptions Summary',
  186. compute='_compute_exceptions_summary',
  187. )
  188. exception_ids = fields.Many2many(
  189. 'exception.rule',
  190. string='Exceptions',
  191. copy=False,
  192. )
  193. ignore_exception = fields.Boolean('Ignore Exceptions', copy=False)
  194. @api.multi
  195. def action_ignore_exceptions(self):
  196. self.write({'ignore_exception': True})
  197. return True
  198. @api.depends('exception_ids', 'ignore_exception')
  199. def _compute_main_error(self):
  200. for rec in self:
  201. if not rec.ignore_exception and rec.exception_ids:
  202. rec.main_exception_id = rec.exception_ids[0]
  203. else:
  204. rec.main_exception_id = False
  205. @api.depends('exception_ids', 'ignore_exception')
  206. def _compute_exceptions_summary(self):
  207. for rec in self:
  208. if rec.exception_ids and not rec.ignore_exception:
  209. rec.exceptions_summary = '<ul>%s</ul>' % ''.join([
  210. '<li>%s: <i>%s</i></li>' % tuple(map(html.escape, (
  211. e.name, e.description))) for e in rec.exception_ids])
  212. @api.multi
  213. def _popup_exceptions(self):
  214. action = self._get_popup_action().read()[0]
  215. action.update({
  216. 'context': {
  217. 'active_id': self.ids[0],
  218. 'active_ids': self.ids,
  219. 'active_model': self._name,
  220. }
  221. })
  222. return action
  223. @api.model
  224. def _get_popup_action(self):
  225. return self.env.ref('base_exception.action_exception_rule_confirm')
  226. @api.multi
  227. def _check_exception(self):
  228. """
  229. This method must be used in a constraint that must be created in the
  230. object that inherits for base.exception.
  231. for sale :
  232. @api.constrains('ignore_exception',)
  233. def sale_check_exception(self):
  234. ...
  235. ...
  236. self._check_exception
  237. """
  238. exception_ids = self.detect_exceptions()
  239. if exception_ids:
  240. exceptions = self.env['exception.rule'].browse(exception_ids)
  241. raise ValidationError('\n'.join(exceptions.mapped('name')))