Skip to content

Commit 41a7691

Browse files
EliSauderCopilot
andcommitted
refactor(mssql): keep ISNULL type selection in the engine policy
Replace the shared FirstArgType instruction with source function identity passed through the generic combination request. Keep first-typed inference in shared code only as the compatibility fallback. Preserve ISNULL identity in AST traversal and printing. Cover first-argument selection versus COALESCE widening, literal NULLs and placeholders with pre-change end-to-end goldens. Exercise formatting directly because the fmt CLI does not support MSSQL. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 91aab3b commit 41a7691

13 files changed

Lines changed: 196 additions & 23 deletions

File tree

‎docs/guides/development.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@ inference fallback, while an error is propagated. Engines without a combiner
2828
keep their existing behavior. `Prepare` accepts the combiner through an
2929
optional analyzer option, inherited by nested queries.
3030

31+
When a converter lowers a function to a shared expression, it can retain the
32+
source function name rather than encoding a result-type instruction in the
33+
AST. `TypeCombinationRequest.FunctionName` passes that qualified identity to
34+
the engine. For example, SQL Server's policy, not shared analysis, selects
35+
ISNULL's first typed argument; ordinary COALESCE still combines its candidates.
36+
The shared first-typed-value helper is only the compatibility fallback for
37+
engines without a policy or for contexts a policy declines.
38+
3139
The compiler's existing engine assembly selects an optional combiner factory.
3240
It calls that factory after `core.NewCached` returns, on both fresh and
3341
restored catalogs, and passes the instance to analysis. No engine names,

‎internal/core/analyzer/expr.go‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -492,8 +492,8 @@ func (a *analyzer) typeCase(e *ast.CaseExpr) (exprType, error) {
492492
return t, nil
493493
}
494494

