Enforce unique creation of singleton with lock and constraint
Closes #10748
This commit is contained in:
1 parent
f3489dc20c
commit
cebf486f6f
2 files changed
+14
No files matched your search
@@ -136,6 +136,9 @@ this repository contains the full copyright notices and license terms. -->
|
||||
<record model="ir.message" id="msg_id_positive">
|
||||
<field name="text">ID must be positive.</field>
|
||||
</record>
|
||||
<record model="ir.message" id="msg_singleton">
|
||||
<field name="text">Only one singleton can be created.</field>
|
||||
</record>
|
||||
<record model="ir.message" id="msg_write_xml_record">
|
||||
<field name="text">You are not allowed to modify the field "%(field)s" in "%(record)s" of "%(model)s".</field>
|
||||
</record>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
# This file is part of Tryton. The COPYRIGHT file at the top level of
|
||||
# this repository contains the full copyright notices and license terms.
|
||||
|
||||
from sql.operators import Equal
|
||||
|
||||
from trytond.transaction import Transaction, without_check_access
|
||||
|
||||
from .modelsql import Exclude, ModelSQL
|
||||
from .modelstorage import ModelStorage
|
||||
|
||||
|
||||
@@ -17,6 +20,12 @@ class ModelSingleton(ModelStorage):
|
||||
# Cache disable because it is used as a read by the client
|
||||
cls.__rpc__['default_get'].cache = None
|
||||
|
||||
if issubclass(cls, ModelSQL):
|
||||
table = cls.__table__()
|
||||
cls._sql_constraints.append(
|
||||
('singleton', Exclude(table, (table.id * 0, Equal)),
|
||||
'ir.msg_singleton'))
|
||||
|
||||
@classmethod
|
||||
def get_singleton(cls):
|
||||
'''
|
||||
@@ -31,6 +40,8 @@ class ModelSingleton(ModelStorage):
|
||||
assert len(vlist) == 1
|
||||
singleton = cls.get_singleton()
|
||||
if not singleton:
|
||||
if issubclass(cls, ModelSQL):
|
||||
cls.lock()
|
||||
return super(ModelSingleton, cls).create(vlist)
|
||||
cls.write([singleton], vlist[0])
|
||||
return [singleton]
|
||||
|
||||
Reference in new issue
Block a user