Skip to content

Commit 3167376

Browse files
committed
make insert_dict() api less confusing
in SQL builders, order of calling individual functions should not matter. Originally it was allowed to first call columns() and then insert_dict as long as the two matched, but I'm not even sure it worked, as we should have used set comparison instead. It is also better to have symmetric API in
1 parent 1d8b141 commit 3167376

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

pypika/queries.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -907,10 +907,10 @@ def insert(self, *terms: Any) -> "QueryBuilder":
907907
self._replace = False
908908

909909
def insert_dict(self, data: Dict[str, Any]) -> "QueryBuilder":
910-
cols = data.keys()
911-
if self._columns and self._columns != cols:
912-
raise QueryException("Current columns differs from columns in keys")
910+
if self._columns:
911+
raise QueryException("Cannot mix use of columns() and insert_dict()")
913912

913+
cols = data.keys()
914914
builder = self.columns(*cols).insert(*data.values())
915915
builder._using_insert_dict = True
916916
return builder

pypika/tests/test_inserts.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,12 @@ def test_inserting_dictionary_produces_builder(self):
185185
q = q.insert(2, datetime(2023, 4, 19))
186186
self.assertEqual("INSERT INTO \"abc\" (\"num\",\"timestamp\") VALUES (1,'2023-04-18T00:00:00'),(2,'2023-04-19T00:00:00')", str(q))
187187

188-
def test_columns_is_not_allowed_with_insert_dict(self):
189-
with self.assertRaises(QueryException):
190-
Query.into(self.table_abc).columns("a", "b").insert_dict({"num": 1})
188+
def test_columns_is_not_allowed_with_insert_dict_even_with_matching_columns(self):
189+
with self.assertRaisesRegex(QueryException, "Cannot mix use of columns.*and insert_dict"):
190+
Query.into(self.table_abc).columns("num", "key").insert_dict({"num": 1, "key": "foo"})
191191

192-
with self.assertRaises(QueryException):
193-
Query.into(self.table_abc).insert_dict({"num": 1}).columns("a", "b")
192+
with self.assertRaisesRegex(QueryException, "Cannot mix use of columns.*and insert_dict"):
193+
Query.into(self.table_abc).insert_dict({"num": 1, "key": "foo"}).columns("num", "key")
194194

195195
class PostgresInsertIntoOnConflictTests(unittest.TestCase):
196196
table_abc = Table("abc")

0 commit comments

Comments
 (0)