Closed ikozinov closed 3 years ago
Thanks for the PR and investigation! Nice job figuring out how to add the test case; I was worried it might be too complicated.
This bug is so strange. Running this prepared query using NULL
for $1
:
EXPLAIN (VERBOSE, FORMAT JSON) SELECT first_name, last_name FROM author ORDER BY author_id = $1;
Has the explain output of:
[
{
"Plan": {
"Node Type": "Seq Scan",
"Parallel Aware": false,
"Relation Name": "author",
"Schema": "pggen_test_240800122",
"Alias": "author",
"Startup Cost": 0.00,
"Total Cost": 16.30,
"Plan Rows": 630,
"Plan Width": 65,
"Output": ["first_name", "last_name", "NULL::boolean"]
}
}
]
I'll try to figure out a more elegant solution, but your PR is a nice quick fix.
Ok, I think I figured it out. The plan output contains enough information to run the the entire query. In this case, the seq scan node propagates the author_id
in order to use it for the sort. It's much clearer if we use a concrete value for the order by
clause:
EXPLAIN (VERBOSE, FORMAT JSON)
SELECT first_name, last_name
FROM author
ORDER BY author_id = 222;
[
{
"Plan": {
"Node Type": "Sort",
"Parallel Aware": false,
"Startup Cost": 47.17,
"Total Cost": 48.74,
"Plan Rows": 630,
"Plan Width": 65,
"Output": ["first_name", "last_name", "((author_id = 222))"],
"Sort Key": ["((author.author_id = 222))"],
"Plans": [
{
"Node Type": "Seq Scan",
"Parent Relationship": "Outer",
"Parallel Aware": false,
"Relation Name": "author",
"Schema": "public",
"Alias": "author",
"Startup Cost": 0.00,
"Total Cost": 17.88,
"Plan Rows": 630,
"Plan Width": 65,
"Output": ["first_name", "last_name", "(author_id = 222)"]
}
]
}
}
]
I'm not sure why the sort node doesn't appear when we run the explain query using null
as a prepared value. Maybe the postgres planner infers that author_id
can never be null due to the primary key constraint so it doesn't bother with a sort.
When generating code for a PostgreSQL request like this:
after executing the code generator, panic occurs:
After debug, I found out that for some reason in the
EXPLAIN
command output in theOutput
field there is an extra value with the name of the column that is mentioned inORDER BY
clause.It turns out that the length of
plan.Outputs
is not always equal to the length of the array with column names (cols
)