Skip to content

Commit

Permalink
Deparser: Add support for COALESCE and other expressions in LIMIT clause
Browse files Browse the repository at this point in the history
We've previously supported "c_expr" being used in a LIMIT clause, but
its actually more correct to treat this as "a_expr", which is a broader
set of functions, including COALESCE.

Note that the previous handling (for "c_expr") is still correct for
FETCH FIRST (expr) ROWS WITH TIES, see the "select_fetch_first_value"
in the Postgres grammar.

In passing fix two new warnings in the deparser caused by a recent code
addition.
  • Loading branch information
lfittl committed Jul 8, 2023
1 parent cb3aa9e commit e6c31d3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/postgres_deparse.c
Original file line number Diff line number Diff line change
Expand Up @@ -2267,9 +2267,11 @@ static void deparseSelectStmt(StringInfo str, SelectStmt *stmt)

if (IsA(stmt->limitCount, A_Const) && castNode(A_Const, stmt->limitCount)->isnull)
appendStringInfoString(str, "ALL");
else
else if (stmt->limitOption == LIMIT_OPTION_WITH_TIES)
deparseCExpr(str, stmt->limitCount);

else
deparseExpr(str, stmt->limitCount);

appendStringInfoChar(str, ' ');

if (stmt->limitOption == LIMIT_OPTION_WITH_TIES)
Expand Down Expand Up @@ -4899,13 +4901,15 @@ static void deparseCreateFunctionStmt(StringInfo str, CreateFunctionStmt *create
/* RETURN or BEGIN ... END
*/
if (IsA(create_function_stmt->sql_body, ReturnStmt))
{
deparseReturnStmt(str, castNode(ReturnStmt, create_function_stmt->sql_body));
}
else
{
appendStringInfoString(str, "BEGIN ATOMIC ");
if (linitial(create_function_stmt->sql_body) != NULL)
if (IsA(create_function_stmt->sql_body, List), linitial((List *) create_function_stmt->sql_body) != NULL)
{
List *body_stmt_list = castNode(List, linitial(create_function_stmt->sql_body));
List *body_stmt_list = castNode(List, linitial((List *) create_function_stmt->sql_body));
foreach(lc, body_stmt_list)
{
if (IsA(lfirst(lc), ReturnStmt))
Expand Down
1 change: 1 addition & 0 deletions test/deparse_tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ const char* tests[] = {
"CREATE PROCEDURE do_nothing() LANGUAGE sql BEGIN ATOMIC END",
"CREATE PROCEDURE returns_one() LANGUAGE sql BEGIN ATOMIC RETURN 1; END",
"CREATE PROCEDURE updates_and_returns_one() LANGUAGE sql BEGIN ATOMIC UPDATE tbl SET a = 1; RETURN 1; END",
"SELECT 1 FROM tbl LIMIT COALESCE($1, $2)",
};

size_t testsLength = __LINE__ - 4;

0 comments on commit e6c31d3

Please sign in to comment.