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.

292 lines
10 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
[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. )
  105. rules_to_remove[rule.id] |= to_remove
  106. rules_to_add.setdefault(
  107. rule.id, main_records.browse()
  108. )
  109. rules_to_add[rule.id] |= to_add
  110. if records_with_exception:
  111. all_exception_ids.append(rule.id)
  112. # Cumulate all the records to attach to the rule
  113. # before linking. We don't want to call "rule.write()"
  114. # which would:
  115. # * write on write_date so lock the expection.rule
  116. # * trigger the recomputation of "main_exception_id" on
  117. # all the sale orders related to the rule, locking them all
  118. # and preventing concurrent writes
  119. # Reversing the write by writing on SaleOrder instead of
  120. # ExceptionRule fixes the 2 kinds of unexpected locks.
  121. # It should not result in more queries than writing on ExceptionRule:
  122. # the "to remove" part generates one DELETE per rule on the relation
  123. # table and the "to add" part generates one INSERT (with unnest) per
  124. # rule.
  125. for rule_id, records in rules_to_remove.iteritems():
  126. records.write({'exception_ids': [(3, rule_id,)]})
  127. for rule_id, records in rules_to_add.iteritems():
  128. records.write(({'exception_ids': [(4, rule_id,)]}))
  129. return all_exception_ids
  130. @api.model
  131. def _exception_rule_eval_context(self, rec):
  132. return {'self': self.pool.get(rec._name),
  133. 'object': rec,
  134. 'obj': rec,
  135. 'pool': self.pool,
  136. 'env': self.env,
  137. 'cr': self.env.cr,
  138. 'uid': self.env.uid,
  139. 'user': self.env.user,
  140. 'time': time,
  141. # copy context to prevent side-effects of eval
  142. 'context': self.env.context.copy()}
  143. @api.model
  144. def _rule_eval(self, rule, rec):
  145. expr = rule.code
  146. space = self._exception_rule_eval_context(rec)
  147. try:
  148. safe_eval(expr,
  149. space,
  150. mode='exec',
  151. nocopy=True) # nocopy allows to return 'result'
  152. except Exception, e:
  153. raise UserError(
  154. _('Error when evaluating the exception.rule '
  155. 'rule:\n %s \n(%s)') % (rule.name, e))
  156. return space.get('failed', False)
  157. @api.multi
  158. def _detect_exceptions(self, rule):
  159. if rule.exception_type == 'by_py_code':
  160. return self._detect_exceptions_by_py_code(rule)
  161. elif rule.exception_type == 'by_domain':
  162. return self._detect_exceptions_by_domain(rule)
  163. @api.multi
  164. def _get_base_domain(self):
  165. return [('ignore_exception', '=', False), ('id', 'in', self.ids)]
  166. @api.multi
  167. def _detect_exceptions_by_py_code(self, rule):
  168. """
  169. Find exceptions found on self.
  170. """
  171. domain = self._get_base_domain()
  172. records = self.search(domain)
  173. records_with_exception = self.env[self._name]
  174. for record in records:
  175. if self._rule_eval(rule, record):
  176. records_with_exception |= record
  177. return records_with_exception
  178. @api.multi
  179. def _detect_exceptions_by_domain(self, rule):
  180. """
  181. Find exceptions found on self.
  182. """
  183. base_domain = self._get_base_domain()
  184. rule_domain = rule._get_domain()
  185. domain = osv.expression.AND([base_domain, rule_domain])
  186. return self.search(domain)
  187. class BaseException(models.AbstractModel):
  188. _inherit = 'base.exception.method'
  189. _name = 'base.exception'
  190. _order = 'main_exception_id asc'
  191. main_exception_id = fields.Many2one(
  192. 'exception.rule',
  193. compute='_compute_main_error',
  194. string='Main Exception',
  195. store=True)
  196. exception_ids = fields.Many2many(
  197. 'exception.rule',
  198. string='Exceptions')
  199. ignore_exception = fields.Boolean('Ignore Exceptions', copy=False)
  200. @api.depends('exception_ids', 'ignore_exception')
  201. def _compute_main_error(self):
  202. for obj in self:
  203. if not obj.ignore_exception and obj.exception_ids:
  204. obj.main_exception_id = obj.exception_ids[0]
  205. else:
  206. obj.main_exception_id = False
  207. @api.multi
  208. def _popup_exceptions(self):
  209. action = self._get_popup_action()
  210. action = action.read()[0]
  211. action.update({
  212. 'context': {
  213. 'active_model': self._name,
  214. 'active_id': self.ids[0],
  215. 'active_ids': self.ids
  216. }
  217. })
  218. return action
  219. @api.model
  220. def _get_popup_action(self):
  221. action = self.env.ref('base_exception.action_exception_rule_confirm')
  222. return action
  223. @api.multi
  224. def _check_exception(self):
  225. """
  226. This method must be called in the create and write methods of the model
  227. using exceptions. The model has to inherit from 'base.exception'.
  228. Example for sale (used in OCA/sale-workflow/sale_exception):
  229. def _fields_trigger_check_exception(self):
  230. return ['ignore_exception', 'order_line', 'state']
  231. @api.model
  232. def create(self, vals):
  233. record = super(SaleOrder, self).create(vals)
  234. check_exceptions = any(
  235. field in vals for field
  236. in self._fields_trigger_check_exception()
  237. )
  238. if check_exceptions:
  239. record.sale_check_exception()
  240. return record
  241. @api.multi
  242. def write(self, vals):
  243. result = super(SaleOrder, self).write(vals)
  244. check_exceptions = any(
  245. field in vals for field
  246. in self._fields_trigger_check_exception()
  247. )
  248. if check_exceptions:
  249. self.sale_check_exception()
  250. return result
  251. def sale_check_exception(self):
  252. orders = self.filtered(lambda s: s.state == 'sale')
  253. if orders:
  254. orders._check_exception()
  255. """
  256. exception_ids = self.detect_exceptions()
  257. if exception_ids:
  258. exceptions = self.env['exception.rule'].browse(exception_ids)
  259. raise ValidationError('\n'.join(exceptions.mapped('name')))