Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion src/crate/client/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,37 @@ def _replace(match: "re.Match[str]") -> str:
return converted_sql, new_params


def _convert_named_bulk_params(
sql: str, seq_of_dicts: t.Sequence[t.Dict[str, t.Any]]
) -> t.Tuple[str, t.List[t.List[t.Any]]]:
"""Convert pyformat SQL and a sequence of dicts to positional bulk args.

Uses the first row to determine the SQL template and position map, then
builds a positional argument list for every row.

Raises ``ProgrammingError`` if a placeholder name is absent from any row.
Extra keys in each row are silently ignored (consistent with
``_convert_named_to_positional``).
"""
first = seq_of_dicts[0]
converted_sql, _ = _convert_named_to_positional(sql, first)
positions = {k: i + 1 for i, k in enumerate(first)}
n = len(positions)

bulk_args: t.List[t.List[t.Any]] = []
for row in seq_of_dicts:
positional: t.List[t.Any] = [None] * n
for name, pos in positions.items():
if name not in row:
raise ProgrammingError(
f"Named parameter '{name}' not found in the parameters dict"
)
positional[pos - 1] = row[name]
bulk_args.append(positional)

return converted_sql, bulk_args


class Cursor:
"""
not thread-safe by intention
Expand Down Expand Up @@ -118,7 +149,16 @@ def executemany(self, sql, seq_of_parameters):
"""
row_counts = []
durations = []
self.execute(sql, bulk_parameters=seq_of_parameters)
bulk_parameters = seq_of_parameters
if (
bulk_parameters
and isinstance(bulk_parameters[0], dict)
and _NAMED_PARAM_RE.search(sql)
Comment on lines +155 to +156
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if there is a mix of dict/non-dict args?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

currently we raise an error. Do we have case to use mix of dict/non-dict together? I couldn't find how server handle that. What it should do?

):
sql, bulk_parameters = _convert_named_bulk_params(
sql, bulk_parameters
)
self.execute(sql, bulk_parameters=bulk_parameters)

for result in self._result.get("results", []):
if result.get("rowcount") > -1:
Expand Down
47 changes: 47 additions & 0 deletions tests/client/test_cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,53 @@ def test_cursor_executemany(mocked_connection):
assert response["results"] == result


def test_executemany_with_named_params(mocked_connection):
"""
Verify that executemany() translates pyformat %(name)s placeholders to
positional $N markers and converts each dict row to a positional list.

"""
response = {
"col_types": [],
"cols": [],
"duration": 123,
"results": [{"rowcount": 1}, {"rowcount": 1}],
}
with mock.patch.object(
mocked_connection.client, "sql", return_value=response
):
cursor = mocked_connection.cursor()
cursor.executemany(
"INSERT INTO characters (name, age) VALUES (%(name)s, %(age)s)",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also add a case where one named argument is used multiple times and check that it gets the same position number?

[
{"name": "Arthur", "age": 42},
{"name": "Bill", "age": 35},
],
)
sql, _params, bulk_args = mocked_connection.client.sql.call_args[0]
assert sql == "INSERT INTO characters (name, age) VALUES ($1, $2)"
assert bulk_args == [["Arthur", 42], ["Bill", 35]]


def test_executemany_with_named_params_missing_key(mocked_connection):
"""
Verify that executemany() raises ProgrammingError when a row is missing a
key that appears as a placeholder in the SQL.
"""
cursor = mocked_connection.cursor()
with pytest.raises(
ProgrammingError, match="Named parameter 'age' not found"
):
cursor.executemany(
"INSERT INTO characters (name, age) VALUES (%(name)s, %(age)s)",
[
{"name": "Arthur", "age": 42},
{"name": "Bill"}, # missing 'age'
],
)
mocked_connection.client.sql.assert_not_called()


def test_create_with_timezone_as_datetime_object(mocked_connection):
"""
The cursor can return timezone-aware `datetime` objects when requested.
Expand Down
Loading