Skip to content

Commit 0f11228

Browse files
committed
fix(cursor, write_dataframe): respect paramstyle
1 parent df7fc1d commit 0f11228

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

redshift_connector/cursor.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -555,7 +555,7 @@ def __is_valid_table(self: "Cursor", table: str) -> bool:
555555

556556
def write_dataframe(self: "Cursor", df: "pandas.DataFrame", table: str) -> None:
557557
"""
558-
Inserts a :class:`pandas.DataFrame` into an table within the current database.
558+
Inserts a :class:`pandas.DataFrame` into a table within the current database.
559559
560560
Parameters
561561
----------
@@ -579,10 +579,21 @@ def write_dataframe(self: "Cursor", df: "pandas.DataFrame", table: str) -> None:
579579
sql: str = "insert into {table} values ({placeholder})".format(
580580
table=sanitized_table_name, placeholder=placeholder
581581
)
582-
if len(arrays) == 1:
583-
self.execute(sql, arrays[0])
584-
elif len(arrays) > 1:
585-
self.executemany(sql, arrays)
582+
cursor_paramstyle: str = self.paramstyle
583+
try:
584+
# force using FORMAT i.e. %s paramstyle for the current statement, then revert the
585+
# cursor to use the cursor's original paramstyle
586+
self.paramstyle = DbApiParamstyle.FORMAT.value
587+
if len(arrays) == 1:
588+
self.execute(sql, arrays[0])
589+
elif len(arrays) > 1:
590+
self.executemany(sql, arrays)
591+
except:
592+
raise InterfaceError(
593+
"An error occurred when attempting to insert the pandas.DataFrame into ${}".format(table)
594+
)
595+
finally:
596+
self.paramstyle = cursor_paramstyle
586597

587598
def fetch_numpy_array(self: "Cursor", num: typing.Optional[int] = None) -> "numpy.ndarray":
588599
"""

test/integration/test_pandas.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import pytest # type: ignore
55

66
import redshift_connector
7+
from redshift_connector.config import DbApiParamstyle
78

89
# Tests relating to the pandas and numpy operation of the database driver
910
# redshift_connector custom interface.
@@ -58,7 +59,8 @@ def test_fetch_dataframe(db_table):
5859

5960

6061
@pandas_only
61-
def test_write_dataframe(db_table):
62+
@pytest.mark.parametrize("paramstyle", DbApiParamstyle.list())
63+
def test_write_dataframe(db_table, paramstyle):
6264
import numpy as np
6365
import pandas as pd
6466

@@ -71,12 +73,16 @@ def test_write_dataframe(db_table):
7173
),
7274
columns=["bookname", "author‎"],
7375
)
76+
db_table.paramstyle = paramstyle
77+
7478
with db_table.cursor() as cursor:
7579
cursor.write_dataframe(df, "book")
7680
cursor.execute("select * from book; ")
7781
result = cursor.fetchall()
7882
assert len(np.array(result)) == 2
7983

84+
assert db_table.paramstyle == paramstyle
85+
8086

8187
@numpy_only
8288
def test_fetch_numpyarray(db_table):

0 commit comments

Comments
 (0)