Cédric Krier pushed to branch branch/default at Tryton / Tryton


Commits:
1f462acb by Cédric Krier at 2023-01-30T14:54:07+01:00
Enforce unique creation of singleton with lock and constraint

Closes #10748
- - - - -


2 changed files:

- trytond/trytond/ir/message.xml
- trytond/trytond/model/modelsingleton.py


Changes:

=====================================
trytond/trytond/ir/message.xml
=====================================
@@ -136,6 +136,9 @@
         <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>


=====================================
trytond/trytond/model/modelsingleton.py
=====================================
@@ -1,5 +1,7 @@
 # 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
 
@@ -4,5 +6,6 @@
 from trytond.transaction import Transaction, without_check_access
 
+from .modelsql import Exclude, ModelSQL
 from .modelstorage import ModelStorage
 
 
@@ -17,6 +20,12 @@
         # 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 @@
         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]



View it on Heptapod: 
https://foss.heptapod.net/tryton/tryton/-/commit/1f462acb3b5578a5b885d263f64006911bd3dc07

-- 
View it on Heptapod: 
https://foss.heptapod.net/tryton/tryton/-/commit/1f462acb3b5578a5b885d263f64006911bd3dc07
You're receiving this email because of your account on foss.heptapod.net.


Reply via email to