diff --git a/pypika/dialects.py b/pypika/dialects.py index 6e151d68..d7c75132 100644 --- a/pypika/dialects.py +++ b/pypika/dialects.py @@ -543,10 +543,12 @@ def _on_conflict_action_sql(self, **kwargs: Any) -> str: updates = [] for field, value in self._on_conflict_do_updates: if value: + value_get_sql_kwargs = kwargs.copy() + value_get_sql_kwargs['with_namespace'] = True updates.append( "{field}={value}".format( field=field.get_sql(**kwargs), - value=value.get_sql(with_namespace=True, **kwargs), + value=value.get_sql(**value_get_sql_kwargs), ) ) else: @@ -559,8 +561,10 @@ def _on_conflict_action_sql(self, **kwargs: Any) -> str: action_sql = " DO UPDATE SET {updates}".format(updates=",".join(updates)) if self._on_conflict_do_update_wheres: + wheres_get_sql_kwargs = kwargs.copy() + wheres_get_sql_kwargs['with_namespace'] = True action_sql += " WHERE {where}".format( - where=self._on_conflict_do_update_wheres.get_sql(subquery=True, with_namespace=True, **kwargs) + where=self._on_conflict_do_update_wheres.get_sql(subquery=True, **wheres_get_sql_kwargs) ) return action_sql diff --git a/pypika/tests/test_inserts.py b/pypika/tests/test_inserts.py index f86efd7a..536edddf 100644 --- a/pypika/tests/test_inserts.py +++ b/pypika/tests/test_inserts.py @@ -399,6 +399,41 @@ def test_where_and_on_conflict_where(self): str(qs), ) + def test_with_statement_and_on_conflict_do_update(self): + sub_query = ( + PostgreSQLQuery.into(self.table_abc) + .insert(1, "m") + .on_conflict("id") + .do_update("name", "m") + ) + + test_query = Query.with_(sub_query, "an_alias").from_(AliasedQuery("an_alias")).select("*") + + self.assertEqual( + 'WITH an_alias AS ' + '(INSERT INTO "abc" VALUES (1,\'m\') ON CONFLICT ("id") DO UPDATE SET "name"=\'m\') ' + 'SELECT * FROM an_alias', + str(test_query), + ) + + def test_with_statement_and_on_conflict_do_update_where(self): + sub_query = ( + PostgreSQLQuery.into(self.table_abc) + .insert(1, "m") + .on_conflict("id") + .do_update("name", "m") + .where(self.table_abc.id.eq(0)) + ) + + test_query = Query.with_(sub_query, "an_alias").from_(AliasedQuery("an_alias")).select("*") + + self.assertEqual( + 'WITH an_alias AS ' + '(INSERT INTO "abc" VALUES (1,\'m\') ON CONFLICT ("id") DO UPDATE SET "name"=\'m\' WHERE "abc"."id"=0) ' + 'SELECT * FROM an_alias', + str(test_query), + ) + def test_on_conflict_do_nothing_where(self): with self.assertRaises(QueryException): (