diff options
| author | Jeremy Kersten <jke@odoo.com> | 2020-09-25 15:06:36 +0000 |
|---|---|---|
| committer | Jeremy Kersten <jke@odoo.com> | 2020-09-28 13:38:28 +0000 |
| commit | d92e61e89f468c2db2fbd68b2f0d6b36c77f1065 (patch) | |
| tree | 020b14bfc941cfc3bd4556704958433c731ea2cc /odoo/tools/sql.py | |
| parent | 1c9370e572b9da4201a89d1f17f83c8f8f991a5a (diff) | |
[FIX] tools.sql, website_*: increment counter with skip lock
*blog, forum, slides
Based on https://github.com/odoo/odoo/pull/48552#discussion_r440061218 suggestion
Add a new method 'increment_skip_lock' in tools.sql to allow to easily
increment a specific field of 1 if the record is not locked.
The method return boolean if at least 1 record has been incremented.
closes odoo/odoo#58534
Signed-off-by: Jérémy Kersten (jke) <jke@openerp.com>
Diffstat (limited to 'odoo/tools/sql.py')
| -rw-r--r-- | odoo/tools/sql.py | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/odoo/tools/sql.py b/odoo/tools/sql.py index 69968f78de8..fc3d6f5524e 100644 --- a/odoo/tools/sql.py +++ b/odoo/tools/sql.py @@ -253,3 +253,27 @@ def reverse_order(order): direction = 'asc' if item[1:] == ['desc'] else 'desc' items.append('%s %s' % (item[0], direction)) return ', '.join(items) + + +def increment_field_skiplock(record, field): + """ + Increment 'friendly' the [field] of the current [record](s) + If record is locked, we just skip the update. + It doesn't invalidate the cache since the update is not critical. + + :rtype: bool - if field has been incremented or not + """ + if not record: + return False + + assert record._fields[field].type == 'integer' + + cr = record._cr + query = """ + UPDATE {table} SET {field} = {field} + 1 WHERE id IN ( + SELECT id from {table} WHERE id in %(ids)s FOR UPDATE SKIP LOCKED + ) RETURNING id + """.format(table=record._table, field=field) + cr.execute(query, {'ids': tuple(record.ids)}) + + return bool(cr.fetchone()) |
