From 515c827073ea5088dac48d7764feb57841291255 Mon Sep 17 00:00:00 2001 From: Erez Shinan Date: Fri, 28 Oct 2022 10:40:21 -0300 Subject: [PATCH] Queries: Added Param mechanism, to help speed up query construction. --- data_diff/queries/ast_classes.py | 13 ++++++++++++- data_diff/queries/compiler.py | 10 +++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/data_diff/queries/ast_classes.py b/data_diff/queries/ast_classes.py index 88d7ab114..c283f3486 100644 --- a/data_diff/queries/ast_classes.py +++ b/data_diff/queries/ast_classes.py @@ -6,7 +6,7 @@ from data_diff.utils import ArithString, join_iter -from .compiler import Compilable, Compiler +from .compiler import Compilable, Compiler, cv_params from .base import SKIP, CompileError, DbPath, Schema, args_as_tuple @@ -38,6 +38,17 @@ def _expr_type(e: Expr) -> type: return type(e) +@dataclass +class Param(Compilable): + """A value placeholder, to be specified at compilation time using the `cv_params` context variable.""" + + name: str + + def compile(self, c: Compiler) -> str: + params = cv_params.get() + return c._compile(params[self.name]) + + @dataclass class Alias(ExprNode): expr: Expr diff --git a/data_diff/queries/compiler.py b/data_diff/queries/compiler.py index 312421319..e9a66bed1 100644 --- a/data_diff/queries/compiler.py +++ b/data_diff/queries/compiler.py @@ -8,10 +8,15 @@ from data_diff.utils import ArithString from data_diff.databases.database_types import AbstractDialect, DbPath +import contextvars + +cv_params = contextvars.ContextVar("params") + @dataclass class Compiler: database: AbstractDialect + params: dict = {} in_select: bool = False # Compilation runtime flag in_join: bool = False # Compilation runtime flag @@ -21,7 +26,10 @@ class Compiler: _counter: List = [0] - def compile(self, elem) -> str: + def compile(self, elem, params=None) -> str: + if params: + cv_params.set(params) + res = self._compile(elem) if self.root and self._subqueries: subq = ", ".join(f"\n {k} AS ({v})" for k, v in self._subqueries.items())