From 3167376de23bb5d2cde657cef76a1485cd1b9dde Mon Sep 17 00:00:00 2001 From: Edvard Majakari Date: Mon, 26 Feb 2024 17:02:30 +0200 Subject: [PATCH] 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 --- pypika/queries.py | 6 +++--- pypika/tests/test_inserts.py | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/pypika/queries.py b/pypika/queries.py index 96a2cc20..d5042bc6 100644 --- a/pypika/queries.py +++ b/pypika/queries.py @@ -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 diff --git a/pypika/tests/test_inserts.py b/pypika/tests/test_inserts.py index d838f920..49071721 100644 --- a/pypika/tests/test_inserts.py +++ b/pypika/tests/test_inserts.py @@ -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")