Skip to content

Commit

Permalink
make insert_dict() api less confusing
Browse files Browse the repository at this point in the history
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
  • Loading branch information
edvardm committed Feb 26, 2024
1 parent 1d8b141 commit 3167376
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
6 changes: 3 additions & 3 deletions pypika/queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -907,10 +907,10 @@ def insert(self, *terms: Any) -> "QueryBuilder":
self._replace = False

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

cols = data.keys()
builder = self.columns(*cols).insert(*data.values())
builder._using_insert_dict = True
return builder
Expand Down
10 changes: 5 additions & 5 deletions pypika/tests/test_inserts.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,12 @@ def test_inserting_dictionary_produces_builder(self):
q = q.insert(2, datetime(2023, 4, 19))
self.assertEqual("INSERT INTO \"abc\" (\"num\",\"timestamp\") VALUES (1,'2023-04-18T00:00:00'),(2,'2023-04-19T00:00:00')", str(q))

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

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

class PostgresInsertIntoOnConflictTests(unittest.TestCase):
table_abc = Table("abc")
Expand Down

0 comments on commit 3167376

Please sign in to comment.