PyPika is a python SQL query builder that exposes the full richness of the SQL language using a syntax that reflects the resulting query. PyPika excels at all sorts of SQL queries but is especially useful for data analysis.
from pypika import *
# setup
t1 = Table('t1')
q1 = Query.from_(t1).select(t1.id)
a = AliasedQuery('test')
# broken query
broken_q = PostgreSQLQuery.with_(q1, 'test').delete().using(a).where(t1.id == a.id)
>>> str(broken_q)
'DELETE USING test WHERE "t1"."id"="test"."id"'
# working query
ok_q = PostgreSQLQuery.with_(q1, 'test').select(a.id).from_(a).where(t1.id == a.id)
>>> str(ok_q)
'WITH test AS (SELECT "id" FROM "t1") SELECT "test"."id" FROM test WHERE "t1"."id"="test"."id"'
expected output (hand written sql i'm converting to pika):
WITH tag AS (SELECT id FROM tags WHERE name=$1),
implied_tag AS (SELECT id FROM tags WHERE name=$2)
DELETE FROM tag_implications USING tag, implied_tag
WHERE tag_id=tag.id AND implied_tag_id=implied_tag.id;
simplified reproduction
"real life" use case
(just in case i'm using it wrong)
expected output (hand written sql i'm converting to pika):