pypika icon indicating copy to clipboard operation
pypika copied to clipboard

Searching in Arrays

Open Apexal opened this issue 3 years ago • 1 comments

I would like to search for a value in an array column (str[]). I am using PostgresSQL and the SQL format for such a query condition is WHERE 'value' = ANY(array_column_name) as documented here. After searching through the PyPika docs, and repo issues, I do not think this is implemented in PyPika. If so, how would I go about dropping in the raw SQL in the middle of a query builder to include such a condition?

For context, I want my final query to look something like:

SELECT * FROM projects WHERE ... AND 'python' = ANY(languages);

Where projects looks like:

project_id title languages
1 Example Project python, html, css

The closest I've gotten is trying to use a CustomFunction:

ARRAY_ANY = CustomFunction('ANY', ['column'])

query = Query.from_(proj_t) \
    .select("*") \
    .where("python" == ANY_SQL(proj_t.languages))

but this generates

SELECT * FROM "projects" WHERE ANY("languages")='python' ORDER BY "created_at"

with the order of ANY and 'python` reverse which is rejected as a syntax error!

Is there a way I can simply enforce the order of 'python' = ANY("languages")?

Apexal avatar Dec 26 '20 08:12 Apexal

This is an old issue but for anyone that comes across this looking for a solution you can use the following:

.where(pypika.terms.Term.wrap_constant("python") == ARRAY_ANY(proj_t.languages))

f11r avatar Apr 15 '22 06:04 f11r