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

feat(spanner): allow untyped nil values in parameterized queries #4482

Merged
merged 3 commits into from Jul 22, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
56 changes: 55 additions & 1 deletion spanner/integration_test.go
Expand Up @@ -1715,9 +1715,63 @@ func TestIntegration_BasicTypes(t *testing.T) {
{col: "NumericArray", val: []NullNumeric(nil)},
{col: "NumericArray", val: []NullNumeric{}},
{col: "NumericArray", val: []NullNumeric{{n1, true}, {n2, true}, {}}},
{col: "String", val: nil, want: NullString{}},
{col: "StringArray", val: nil, want: []NullString(nil)},
{col: "Bytes", val: nil, want: []byte(nil)},
{col: "BytesArray", val: nil, want: [][]byte(nil)},
{col: "Int64a", val: nil, want: NullInt64{}},
{col: "Int64Array", val: nil, want: []NullInt64(nil)},
{col: "Bool", val: nil, want: NullBool{}},
{col: "BoolArray", val: nil, want: []NullBool(nil)},
{col: "Float64", val: nil, want: NullFloat64{}},
{col: "Float64Array", val: nil, want: []NullFloat64(nil)},
{col: "Date", val: nil, want: NullDate{}},
{col: "DateArray", val: nil, want: []NullDate(nil)},
{col: "Timestamp", val: nil, want: NullTime{}},
{col: "TimestampArray", val: nil, want: []NullTime(nil)},
{col: "Numeric", val: nil, want: NullNumeric{}},
{col: "NumericArray", val: nil, want: []NullNumeric(nil)},
}

// Write rows into table first using DML. Only do this on real Spanner
// as the emulator does not support untyped parameters.
// TODO: Remove when the emulator supports untyped parameters.
if isEmulatorEnvSet() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be !isEmulatorEnvSet() if the emulator env is not set?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep 👍

statements := make([]Statement, 0)
for i, test := range tests {
stmt := NewStatement(fmt.Sprintf("INSERT INTO Types (RowId, `%s`) VALUES (@id, @value)", test.col))
// Note: We are not setting the parameter type here to ensure that it
// can be automatically recognized when it is actually needed.
stmt.Params["id"] = i
stmt.Params["value"] = test.val
statements = append(statements, stmt)
}
_, err := client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *ReadWriteTransaction) error {
rowCounts, err := tx.BatchUpdate(ctx, statements)
if err != nil {
return err
}
if len(rowCounts) != len(tests) {
return fmt.Errorf("rowCounts length mismatch\nGot: %v\nWant: %v", len(rowCounts), len(tests))
}
for i, c := range rowCounts {
if c != 1 {
return fmt.Errorf("row count mismatch for row %v:\nGot: %v\nWant: %v", i, c, 1)
}
}
return nil
})
if err != nil {
t.Fatalf("failed to insert values using DML: %v", err)
}
// Delete all the rows so we can insert them using mutations as well.
_, err = client.Apply(ctx, []*Mutation{Delete("Types", AllKeys())})
if err != nil {
t.Fatalf("failed to delete all rows: %v", err)
}
}

// Write rows into table first.
// Verify that we can insert the rows using mutations.
var muts []*Mutation
for i, test := range tests {
muts = append(muts, InsertOrUpdate("Types", []string{"RowID", test.col}, []interface{}{i, test.val}))
Expand Down
16 changes: 3 additions & 13 deletions spanner/statement.go
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package spanner

import (
"errors"
"fmt"

proto3 "github.com/golang/protobuf/ptypes/struct"
Expand Down Expand Up @@ -48,11 +47,6 @@ func NewStatement(sql string) Statement {
return Statement{SQL: sql, Params: map[string]interface{}{}}
}

var (
errNilParam = errors.New("use T(nil), not nil")
errNoType = errors.New("no type information")
)

// convertParams converts a statement's parameters into proto Param and
// ParamTypes.
func (s *Statement) convertParams() (*structpb.Struct, map[string]*sppb.Type, error) {
Expand All @@ -61,18 +55,14 @@ func (s *Statement) convertParams() (*structpb.Struct, map[string]*sppb.Type, er
}
paramTypes := map[string]*sppb.Type{}
for k, v := range s.Params {
if v == nil {
return nil, nil, errBindParam(k, v, errNilParam)
}
val, t, err := encodeValue(v)
if err != nil {
return nil, nil, errBindParam(k, v, err)
}
if t == nil { // should not happen, because of nil check above
return nil, nil, errBindParam(k, v, errNoType)
}
params.Fields[k] = val
paramTypes[k] = t
if t != nil {
paramTypes[k] = t
}
}

return params, paramTypes, nil
Expand Down
23 changes: 6 additions & 17 deletions spanner/statement_test.go
Expand Up @@ -159,6 +159,12 @@ func TestConvertParams(t *testing.T) {
listProto(listProto(intProto(10)), listProto(intProto(20))),
listType(structType(mkField("field", intType()))),
},
// Untyped null
{
nil,
nullProto(),
nil,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious: would this work? Because it expects a *sppb.Type but we give nothing, e.g.,

func numericType() *sppb.Type {
	return &sppb.Type{Code: sppb.TypeCode_NUMERIC}
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this test it would fail, as the test will verify that the param type is not set (or set to nil). That comparison will fail if we set it to TypeCode_NUMERIC. If we were to do something like that on production, it will also fail. I tried it out with the integration test, and it will refuse to insert a NULL value with type NUMERIC into a STRING column:

failed to insert values using DML: spanner: code = "InvalidArgument", desc = "Value has type NUMERIC which cannot be inserted into column String, which has type STRING [at 1:50]\\nINSERT INTO Types (RowId, `String`) VALUES (@id, @value)

},
} {
st.Params["var"] = test.val
gotParams, gotParamTypes, gotErr := st.convertParams()
Expand All @@ -179,23 +185,6 @@ func TestConvertParams(t *testing.T) {
t.Errorf("%#v: got %v, want %v\n", test.val, gotParamType, test.wantField)
}
}

// Verify type error reporting.
for _, test := range []struct {
val interface{}
wantErr error
}{
{
nil,
errBindParam("var", nil, errNilParam),
},
} {
st.Params["var"] = test.val
_, _, gotErr := st.convertParams()
if !testEqual(gotErr, test.wantErr) {
t.Errorf("value %#v:\ngot: %v\nwant: %v", test.val, gotErr, test.wantErr)
}
}
}

func TestNewStatement(t *testing.T) {
Expand Down