Skip to content

Commit 0bb6a6e

Browse files
compiler: a scalar subquery's column is nullable
A scalar subquery yields NULL when it matches no row, so its column is nullable unless the subquery always yields one row: an aggregate with no GROUP BY, HAVING or LIMIT, or a SELECT with no FROM. Fixes #4262 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3ad8b20 commit 0bb6a6e

8 files changed

Lines changed: 211 additions & 2 deletions

File tree

‎internal/compiler/output_columns.go‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package compiler
33
import (
44
"errors"
55
"fmt"
6+
"strings"
67

78
"github.com/sqlc-dev/sqlc/internal/config"
89
"github.com/sqlc-dev/sqlc/internal/sql/ast"
@@ -349,11 +350,15 @@ func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, er
349350
if err != nil {
350351
return nil, err
351352
}
352-
first := subcols[0]
353+
first := *subcols[0]
353354
if res.Name != nil {
354355
first.Name = *res.Name
355356
}
356-
cols = append(cols, first)
357+
// A scalar subquery that matches no row yields NULL
358+
if !yieldsOneRow(n.Subselect) {
359+
first.NotNull = false
360+
}
361+
cols = append(cols, &first)
357362
default:
358363
cols = append(cols, &Column{Name: name, DataType: "any", NotNull: false})
359364
}
@@ -810,3 +815,52 @@ func findColumnForRef(ref *ast.ColumnRef, tables []*Table, targetList *ast.List)
810815

811816
return nil
812817
}
818+
819+
// aggregates names the aggregate functions that return a row even when no row
820+
// matches, as count(*) does
821+
var aggregates = map[string]bool{
822+
"count": true, "sum": true, "avg": true, "min": true, "max": true,
823+
"bool_and": true, "bool_or": true, "every": true, "array_agg": true,
824+
"string_agg": true, "json_agg": true, "jsonb_agg": true,
825+
"json_object_agg": true, "jsonb_object_agg": true,
826+
}
827+
828+
// yieldsOneRow reports whether a scalar subquery always yields exactly one row:
829+
// a SELECT with no FROM or WHERE, or one whose every column is an aggregate,
830+
// with no GROUP BY, HAVING, LIMIT, OFFSET or set operation.
831+
func yieldsOneRow(node ast.Node) bool {
832+
sel, ok := node.(*ast.SelectStmt)
833+
if !ok || sel.Op != ast.None || given(sel.LimitCount) || given(sel.LimitOffset) || given(sel.HavingClause) {
834+
return false
835+
}
836+
if sel.GroupClause != nil && len(sel.GroupClause.Items) > 0 {
837+
return false
838+
}
839+
if (sel.FromClause == nil || len(sel.FromClause.Items) == 0) && !given(sel.WhereClause) {
840+
return true
841+
}
842+
if sel.TargetList == nil || len(sel.TargetList.Items) == 0 {
843+
return false
844+
}
845+
for _, item := range sel.TargetList.Items {
846+
res, ok := item.(*ast.ResTarget)
847+
if !ok {
848+
return false
849+
}
850+
call, ok := res.Val.(*ast.FuncCall)
851+
if !ok || call.Func == nil || call.Over != nil || !aggregates[strings.ToLower(call.Func.Name)] {
852+
return false
853+
}
854+
}
855+
return true
856+
}
857+
858+
// given reports whether a clause was written: the parser leaves one that wasn't
859+
// as nil or as a placeholder
860+
func given(n ast.Node) bool {
861+
if n == nil {
862+
return false
863+
}
864+
_, placeholder := n.(*ast.TODO)
865+
return !placeholder
866+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
https://github.com/sqlc-dev/sqlc/issues/4262

‎internal/endtoend/testdata/nullable_scalar_subquery/postgresql/stdlib/go/db.go‎

Lines changed: 31 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎internal/endtoend/testdata/nullable_scalar_subquery/postgresql/stdlib/go/models.go‎

Lines changed: 25 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎internal/endtoend/testdata/nullable_scalar_subquery/postgresql/stdlib/go/query.sql.go‎

Lines changed: 74 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
-- name: ThroughView :many
2+
select id, review_id, reviews from book_view;
3+
4+
-- name: Inline :many
5+
select (select r.id from reviews r where r.book_id = b.id limit 1) review_id,
6+
(select count(*) from reviews r where r.book_id = b.id) reviews,
7+
(select 1) one
8+
from books b;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
create table books (id int primary key, title text not null);
2+
create table reviews (id int primary key, book_id int not null);
3+
create view book_view as
4+
select b.id, (select r.id from reviews r where r.book_id = b.id limit 1) review_id,
5+
(select count(*) from reviews r where r.book_id = b.id) reviews
6+
from books b;
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
version: "2"
2+
sql:
3+
- engine: "postgresql"
4+
schema: "schema.sql"
5+
queries: "query.sql"
6+
gen:
7+
go:
8+
package: "querytest"
9+
out: "go"
10+
sql_package: "database/sql"

0 commit comments

Comments
 (0)