cockroachdb / cockroachdb/cockroach

opt: attempting to aggregate by an outer column causes an internal error

Open
#142,845 1 comment 0 reactions 0 assignees View on GitHub
branch-release-25.1 C-bug O-support P-3 T-sql-queries
Dominant language
Go
Stars
32.5k
Forks
4.1k
PR merge metrics
PR metrics pending

Description

It is possible to trigger assertion errors like the following during optimization by attempting to aggregate over an outer-column reference:
```
expected success, but found
(XX000) internal error: top-level relational expression cannot have outer columns: (4)
optimizer.go:276: in Optimize()
DETAIL: stack trace:
pkg/sql/opt/xform/optimizer.go:276: Optimize()
pkg/sql/plan_opt.go:862: buildExecMemo()
pkg/sql/plan_opt.go:260: makeOptimizerPlan()
pkg/sql/conn_executor_exec.go:3302: makeExecPlan()
pkg/sql/conn_executor_exec.go:2848: dispatchToExecutionEngine()
pkg/sql/conn_executor_exec.go:2115: execStmtInOpenStateWithPausablePortal()
pkg/sql/conn_executor_exec.go:163: func1()
pkg/sql/conn_executor_exec.go:4463: execWithProfiling()
pkg/sql/conn_executor_exec.go:162: execStmt()
pkg/sql/conn_executor.go:2425: func1()
pkg/sql/conn_executor.go:2430: execCmd()
pkg/sql/conn_executor.go:2347: run()
pkg/sql/conn_executor.go:1018: ServeConn()
pkg/sql/pgwire/conn.go:252: processCommands()
pkg/sql/pgwire/server.go:1197: func4()
src/runtime/asm_arm64.s:1223: goexit()
```
Here are two logic tests that reproduce the issue:

One with the outer column produced by an apply-join:
```
statement ok
SELECT * FROM (SELECT 1) AS foo(bar)
INNER JOIN LATERAL (SELECT sum(bar) FROM generate_series(1, 10)) ON true
```
And one with the outer column produced by a routine:
```
statement ok
CREATE FUNCTION bar() RETURNS DECIMAL LANGUAGE PLpgSQL AS $$
DECLARE
baz DECIMAL := 1.0;
BEGIN
SELECT sum(baz) INTO baz
FROM generate_series(1, 10) g(t);
RETURN baz;
END
$$;

statement ok
SELECT bar()
```
Here's what Postgres does for the first example:
```
postgres=# SELECT * FROM (SELECT 1) AS foo(bar)
INNER JOIN LATERAL (SELECT sum(bar) FROM generate_series(1, 10)) ON true;
ERROR: 42803: aggregate functions are not allowed in FROM clause of their own query level
LINE 2: INNER JOIN LATERAL (SELECT sum(bar) FROM generate_series(1, ...
^
LOCATION: check_agglevels_and_constraints, parse_agg.c:589
```
Postgres actually allows the routine example, but it's unclear if we want to do the same:
```
postgres=# CREATE FUNCTION bar() RETURNS DECIMAL LANGUAGE PLpgSQL AS $$
DECLARE
baz DECIMAL := 1.0;
BEGIN
SELECT sum(baz) INTO baz
FROM generate_series(1, 10) g(t);
RETURN baz;
END
$$;
CREATE FUNCTION
postgres=# SELECT bar();
bar
------
10.0
(1 row)
```

Jira issue: CRDB-48542

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.