Skip to content

Commit 0c14a1a

Browse files
committed
ENH/TST: Raise error if invalid value passed to if_exists argument
The if_exists argument in io.sql.write_frame needed data validation because the logic of the function implicitly used 'append' if the argument value was any string that was not either 'fail' or 'replace'. I added a new unit test to support the requirement.
1 parent e07dc19 commit 0c14a1a

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

pandas/io/sql.py

+4
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,10 @@ def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs):
196196
if_exists='append'
197197
else:
198198
if_exists='fail'
199+
200+
if if_exists not in ('fail', 'replace', 'append'):
201+
raise ValueError, "'%s' is not valid for if_exists" % if_exists
202+
199203
exists = table_exists(name, con, flavor)
200204
if if_exists == 'fail' and exists:
201205
raise ValueError, "Table '%s' already exists." % name

pandas/io/tests/test_sql.py

+18
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,24 @@ def test_onecolumn_of_integer(self):
240240
result = sql.read_frame("select * from mono_df",con_x)
241241
tm.assert_frame_equal(result,mono_df)
242242

243+
def test_if_exists(self):
244+
df_if_exists_1 = DataFrame({'col1': [1, 2], 'col2': ['A', 'B']})
245+
df_if_exists_2 = DataFrame({'col1': [3, 4, 5], 'col2': ['C', 'D', 'E']})
246+
table_name = 'table_if_exists'
247+
248+
# test if invalid value for if_exists raises appropriate error
249+
self.assertRaises(ValueError,
250+
sql.write_frame,
251+
frame=df_if_exists_1,
252+
con=self.db,
253+
name=table_name,
254+
flavor='sqlite',
255+
if_exists='notvalidvalue')
256+
if sql.table_exists(table_name, self.db, flavor='sqlite'):
257+
cur = self.db.cursor()
258+
cur.execute("DROP TABLE %s" % table_name)
259+
cur.close()
260+
243261

244262
class TestMySQL(unittest.TestCase):
245263

0 commit comments

Comments
 (0)