ORDER BY "..." is ambiguous
- Dominant language
- C
- Stars
- 12.8k
- Forks
- 794
- Avg merge
- 2d 14h
- Merged PRs (30d)
- 31
Description
When a CTE/subquery is materialised and read back in via read_intermediate_result there is a chance that an ORDER BY causes a misbehaviour between the postgres parser and deparser. When the same name is used multiple times in the target list the parser might give an error while parsing a previously deparsed query.
```sql
CREATE TABLE t0 (a int PRIMARY KEY);
SELECT create_distributed_table('t0', 'a');
WITH a AS (SELECT a, a FROM t0 OFFSET 0) SELECT * FROM a ORDER BY 1, 2;
ERROR: ORDER BY "a" is ambiguous
```
The cause is the query created for processing the intermediate result gets turned into the following:
```sql
SELECT a, a_1 AS a
FROM (
SELECT intermediate_result.a, intermediate_result.a_1 AS a
FROM read_intermediate_result('8_1'::text, 'binary'::citus_copy_format) intermediate_result(a integer, a_1 integer)
) a(a, a_1) ORDER BY a, a_1;
```
When parsing this query back it will not know which `a` to resolve in the `ORDER BY` as there are 2 `a` names defined in the target list. To resolve to the right `a` here it would ideally be prefixed by the alias given to the relation that the field comes from. `ORDER BY a.a, a_1` works.
A quick way to achieve this is to set `varprefix` to true in the deparse context. This however changes roughly 56 test suites due to the deparsed query showing in the log output.
https://github.com/citusdata/citus/blob/81894157318131fd7d325b71bf1a338ba045da59/src/backend/distributed/deparser/ruleutils_12.c#L1950-L1951
To limit blast radius we would need to investigate the possibility of adding an extra check to https://github.com/citusdata/citus/blob/81894157318131fd7d325b71bf1a338ba045da59/src/backend/distributed/deparser/ruleutils_12.c#L3753-L3757 so to force the writing of `refname` when `attname` will not uniquely resolve. This will also be a more fundamental fix to the deparser which could be upstreamed to postgres.
Contributor guide
Assessment
This issue has not been assessed yet.