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.

264 lines
9.5 KiB

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