495-
// typeCoalesce types COALESCE, which is null only when every argument is,
496-
// and uses a common type unless the AST requests the first typed argument.
495+
// typeCoalesce types COALESCE-like expressions, which are null only when
496+
// every argument is. Function-specific type selection belongs to the dialect.
497497
func (a *analyzer) typeCoalesce(e *ast.CoalesceExpr) (exprType, error) {
498498
types := make([]exprType, 0, len(listItems(e.Args)))
499499
nullable := true
@@ -505,15 +505,18 @@ func (a *analyzer) typeCoalesce(e *ast.CoalesceExpr) (exprType, error) {
505505
types = append(types, t)
506506
nullable = nullable && t.nullable
507507
}
508-
var t exprType
509-
if e.FirstArgType {
510-
t = firstTyped(types)
511-
} else {
512-
var err error
513-
t, err = a.commonType(core.CombineCoalesce, types)
514-
if err != nil {
515-
return exprType{}, err
508+
req := core.TypeCombinationRequest{Context: core.CombineCoalesce}
509+
if e.Func != nil {
510+
if e.Func.Catalog != "" {
511+
req.FunctionName = append(req.FunctionName, e.Func.Catalog, e.Func.Schema)
512+
} else if e.Func.Schema != "" {
513+
req.FunctionName = append(req.FunctionName, e.Func.Schema)
516514
}
515+
req.FunctionName = append(req.FunctionName, e.Func.Name)
516+
}
517+
t, err := a.commonType(req, types)
518+
if err != nil {
519+
return exprType{}, err
517520
}
518521
// A placeholder there is one that may be NULL.
519522
a.inferAlternatives(listItems(e.Args), t, true)
@@ -535,7 +538,7 @@ func (a *analyzer) typeFirstOf(context core.TypeCombinationContext, nodes []ast.
535538
types = append(types, t)
536539
nullable = nullable || t.nullable
537540
}
538-
out, err := a.commonType(context, types)
541+
out, err := a.commonType(core.TypeCombinationRequest{Context: context}, types)
539542
if err != nil {
540543
return exprType{}, err
541544
}

‎internal/core/analyzer/setop.go‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ func (a *analyzer) combineColumns(op ast.SetOperation, left, right []core.Column
3232
case ast.Except:
3333
col.NotNull = l.NotNull
3434
}
35-
t, handled, err := a.combineTypes(context, []exprType{columnExprType(l), columnExprType(r)})
35+
t, handled, err := a.combineTypes(core.TypeCombinationRequest{Context: context}, []exprType{columnExprType(l), columnExprType(r)})
3636
if err != nil {
3737
return nil, err
3838
}
@@ -51,7 +51,7 @@ func (a *analyzer) combineColumns(op ast.SetOperation, left, right []core.Column
5151

5252
// combineTypes delegates selection and modifiers to engine-supplied behavior.
5353
// The whole list is passed without discarding untyped candidate positions.
54-
func (a *analyzer) combineTypes(context core.TypeCombinationContext, types []exprType) (exprType, bool, error) {
54+
func (a *analyzer) combineTypes(req core.TypeCombinationRequest, types []exprType) (exprType, bool, error) {
5555
if a.combiner == nil {
5656
return exprType{}, false, nil
5757
}
@@ -63,7 +63,8 @@ func (a *analyzer) combineTypes(context core.TypeCombinationContext, types []exp
6363
typed++
6464
}
6565
}
66-
result, err := a.combiner.Combine(core.TypeCombinationRequest{Context: context, Candidates: candidates})
66+
req.Candidates = candidates
67+
result, err := a.combiner.Combine(req)
6768
if err != nil {
6869
return exprType{}, false, err
6970
}
@@ -91,8 +92,8 @@ func (a *analyzer) combineTypes(context core.TypeCombinationContext, types []exp
9192

9293
// commonType retains first-typed-value inference when no combiner handles
9394
// the context. This compatibility fallback is not database coercion semantics.
94-
func (a *analyzer) commonType(context core.TypeCombinationContext, types []exprType) (exprType, error) {
95-
out, handled, err := a.combineTypes(context, types)
95+
func (a *analyzer) commonType(req core.TypeCombinationRequest, types []exprType) (exprType, error) {
96+
out, handled, err := a.combineTypes(req, types)
9697
if err != nil || handled {
9798
return out, err
9899
}

‎internal/core/analyzer/typecombiner_test.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ func TestTypeCombinerContract(t *testing.T) {
2222
a := &analyzer{}
2323
if name != "absent" {
2424
a.combiner = combinerFunc(func(req core.TypeCombinationRequest) (core.TypeCombinationResult, error) {
25-
if req.Context != core.CombineCase || len(req.Candidates) != 3 ||
25+
if req.Context != core.CombineCoalesce || len(req.FunctionName) != 2 ||
26+
req.FunctionName[0] != "schema" || req.FunctionName[1] != "fn" ||
27+
len(req.Candidates) != 3 ||
2628
req.Candidates[0] != nil || req.Candidates[1].Name != "integer" ||
2729
req.Candidates[2].Name != "text" {
2830
t.Fatalf("candidate context/order not preserved: %+v", req)
@@ -37,7 +39,9 @@ func TestTypeCombinerContract(t *testing.T) {
3739
}
3840
})
3941
}
40-
got, err := a.commonType(core.CombineCase, types)
42+
got, err := a.commonType(core.TypeCombinationRequest{
43+
Context: core.CombineCoalesce, FunctionName: []string{"schema", "fn"},
44+
}, types)
4145
if name == "error" {
4246
if !errors.Is(err, failure) {
4347
t.Fatalf("got %v, want policy failure", err)

‎internal/core/typecombiner.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ const (
1717

1818
type TypeCombinationRequest struct {
1919
Context TypeCombinationContext
20+
// FunctionName preserves a lowered function's identity as qualified name
21+
// components, not a result-type instruction. Nil means the ordinary
22+
// construct identified by Context.
23+
FunctionName []string
2024
// Candidates are in expression order, with nil for an untyped value.
2125
// Top-level result nullability is handled by the analyzer.
2226
Candidates []*TypeExpr

‎internal/endtoend/testdata/analyze_isnull/mssql/query.sql‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,11 @@ SELECT id,
55
ISNULL(amount, 0) AS amount
66
FROM readings
77
WHERE ISNULL(note, raw) = @value;
8+
9+
-- name: FirstArgumentTypes :many
10+
SELECT ISNULL(raw, CAST(note AS NVARCHAR(40))) AS first_text,
11+
COALESCE(raw, CAST(note AS NVARCHAR(40))) AS combined_text,
12+
ISNULL(NULL, raw) AS literal_null,
13+
ISNULL(@fallback, raw) AS placeholder_first,
14+
ISNULL(note, @replacement) AS placeholder_second
15+
FROM readings;

‎internal/endtoend/testdata/analyze_isnull/mssql/stdout.json‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,5 +64,99 @@
6464
}
6565
}
6666
]
67+
},
68+
{
69+
"name": "FirstArgumentTypes",
70+
"cmd": ":many",
71+
"columns": [
72+
{
73+
"name": "first_text",
74+
"type": {
75+
"name": "varchar",
76+
"args": [
77+
{
78+
"int": 10
79+
}
80+
]
81+
}
82+
},
83+
{
84+
"name": "combined_text",
85+
"type": {
86+
"name": "nvarchar",
87+
"args": [
88+
{
89+
"int": 40
90+
}
91+
]
92+
}
93+
},
94+
{
95+
"name": "literal_null",
96+
"type": {
97+
"name": "varchar",
98+
"args": [
99+
{
100+
"int": 10
101+
}
102+
]
103+
}
104+
},
105+
{
106+
"name": "placeholder_first",
107+
"type": {
108+
"name": "varchar",
109+
"args": [
110+
{
111+
"int": 10
112+
}
113+
]
114+
}
115+
},
116+
{
117+
"name": "placeholder_second",
118+
"type": {
119+
"name": "varchar",
120+
"nullable": true,
121+
"args": [
122+
{
123+
"int": 10
124+
}
125+
]
126+
}
127+
}
128+
],
129+
"params": [
130+
{
131+
"number": 1,
132+
"column": {
133+
"name": "fallback",
134+
"type": {
135+
"name": "varchar",
136+
"nullable": true,
137+
"args": [
138+
{
139+
"int": 10
140+
}
141+
]
142+
}
143+
}
144+
},
145+
{
146+
"number": 2,
147+
"column": {
148+
"name": "replacement",
149+
"type": {
150+
"name": "varchar",
151+
"nullable": true,
152+
"args": [
153+
{
154+
"int": 10
155+
}
156+
]
157+
}
158+
}
159+
}
160+
]
67161
}
68162
]

‎internal/engine/mssql/convert.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ func (c *cc) convertAlternatives(e *tsql.FunctionCall) ast.Node {
700700
switch identifierValue(e.FunctionName) {
701701
case "isnull":
702702
if len(args.Items) == 2 {
703-
return &ast.CoalesceExpr{Args: args, FirstArgType: true, Location: c.loc(e)}
703+
return &ast.CoalesceExpr{Args: args, Func: &ast.FuncName{Name: "isnull"}, Location: c.loc(e)}
704704
}
705705
case "greatest":
706706
return &ast.MinMaxExpr{Op: 0, Args: args, Location: c.loc(e)}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package mssql
2+
3+
import (
4+
"strings"
5+
"testing"
6+
7+
"github.com/sqlc-dev/sqlc/internal/sql/ast"
8+
)
9+
10+
// The fmt CLI does not support MSSQL, so exercise its AST printer directly.
11+
func TestLoweredFunctionFormatting(t *testing.T) {
12+
parser := NewParser()
13+
for _, name := range []string{"isnull", "coalesce"} {
14+
t.Run(name, func(t *testing.T) {
15+
stmts, err := parser.Parse(strings.NewReader("SELECT " + name + "(NULL, 1);"))
16+
if err != nil {
17+
t.Fatal(err)
18+
}
19+
// This literal-only expression needs no dialect formatting hooks.
20+
formatted := ast.Format(stmts[0].Raw, nil)
21+
if !strings.Contains(formatted, name+"(") {
22+
t.Fatalf("function identity changed: %s", formatted)
23+
}
24+
if _, err := parser.Parse(strings.NewReader(formatted)); err != nil {
25+
t.Fatalf("formatted SQL cannot be parsed: %v", err)
26+
}
27+
})
28+
}
29+
}

‎internal/engine/mssql/typepolicy/combine.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,19 @@ func decodeRules(data []byte) (rules, error) {
5151
}
5252

5353
func (p *combiner) Combine(req core.TypeCombinationRequest) (core.TypeCombinationResult, error) {
54+
if req.Context == core.CombineCoalesce && len(req.FunctionName) > 0 {
55+
if len(req.FunctionName) != 1 || req.FunctionName[0] != "isnull" {
56+
return core.TypeCombinationResult{}, nil
57+
}
58+
// ISNULL retains the first typed argument, including when a literal
59+
// NULL or an unconstrained placeholder comes before it.
60+
for _, candidate := range req.Candidates {
61+
if candidate != nil {
62+
return core.TypeCombinationResult{Handled: true, Type: candidate.WithNullable(false)}, nil
63+
}
64+
}
65+
return core.TypeCombinationResult{Handled: true}, nil
66+
}
5467
switch req.Context {
5568
case core.CombineUnion, core.CombineIntersect, core.CombineExcept,
5669
core.CombineCase, core.CombineCoalesce, core.CombineGreatest, core.CombineLeast:

0 commit comments

Comments
 (0)