From 7cd9765f9bd3397b8d4d0f507021ef848b6d48d2 Mon Sep 17 00:00:00 2001 From: Tom Lane Date: Fri, 22 Jan 2021 16:26:22 -0500 Subject: Re-allow DISTINCT in pl/pgsql expressions. I'd omitted this from the grammar in commit c9d529848, figuring that it wasn't worth supporting. However we already have one complaint, so it seems that judgment was wrong. It doesn't require a huge amount of code, so add it back. (I'm still drawing the line at UNION/INTERSECT/EXCEPT though: those'd require an unreasonable amount of grammar refactoring, and the single-result-row restriction makes them near useless anyway.) Also rethink the documentation: this behavior is a property of all pl/pgsql expressions, not just assignments. Discussion: https://postgr.es/m/20210122134106.e94c5cd7@mail.verfriemelt.org --- src/backend/parser/analyze.c | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) (limited to 'src/backend/parser/analyze.c') diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 28e192f51c8..65483892252 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -2466,7 +2466,7 @@ transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt) /* * The rest mostly matches transformSelectStmt, except that we needn't - * consider WITH or DISTINCT, and we build a targetlist our own way. + * consider WITH or INTO, and we build a targetlist our own way. */ qry->commandType = CMD_SELECT; pstate->p_is_insert = false; @@ -2590,10 +2590,29 @@ transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt) EXPR_KIND_GROUP_BY, false /* allow SQL92 rules */ ); - /* No DISTINCT clause */ - Assert(!sstmt->distinctClause); - qry->distinctClause = NIL; - qry->hasDistinctOn = false; + if (sstmt->distinctClause == NIL) + { + qry->distinctClause = NIL; + qry->hasDistinctOn = false; + } + else if (linitial(sstmt->distinctClause) == NULL) + { + /* We had SELECT DISTINCT */ + qry->distinctClause = transformDistinctClause(pstate, + &qry->targetList, + qry->sortClause, + false); + qry->hasDistinctOn = false; + } + else + { + /* We had SELECT DISTINCT ON */ + qry->distinctClause = transformDistinctOnClause(pstate, + sstmt->distinctClause, + &qry->targetList, + qry->sortClause); + qry->hasDistinctOn = true; + } /* transform LIMIT */ qry->limitOffset = transformLimitClause(pstate, sstmt->limitOffset, -- cgit v1.2.3