kayak / pypika

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.
http://pypika.readthedocs.io/en/latest/
Apache License 2.0
2.43k stars 292 forks source link

:star: Improve parameterized query support - fixes #793 #794

Open mvanderlee opened 4 months ago

mvanderlee commented 4 months ago

Fixes #793 The implemented tests speak for themselves, but here is an extract:

subquery = (
    Query.from_(self.table_efg)
    .select(self.table_efg.fiz, self.table_efg.buz)
    .where(self.table_efg.buz == 'buz')
)

q = (
    Query.from_(self.table_abc)
    .join(subquery)
    .on(self.table_abc.bar == subquery.buz)
    .select(self.table_abc.foo, subquery.fiz)
    .where(self.table_abc.bar == 'bar')
)

parameter = NamedParameter()
sql = q.get_sql(parameter=parameter)
self.assertEqual(
    'SELECT "abc"."foo","sq0"."fiz" FROM "abc" JOIN (SELECT "fiz","buz" FROM "efg" WHERE "buz"=:param1)'
    ' "sq0" ON "abc"."bar"="sq0"."buz" WHERE "abc"."bar"=:param2',
    sql,
)
self.assertEqual({'param1': 'buz', 'param2': 'bar'}, parameter.get_parameters())

This would allow the user to easily plug into SQLAlchemy for example:

parameter = NamedParameter()
session.execute(text(q.get_sql(parameter=parameter)), **parameter.get_parameters())
wd60622 commented 4 months ago

Thanks for the PR! Will take a deeper look later

coveralls commented 4 months ago

Coverage Status

coverage: 98.331% (-0.06%) from 98.39% when pulling 66c6310e386e5dcacf62c920464e7c43d99c39f4 on mvanderlee:mvanderlee/parametized_query into 8841520e906970d76c5ed81c7dd5d154f0d5259d on kayak:master.

mvanderlee commented 3 months ago

Thanks for the PR! Will take a deeper look later

@wd60622 Do you think you'll have time this week?

wd60622 commented 3 months ago

Do you have any thoughts as well? @AzisK

mvanderlee commented 2 months ago

@wd60622 @AzisK any update on this? It should go hand in hand with #792

AzisK commented 2 months ago

Could we also have this functionality described in pypika docs?

AzisK commented 2 months ago

The tests look really nice. What about adding PyformatParameter in the tests as well?