pypika
pypika copied to clipboard
Alias not being specified for complex criteria
I'm attempting to use the code snippet below however my alias directives are not being honoured for the middle two SELECT clauses (Q2 and Q3) while the are being specified for Q1 and Q4 (which are simple less than or greater than comparisons). The function returns without error so it's failing silently. Am I specifying something incorrectly? I also tried with Criterion.all([]) with the same result. Python 3.9.0 and PyPika 0.44.0
from pypika import MySQLQuery, Table, functions
metrics = Table('metrics')
q = MySQLQuery.from_(metrics).select(
functions.Count('1').as_('count'),
(metrics.date < "2020-04-01 00:00:00").as_('Q1'),
((metrics.date >= "2020-04-01 00:00:00") & (metrics.date < "2020-07-01 00:00:00")).as_('Q2'),
((metrics.date >= "2020-07-01 00:00:00") & (metrics.date < "2020-10-01 00:00:00")).as_('Q3'),
(metrics.date >= "2020-10-01 00:00:00").as_('Q4')
).where(metrics.date >= "2020-01-01 00:00:00").groupby("Q1", "Q2", "Q3", "Q4")
print(q.get_sql())
Output:
SELECT COUNT('1') `count`,`date`<'2020-04-01 00:00:00' Q1,`date`>='2020-04-01 00:00:00' AND `date`<'2020-07-01 00:00:00',`date`>='2020-07-01 00:00:00' AND `date`<'2020-10-01 00:00:00',`date`>='2020-10-01 00:00:00' Q4 FROM `metrics` WHERE `date`>='2020-01-01 00:00:00' GROUP BY `Q1`,`Q2`,`Q3`,`Q4`
I am seeing a similar issue. I am expecting this to give a single column named "in_the_future"
, but the alias is not coming out in the generated SQL.
from pypika import Table, Query
from pypika.functions import Now, Coalesce
table = Table('table')
query = Query.from_(table).select(
(table.some_boolean_column | Coalesce(table.timestamp > Now(), False)).as_('in_the_future'),
)
print(query.get_sql())
Expected output:
SELECT "some_boolean_column" OR COALESCE("timestamp">NOW(),false) in_the_future FROM "table"
Actual output:
SELECT "some_boolean_column" OR COALESCE("timestamp">NOW(),false) FROM "table"
see https://github.com/kayak/pypika/pull/735