From 92db2a096b68d79e1b8d0ec4fa08e0efbd46700a Mon Sep 17 00:00:00 2001 From: Federico Caselli Date: Tue, 6 Oct 2020 21:21:46 +0200 Subject: Handle case where InstanceState.obj returns None Fixed bug where a call ``InstanceState.obj()`` could return None when synchronizing the instance states of the objects in the session in case they become out of scope but are not yet finalized by the gc. This case does not happen in cPython, but it may present itself in pypy. The approach is to allow None to be gracefully handled by the evaluator itself, ensuring it returns None in all cases when None is passed in. Fixes: #5631 Change-Id: I53d38fbea2e72b2e677c6e7f70bf075a58e58945 --- lib/sqlalchemy/orm/evaluator.py | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) (limited to 'lib/sqlalchemy') diff --git a/lib/sqlalchemy/orm/evaluator.py b/lib/sqlalchemy/orm/evaluator.py index f7f12ce12..23c48329d 100644 --- a/lib/sqlalchemy/orm/evaluator.py +++ b/lib/sqlalchemy/orm/evaluator.py @@ -17,6 +17,16 @@ class UnevaluatableError(Exception): pass +class _NoObject(operators.ColumnOperators): + def operate(self, *arg, **kw): + return None + + def reverse_operate(self, *arg, **kw): + return None + + +_NO_OBJECT = _NoObject() + _straight_ops = set( getattr(operators, op) for op in ( @@ -36,8 +46,10 @@ _straight_ops = set( ) _extended_ops = { - operators.in_op: (lambda a, b: a in b), - operators.not_in_op: (lambda a, b: a not in b), + operators.in_op: (lambda a, b: a in b if a is not _NO_OBJECT else None), + operators.not_in_op: ( + lambda a, b: a not in b if a is not _NO_OBJECT else None + ), } _notimplemented_ops = set( @@ -111,7 +123,11 @@ class EvaluatorCompiler(object): raise UnevaluatableError("Cannot evaluate column: %s" % clause) get_corresponding_attr = operator.attrgetter(key) - return lambda obj: get_corresponding_attr(obj) + return ( + lambda obj: get_corresponding_attr(obj) + if obj is not None + else _NO_OBJECT + ) def visit_tuple(self, clause): return self.visit_clauselist(clause) @@ -137,7 +153,7 @@ class EvaluatorCompiler(object): for sub_evaluate in evaluators: value = sub_evaluate(obj) if not value: - if value is None: + if value is None or value is _NO_OBJECT: return None return False return True @@ -148,7 +164,7 @@ class EvaluatorCompiler(object): values = [] for sub_evaluate in evaluators: value = sub_evaluate(obj) - if value is None: + if value is None or value is _NO_OBJECT: return None values.append(value) return tuple(values) -- cgit v1.2.1