Skip to content

Commit a86abd3

Browse files
author
Jesse Whitehouse
committed
Simplify implementation by using string interpolation rather than regex
Signed-off-by: Jesse Whitehouse <jesse.whitehouse@databricks.com>
1 parent 272c7f7 commit a86abd3

File tree

2 files changed

+8
-17
lines changed

2 files changed

+8
-17
lines changed

src/databricks/sql/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,7 @@ def execute(
665665
operation, parameters
666666
)
667667
elif param_approach == ParameterApproach.NATIVE:
668-
transformed_operation = transform_paramstyle(operation)
668+
transformed_operation = transform_paramstyle(operation, parameters)
669669
prepared_operation, prepared_params = self._prepare_native_parameters(
670670
transformed_operation, parameters
671671
)

src/databricks/sql/utils.py

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import datetime
44
import decimal
5-
import re
65
from abc import ABC, abstractmethod
76
from collections import OrderedDict, namedtuple
87
from collections.abc import Iterable
@@ -388,34 +387,26 @@ def inject_parameters(operation: str, parameters: Dict[str, str]):
388387
return operation % parameters
389388

390389

391-
def transform_paramstyle(operation: str) -> str:
390+
def transform_paramstyle(operation: str, parameters: Dict[str, Any]) -> str:
392391
"""
393-
Performs a regex substitution such that any occurence of `%(param)s` will be replaced with `:param`
392+
Performs a Python string interpolation such that any occurence of `%(param)s` will be replaced with `:param`
394393
395394
This utility function is built to assist users in the transition between the default paramstyle in
396395
this connector prior to version 3.0.0 (`pyformat`) and the new default paramstyle (`named`).
397396
397+
This method will fail if parameters is passed as a list.
398+
398399
Args:
399400
operation (str): The operation or SQL text to transform.
401+
parameters (Dict[str, Any]): The parameters to use for the transformation.
400402
401403
Returns:
402404
str
403405
"""
404406

405-
_output_operation = operation
406-
407-
PYFORMAT_PARAMSTYLE_REGEX = r"%\((\w+)\)s"
408-
pat = re.compile(PYFORMAT_PARAMSTYLE_REGEX)
409-
NAMED_PARAMSTYLE_FMT = ":{}"
410-
PYFORMAT_PARAMSTYLE_FMT = "%({})s"
411-
412-
pyformat_markers = pat.findall(operation)
413-
for marker in pyformat_markers:
414-
pyformat_marker = PYFORMAT_PARAMSTYLE_FMT.format(marker)
415-
named_marker = NAMED_PARAMSTYLE_FMT.format(marker)
416-
_output_operation = _output_operation.replace(pyformat_marker, named_marker)
407+
interpolation_values = {key: f":{key}" for key in parameters.keys()}
417408

418-
return _output_operation
409+
return operation % interpolation_values
419410

420411

421412
def create_arrow_table_from_arrow_file(file_bytes: bytes, description) -> pyarrow.Table:

0 commit comments

Comments
 (0)