Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sql: support preferred binary operators #70066

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pkg/sql/pgwire/pgwire_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,14 @@ func TestPGPreparedQuery(t *testing.T) {
{"TRUNCATE TABLE d.str", []preparedQueryTest{
baseTest.SetArgs(),
}},
{"SELECT '{\"field\": 12}'::JSON->$1", []preparedQueryTest{
baseTest.SetArgs("field").Results("12"),
baseTest.SetArgs(0).Results(gosql.NullString{}),
}},
{"SELECT '{\"field\": 12}'::JSON->>$1", []preparedQueryTest{
baseTest.SetArgs("field").Results("12"),
baseTest.SetArgs(0).Results(gosql.NullString{}),
}},

// TODO(nvanbenschoten): Same class of limitation as that in logic_test/typing:
// Nested constants are not exposed to the same constant type resolution rules
Expand Down
33 changes: 18 additions & 15 deletions pkg/sql/sem/tree/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,12 +284,13 @@ type TwoArgFn func(*EvalContext, Datum, Datum) (Datum, error)

// BinOp is a binary operator.
type BinOp struct {
LeftType *types.T
RightType *types.T
ReturnType *types.T
NullableArgs bool
Fn TwoArgFn
Volatility Volatility
LeftType *types.T
RightType *types.T
ReturnType *types.T
NullableArgs bool
Fn TwoArgFn
Volatility Volatility
PreferredOverload bool

types TypeList
retType ReturnTyper
Expand All @@ -311,8 +312,8 @@ func (op *BinOp) returnType() ReturnTyper {
return op.retType
}

func (*BinOp) preferred() bool {
return false
func (op *BinOp) preferred() bool {
return op.PreferredOverload
}

// AppendToMaybeNullArray appends an element to an array. If the first
Expand Down Expand Up @@ -1891,7 +1892,8 @@ var BinOps = map[BinaryOperatorSymbol]binOpOverload{
}
return &DJSON{j}, nil
},
Volatility: VolatilityImmutable,
PreferredOverload: true,
Volatility: VolatilityImmutable,
},
&BinOp{
LeftType: types.Jsonb,
Expand Down Expand Up @@ -1952,7 +1954,8 @@ var BinOps = map[BinaryOperatorSymbol]binOpOverload{
}
return NewDString(*text), nil
},
Volatility: VolatilityImmutable,
PreferredOverload: true,
Volatility: VolatilityImmutable,
},
&BinOp{
LeftType: types.Jsonb,
Expand Down Expand Up @@ -2026,7 +2029,7 @@ type CmpOp struct {

Volatility Volatility

isPreferred bool
PreferredOverload bool
}

func (op *CmpOp) params() TypeList {
Expand All @@ -2044,7 +2047,7 @@ func (op *CmpOp) returnType() ReturnTyper {
}

func (op *CmpOp) preferred() bool {
return op.isPreferred
return op.PreferredOverload
}

func cmpOpFixups(
Expand Down Expand Up @@ -2319,9 +2322,9 @@ var CmpOps = cmpOpFixups(map[ComparisonOperatorSymbol]cmpOpOverload{
RightType: types.Unknown,
Fn: cmpOpScalarIsFn,
NullableArgs: true,
// Avoids ambiguous comparison error for NULL IS NOT DISTINCT FROM NULL>
isPreferred: true,
Volatility: VolatilityLeakProof,
// Avoids ambiguous comparison error for NULL IS NOT DISTINCT FROM NULL.
PreferredOverload: true,
Volatility: VolatilityLeakProof,
},
&CmpOp{
LeftType: types.AnyArray,
Expand Down
27 changes: 15 additions & 12 deletions pkg/sql/sem/tree/overload.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,14 @@ func (b Overload) Signature(simplify bool) string {
type overloadImpl interface {
params() TypeList
returnType() ReturnTyper
// allows manually resolving preference between multiple compatible overloads
// allows manually resolving preference between multiple compatible overloads.
preferred() bool
}

var _ overloadImpl = &Overload{}
var _ overloadImpl = &UnaryOp{}
var _ overloadImpl = &BinOp{}
var _ overloadImpl = &CmpOp{}

// GetParamsAndReturnType gets the parameters and return type of an
// overloadImpl.
Expand Down Expand Up @@ -582,7 +583,8 @@ func typeCheckOverloadedExprs(
return typedExprs, fns, err
}

// The first heuristic is to prefer candidates that return the desired type.
// The first heuristic is to prefer candidates that return the desired type,
// if a desired type was provided.
if desired.Family() != types.AnyFamily {
s.overloadIdxs = filterOverloads(s.overloads, s.overloadIdxs,
func(o overloadImpl) bool {
Expand Down Expand Up @@ -741,7 +743,17 @@ func typeCheckOverloadedExprs(
}
}

// The fifth heuristic is to prefer candidates where all placeholders can be
// The fifth heuristic is to defer to preferred candidates, if one has been
// specified in the overload list.
if ok, typedExprs, fns, err := filterAttempt(ctx, semaCtx, &s, func() {
s.overloadIdxs = filterOverloads(s.overloads, s.overloadIdxs, func(o overloadImpl) bool {
return o.preferred()
})
}); ok {
return typedExprs, fns, err
}

// The sixth heuristic is to prefer candidates where all placeholders can be
// given the same type as all constants and resolvable expressions. This is
// only possible if all constants and resolvable expressions were resolved
// homogeneously up to this point.
Expand Down Expand Up @@ -851,15 +863,6 @@ func typeCheckOverloadedExprs(
}
}

// The final heuristic is to defer to preferred candidates, if available.
if ok, typedExprs, fns, err := filterAttempt(ctx, semaCtx, &s, func() {
s.overloadIdxs = filterOverloads(s.overloads, s.overloadIdxs, func(o overloadImpl) bool {
return o.preferred()
})
}); ok {
return typedExprs, fns, err
}

if err := defaultTypeCheck(ctx, semaCtx, &s, len(s.overloads) > 0); err != nil {
return nil, nil, err
}
Expand Down
19 changes: 15 additions & 4 deletions pkg/sql/sem/tree/overload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ func (to testOverload) preferred() bool {
return to.pref
}

func (to testOverload) withPreferred(pref bool) *testOverload {
to.pref = pref
return &to
}

func (to *testOverload) String() string {
typeNames := make([]string, len(to.paramTypes))
for i, param := range to.paramTypes {
Expand All @@ -117,7 +122,7 @@ func (to *testOverload) String() string {
return fmt.Sprintf("func(%s) %s", strings.Join(typeNames, ","), to.retType)
}

func makeTestOverload(retType *types.T, params ...*types.T) overloadImpl {
func makeTestOverload(retType *types.T, params ...*types.T) *testOverload {
t := make(ArgTypes, len(params))
for i := range params {
t[i].Typ = params[i]
Expand Down Expand Up @@ -148,13 +153,14 @@ func TestTypeCheckOverloadedExprs(t *testing.T) {
}

unaryIntFn := makeTestOverload(types.Int, types.Int)
unaryIntFnPref := &testOverload{retType: types.Int, paramTypes: ArgTypes{}, pref: true}
unaryIntFnPref := makeTestOverload(types.Int, types.Int).withPreferred(true)
unaryFloatFn := makeTestOverload(types.Float, types.Float)
unaryDecimalFn := makeTestOverload(types.Decimal, types.Decimal)
unaryStringFn := makeTestOverload(types.String, types.String)
unaryIntervalFn := makeTestOverload(types.Interval, types.Interval)
unaryTimestampFn := makeTestOverload(types.Timestamp, types.Timestamp)
binaryIntFn := makeTestOverload(types.Int, types.Int, types.Int)
binaryIntFnPref := makeTestOverload(types.Int, types.Int, types.Int).withPreferred(true)
binaryFloatFn := makeTestOverload(types.Float, types.Float, types.Float)
binaryDecimalFn := makeTestOverload(types.Decimal, types.Decimal, types.Decimal)
binaryStringFn := makeTestOverload(types.String, types.String, types.String)
Expand All @@ -177,6 +183,7 @@ func TestTypeCheckOverloadedExprs(t *testing.T) {
inBinOp bool
}{
// Unary constants.
{nil, []Expr{intConst("1")}, []overloadImpl{unaryIntFn, unaryIntFn}, ambiguous, false},
{nil, []Expr{intConst("1")}, []overloadImpl{unaryIntFn, unaryFloatFn}, unaryIntFn, false},
{nil, []Expr{decConst("1.0")}, []overloadImpl{unaryIntFn, unaryDecimalFn}, unaryDecimalFn, false},
{nil, []Expr{decConst("1.0")}, []overloadImpl{unaryIntFn, unaryFloatFn}, unsupported, false},
Expand All @@ -186,12 +193,13 @@ func TestTypeCheckOverloadedExprs(t *testing.T) {
{nil, []Expr{strConst("PT12H2M")}, []overloadImpl{unaryIntervalFn}, unaryIntervalFn, false},
{nil, []Expr{strConst("PT12H2M")}, []overloadImpl{unaryIntervalFn, unaryStringFn}, unaryStringFn, false},
{nil, []Expr{strConst("PT12H2M")}, []overloadImpl{unaryIntervalFn, unaryTimestampFn}, unaryIntervalFn, false},
{nil, []Expr{}, []overloadImpl{unaryIntFn, unaryIntFnPref}, unaryIntFnPref, false},
{nil, []Expr{}, []overloadImpl{unaryIntFnPref, unaryIntFnPref}, ambiguous, false},
{nil, []Expr{intConst("1")}, []overloadImpl{unaryIntFn, unaryIntFnPref}, unaryIntFnPref, false},
{nil, []Expr{intConst("1")}, []overloadImpl{unaryIntFnPref, unaryIntFnPref}, ambiguous, false},
{nil, []Expr{strConst("PT12H2M")}, []overloadImpl{unaryIntervalFn, unaryIntFn}, unaryIntervalFn, false},
// Unary unresolved Placeholders.
{nil, []Expr{placeholder(0)}, []overloadImpl{unaryStringFn, unaryIntFn}, shouldError, false},
{nil, []Expr{placeholder(0)}, []overloadImpl{unaryStringFn, binaryIntFn}, unaryStringFn, false},
{nil, []Expr{placeholder(0)}, []overloadImpl{unaryStringFn, unaryIntFnPref}, unaryIntFnPref, false},
// Unary values (not constants).
{nil, []Expr{NewDInt(1)}, []overloadImpl{unaryIntFn, unaryFloatFn}, unaryIntFn, false},
{nil, []Expr{NewDFloat(1)}, []overloadImpl{unaryIntFn, unaryFloatFn}, unaryFloatFn, false},
Expand All @@ -205,9 +213,12 @@ func TestTypeCheckOverloadedExprs(t *testing.T) {
{nil, []Expr{strConst("2010-09-28"), strConst("2010-09-29")}, []overloadImpl{binaryTimestampFn}, binaryTimestampFn, false},
{nil, []Expr{strConst("2010-09-28"), strConst("2010-09-29")}, []overloadImpl{binaryTimestampFn, binaryStringFn}, binaryStringFn, false},
{nil, []Expr{strConst("2010-09-28"), strConst("2010-09-29")}, []overloadImpl{binaryTimestampFn, binaryIntFn}, binaryTimestampFn, false},
{nil, []Expr{intConst("1"), intConst("1")}, []overloadImpl{binaryIntFn, binaryFloatFn, binaryIntFnPref}, binaryIntFnPref, false},
{nil, []Expr{intConst("1"), intConst("1")}, []overloadImpl{binaryIntFn, binaryIntFnPref, binaryIntFnPref}, ambiguous, false},
// Binary unresolved Placeholders.
{nil, []Expr{placeholder(0), placeholder(1)}, []overloadImpl{binaryIntFn, binaryFloatFn}, shouldError, false},
{nil, []Expr{placeholder(0), placeholder(1)}, []overloadImpl{binaryIntFn, unaryStringFn}, binaryIntFn, false},
{nil, []Expr{placeholder(0), placeholder(1)}, []overloadImpl{binaryIntFnPref, binaryFloatFn}, binaryIntFnPref, false},
{nil, []Expr{placeholder(0), NewDString("a")}, []overloadImpl{binaryIntFn, binaryStringFn}, binaryStringFn, false},
{nil, []Expr{placeholder(0), intConst("1")}, []overloadImpl{binaryIntFn, binaryFloatFn}, binaryIntFn, false},
{nil, []Expr{placeholder(0), intConst("1")}, []overloadImpl{binaryStringFn, binaryFloatFn}, binaryFloatFn, false},
Expand Down
2 changes: 1 addition & 1 deletion pkg/sql/sem/tree/type_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ const (
// (RejectAggregates notwithstanding).
RejectNestedAggregates

// RejectNestedWindows rejects any use of window functions inside the
// RejectNestedWindowFunctions rejects any use of window functions inside the
// argument list of another window function.
RejectNestedWindowFunctions

Expand Down