diff --git a/queue_job/job.py b/queue_job/job.py index b2d64c6d34..9610511927 100644 --- a/queue_job/job.py +++ b/queue_job/job.py @@ -13,9 +13,30 @@ from random import randint import odoo +from odoo.models import BaseModel from .exception import FailedJobError, NoSuchJobError, RetryableJobError + +def _rebind_to_cr(value, cr): + """Rebind any BaseModel inside ``value`` to the cursor ``cr``. + + Recurses into lists, tuples and dicts. Preserves uid/su/context of each + inner env - only the cursor is swapped. Recordsets already bound to + ``cr`` and non-recordset values pass through untouched. Containers are + rebuilt, so in-place changes to the result are lost. + """ + if isinstance(value, BaseModel): + if value.env.cr is cr: + return value + return value.with_env(value.env(cr=cr)) + if isinstance(value, (list, tuple)): + return type(value)(_rebind_to_cr(v, cr) for v in value) + if isinstance(value, dict): + return {k: _rebind_to_cr(v, cr) for k, v in value.items()} + return value + + WAIT_DEPENDENCIES = "wait_dependencies" PENDING = "pending" ENQUEUED = "enqueued" @@ -533,8 +554,8 @@ def perform(self): def in_temporary_env(self): with self.env.registry.cursor() as new_cr: env = self.env - self._env = env(cr=new_cr) try: + self._env = env(cr=new_cr) yield finally: self._env = env @@ -705,6 +726,24 @@ def env(self): def _env(self, env): self.recordset = self.recordset.with_env(env) + @property + def args(self): + """Positional arguments, rebound to the job's current cursor.""" + return _rebind_to_cr(self._args, self.env.cr) + + @args.setter + def args(self, value): + self._args = value + + @property + def kwargs(self): + """Keyword arguments, rebound to the job's current cursor.""" + return _rebind_to_cr(self._kwargs, self.env.cr) + + @kwargs.setter + def kwargs(self, value): + self._kwargs = value + @property def func(self): recordset = self.recordset.with_context(job_uuid=self.uuid) diff --git a/test_queue_job/data/queue_job_function_data.xml b/test_queue_job/data/queue_job_function_data.xml index 8338045141..c01903b0f3 100644 --- a/test_queue_job/data/queue_job_function_data.xml +++ b/test_queue_job/data/queue_job_function_data.xml @@ -20,6 +20,14 @@ job_with_retry_pattern__no_zero + + + job_commit_with_arg_records + +