github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/sqlbase/roundtrip_format.go (about) 1 // Copyright 2020 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package sqlbase 12 13 import ( 14 "github.com/cockroachdb/cockroach/pkg/sql/parser" 15 "github.com/cockroachdb/cockroach/pkg/sql/sem/tree" 16 "github.com/cockroachdb/cockroach/pkg/sql/types" 17 ) 18 19 // ParseDatumStringAs parses s as type t. This function is guaranteed to 20 // round-trip when printing a Datum with FmtExport. 21 func ParseDatumStringAs(t *types.T, s string, evalCtx *tree.EvalContext) (tree.Datum, error) { 22 switch t.Family() { 23 // We use a different parser for array types because ParseAndRequireString only parses 24 // the internal postgres string representation of arrays. 25 case types.ArrayFamily, types.CollatedStringFamily: 26 return parseAsTyp(evalCtx, t, s) 27 default: 28 return tree.ParseAndRequireString(t, s, evalCtx) 29 } 30 } 31 32 // ParseDatumStringAsWithRawBytes parses s as type t. However, if the requested type is Bytes 33 // then the string is returned unchanged. This function is used when the input string might be 34 // unescaped raw bytes, so we don't want to run a bytes parsing routine on the input. Other 35 // than the bytes case, this function does the same as ParseDatumStringAs but is not 36 // guaranteed to round-trip. 37 func ParseDatumStringAsWithRawBytes( 38 t *types.T, s string, evalCtx *tree.EvalContext, 39 ) (tree.Datum, error) { 40 switch t.Family() { 41 case types.BytesFamily: 42 return tree.NewDBytes(tree.DBytes(s)), nil 43 default: 44 return ParseDatumStringAs(t, s, evalCtx) 45 } 46 } 47 48 func parseAsTyp(evalCtx *tree.EvalContext, typ *types.T, s string) (tree.Datum, error) { 49 expr, err := parser.ParseExpr(s) 50 if err != nil { 51 return nil, err 52 } 53 semaCtx := tree.MakeSemaContext() 54 typedExpr, err := tree.TypeCheck(evalCtx.Context, expr, &semaCtx, typ) 55 if err != nil { 56 return nil, err 57 } 58 datum, err := typedExpr.Eval(evalCtx) 59 return datum, err 60 }