本文整理汇总了Golang中github.com/cockroachdb/cockroach/pkg/sql/parser.DBytes函数的典型用法代码示例。如果您正苦于以下问题:Golang DBytes函数的具体用法?Golang DBytes怎么用?Golang DBytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DBytes函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: SetUIData
// SetUIData is an endpoint that stores the given key/value pairs in the
// system.ui table. See GetUIData for more details on semantics.
func (s *adminServer) SetUIData(
ctx context.Context, req *serverpb.SetUIDataRequest,
) (*serverpb.SetUIDataResponse, error) {
if len(req.KeyValues) == 0 {
return nil, grpc.Errorf(codes.InvalidArgument, "KeyValues cannot be empty")
}
args := sql.SessionArgs{User: s.getUser(req)}
session := s.NewSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
for key, val := range req.KeyValues {
// Do an upsert of the key. We update each key in a separate transaction to
// avoid long-running transactions and possible deadlocks.
br := s.server.sqlExecutor.ExecuteStatements(session, "BEGIN;", nil)
defer br.Close()
if err := s.checkQueryResults(br.ResultList, 1); err != nil {
return nil, s.serverError(err)
}
// See if the key already exists.
resp, err := s.getUIData(session, s.getUser(req), []string{key})
if err != nil {
return nil, s.serverError(err)
}
_, alreadyExists := resp.KeyValues[key]
// INSERT or UPDATE as appropriate.
if alreadyExists {
query := "UPDATE system.ui SET value = $1, lastUpdated = NOW() WHERE key = $2; COMMIT;"
qargs := parser.NewPlaceholderInfo()
qargs.SetValue(`1`, parser.NewDString(string(val)))
qargs.SetValue(`2`, parser.NewDString(key))
r := s.server.sqlExecutor.ExecuteStatements(session, query, qargs)
defer r.Close()
if err := s.checkQueryResults(r.ResultList, 2); err != nil {
return nil, s.serverError(err)
}
if a, e := r.ResultList[0].RowsAffected, 1; a != e {
return nil, s.serverErrorf("rows affected %d != expected %d", a, e)
}
} else {
query := "INSERT INTO system.ui (key, value, lastUpdated) VALUES ($1, $2, NOW()); COMMIT;"
qargs := parser.NewPlaceholderInfo()
qargs.SetValue(`1`, parser.NewDString(key))
qargs.SetValue(`2`, parser.NewDBytes(parser.DBytes(val)))
r := s.server.sqlExecutor.ExecuteStatements(session, query, qargs)
defer r.Close()
if err := s.checkQueryResults(r.ResultList, 2); err != nil {
return nil, s.serverError(err)
}
if a, e := r.ResultList[0].RowsAffected, 1; a != e {
return nil, s.serverErrorf("rows affected %d != expected %d", a, e)
}
}
}
return &serverpb.SetUIDataResponse{}, nil
}
开发者ID:knz,项目名称:cockroach,代码行数:61,代码来源:admin.go
示例2: golangFillQueryArguments
// golangFillQueryArguments populates the placeholder map with
// types and values from an array of Go values.
// TODO: This does not support arguments of the SQL 'Date' type, as there is not
// an equivalent type in Go's standard library. It's not currently needed by any
// of our internal tables.
func golangFillQueryArguments(pinfo *parser.PlaceholderInfo, args []interface{}) {
pinfo.Clear()
for i, arg := range args {
k := fmt.Sprint(i + 1)
if arg == nil {
pinfo.SetValue(k, parser.DNull)
continue
}
// A type switch to handle a few explicit types with special semantics:
// - Datums are passed along as is.
// - Time datatypes get special representation in the database.
var d parser.Datum
switch t := arg.(type) {
case parser.Datum:
d = t
case time.Time:
d = parser.MakeDTimestamp(t, time.Microsecond)
case time.Duration:
d = &parser.DInterval{Duration: duration.Duration{Nanos: t.Nanoseconds()}}
case *inf.Dec:
dd := &parser.DDecimal{}
dd.Set(t)
d = dd
}
if d == nil {
// Handle all types which have an underlying type that can be stored in the
// database.
// Note: if this reflection becomes a performance concern in the future,
// commonly used types could be added explicitly into the type switch above
// for a performance gain.
val := reflect.ValueOf(arg)
switch val.Kind() {
case reflect.Bool:
d = parser.MakeDBool(parser.DBool(val.Bool()))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
d = parser.NewDInt(parser.DInt(val.Int()))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
d = parser.NewDInt(parser.DInt(val.Uint()))
case reflect.Float32, reflect.Float64:
d = parser.NewDFloat(parser.DFloat(val.Float()))
case reflect.String:
d = parser.NewDString(val.String())
case reflect.Slice:
// Handle byte slices.
if val.Type().Elem().Kind() == reflect.Uint8 {
d = parser.NewDBytes(parser.DBytes(val.Bytes()))
}
}
if d == nil {
panic(fmt.Sprintf("unexpected type %T", arg))
}
}
pinfo.SetValue(k, d)
}
}
开发者ID:hvaara,项目名称:cockroach,代码行数:62,代码来源:executor.go
示例3: DecodeTableValue
// DecodeTableValue decodes a value encoded by EncodeTableValue.
func DecodeTableValue(a *DatumAlloc, valType parser.Type, b []byte) (parser.Datum, []byte, error) {
_, dataOffset, _, typ, err := encoding.DecodeValueTag(b)
if err != nil {
return nil, b, err
}
if typ == encoding.Null {
return parser.DNull, b[dataOffset:], nil
}
switch valType {
case parser.TypeBool:
var x bool
b, x, err = encoding.DecodeBoolValue(b)
// No need to chunk allocate DBool as MakeDBool returns either
// parser.DBoolTrue or parser.DBoolFalse.
return parser.MakeDBool(parser.DBool(x)), b, err
case parser.TypeInt:
var i int64
b, i, err = encoding.DecodeIntValue(b)
return a.NewDInt(parser.DInt(i)), b, err
case parser.TypeFloat:
var f float64
b, f, err = encoding.DecodeFloatValue(b)
return a.NewDFloat(parser.DFloat(f)), b, err
case parser.TypeDecimal:
var d *inf.Dec
b, d, err = encoding.DecodeDecimalValue(b)
dd := a.NewDDecimal(parser.DDecimal{})
dd.Set(d)
return dd, b, err
case parser.TypeString:
var data []byte
b, data, err = encoding.DecodeBytesValue(b)
return a.NewDString(parser.DString(data)), b, err
case parser.TypeBytes:
var data []byte
b, data, err = encoding.DecodeBytesValue(b)
return a.NewDBytes(parser.DBytes(data)), b, err
case parser.TypeDate:
var i int64
b, i, err = encoding.DecodeIntValue(b)
return a.NewDDate(parser.DDate(i)), b, err
case parser.TypeTimestamp:
var t time.Time
b, t, err = encoding.DecodeTimeValue(b)
return a.NewDTimestamp(parser.DTimestamp{Time: t}), b, err
case parser.TypeTimestampTZ:
var t time.Time
b, t, err = encoding.DecodeTimeValue(b)
return a.NewDTimestampTZ(parser.DTimestampTZ{Time: t}), b, err
case parser.TypeInterval:
var d duration.Duration
b, d, err = encoding.DecodeDurationValue(b)
return a.NewDInterval(parser.DInterval{Duration: d}), b, err
default:
return nil, nil, errors.Errorf("TODO(pmattis): decoded index value: %s", valType)
}
}
开发者ID:jmptrader,项目名称:cockroach,代码行数:58,代码来源:table.go
示例4: RandDatum
// RandDatum generates a random Datum of the given type.
// If null is true, the datum can be DNull.
func RandDatum(rng *rand.Rand, typ ColumnType_Kind, null bool) parser.Datum {
if null && rng.Intn(10) == 0 {
return parser.DNull
}
switch typ {
case ColumnType_BOOL:
return parser.MakeDBool(rng.Intn(2) == 1)
case ColumnType_INT:
return parser.NewDInt(parser.DInt(rng.Int63()))
case ColumnType_FLOAT:
return parser.NewDFloat(parser.DFloat(rng.NormFloat64()))
case ColumnType_DECIMAL:
d := &parser.DDecimal{}
d.Dec.SetScale(inf.Scale(rng.Intn(40) - 20))
d.Dec.SetUnscaled(rng.Int63())
return d
case ColumnType_DATE:
return parser.NewDDate(parser.DDate(rng.Intn(10000)))
case ColumnType_TIMESTAMP:
return &parser.DTimestamp{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
case ColumnType_INTERVAL:
return &parser.DInterval{Duration: duration.Duration{Months: rng.Int63n(1000),
Days: rng.Int63n(1000),
Nanos: rng.Int63n(1000000),
}}
case ColumnType_STRING:
// Generate a random ASCII string.
p := make([]byte, rng.Intn(10))
for i := range p {
p[i] = byte(1 + rng.Intn(127))
}
return parser.NewDString(string(p))
case ColumnType_BYTES:
p := make([]byte, rng.Intn(10))
_, _ = rng.Read(p)
return parser.NewDBytes(parser.DBytes(p))
case ColumnType_TIMESTAMPTZ:
return &parser.DTimestampTZ{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
case ColumnType_INT_ARRAY:
// TODO(cuongdo): we don't support for persistence of arrays yet
return parser.DNull
default:
panic(fmt.Sprintf("invalid type %s", typ))
}
}
开发者ID:jmptrader,项目名称:cockroach,代码行数:47,代码来源:testutils.go
示例5: TestAdminAPIZoneDetails
// TestAdminAPIZoneDetails verifies the zone configuration information returned
// for both DatabaseDetailsResponse AND TableDetailsResponse.
func TestAdminAPIZoneDetails(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop()
ts := s.(*TestServer)
// Create database and table.
ac := log.AmbientContext{Tracer: tracing.NewTracer()}
ctx, span := ac.AnnotateCtxWithSpan(context.Background(), "test")
defer span.Finish()
session := sql.NewSession(
ctx, sql.SessionArgs{User: security.RootUser}, ts.sqlExecutor, nil, &sql.MemoryMetrics{})
session.StartUnlimitedMonitor()
setupQueries := []string{
"CREATE DATABASE test",
"CREATE TABLE test.tbl (val STRING)",
}
for _, q := range setupQueries {
res := ts.sqlExecutor.ExecuteStatements(session, q, nil)
defer res.Close()
if res.ResultList[0].Err != nil {
t.Fatalf("error executing '%s': %s", q, res.ResultList[0].Err)
}
}
// Function to verify the zone for table "test.tbl" as returned by the Admin
// API.
verifyTblZone := func(
expectedZone config.ZoneConfig, expectedLevel serverpb.ZoneConfigurationLevel,
) {
var resp serverpb.TableDetailsResponse
if err := getAdminJSONProto(s, "databases/test/tables/tbl", &resp); err != nil {
t.Fatal(err)
}
if a, e := &resp.ZoneConfig, &expectedZone; !proto.Equal(a, e) {
t.Errorf("actual table zone config %v did not match expected value %v", a, e)
}
if a, e := resp.ZoneConfigLevel, expectedLevel; a != e {
t.Errorf("actual table ZoneConfigurationLevel %s did not match expected value %s", a, e)
}
if t.Failed() {
t.FailNow()
}
}
// Function to verify the zone for database "test" as returned by the Admin
// API.
verifyDbZone := func(
expectedZone config.ZoneConfig, expectedLevel serverpb.ZoneConfigurationLevel,
) {
var resp serverpb.DatabaseDetailsResponse
if err := getAdminJSONProto(s, "databases/test", &resp); err != nil {
t.Fatal(err)
}
if a, e := &resp.ZoneConfig, &expectedZone; !proto.Equal(a, e) {
t.Errorf("actual db zone config %v did not match expected value %v", a, e)
}
if a, e := resp.ZoneConfigLevel, expectedLevel; a != e {
t.Errorf("actual db ZoneConfigurationLevel %s did not match expected value %s", a, e)
}
if t.Failed() {
t.FailNow()
}
}
// Function to store a zone config for a given object ID.
setZone := func(zoneCfg config.ZoneConfig, id sqlbase.ID) {
zoneBytes, err := zoneCfg.Marshal()
if err != nil {
t.Fatal(err)
}
const query = `INSERT INTO system.zones VALUES($1, $2)`
params := parser.NewPlaceholderInfo()
params.SetValue(`1`, parser.NewDInt(parser.DInt(id)))
params.SetValue(`2`, parser.NewDBytes(parser.DBytes(zoneBytes)))
res := ts.sqlExecutor.ExecuteStatements(session, query, params)
defer res.Close()
if res.ResultList[0].Err != nil {
t.Fatalf("error executing '%s': %s", query, res.ResultList[0].Err)
}
}
// Verify zone matches cluster default.
verifyDbZone(config.DefaultZoneConfig(), serverpb.ZoneConfigurationLevel_CLUSTER)
verifyTblZone(config.DefaultZoneConfig(), serverpb.ZoneConfigurationLevel_CLUSTER)
// Get ID path for table. This will be an array of three IDs, containing the ID of the root namespace,
// the database, and the table (in that order).
idPath, err := ts.admin.queryDescriptorIDPath(session, []string{"test", "tbl"})
if err != nil {
t.Fatal(err)
}
// Apply zone configuration to database and check again.
dbZone := config.ZoneConfig{
RangeMinBytes: 456,
}
setZone(dbZone, idPath[1])
//.........这里部分代码省略.........
开发者ID:veteranlu,项目名称:cockroach,代码行数:101,代码来源:admin_test.go
示例6: dumpTable
//.........这里部分代码省略.........
inserts := make([][]string, 0, limit)
i := 0
for i < limit {
vals := make([]driver.Value, len(cols)+len(pkcols))
if err := rows.Next(vals); err == io.EOF {
break
} else if err != nil {
return err
}
if pk == nil {
q = fmt.Sprintf(bs, wbuf.String())
}
pk = vals[:len(index)]
vals = vals[len(index):]
ivals := make([]string, len(vals))
// Values need to be correctly encoded for INSERT statements in a text file.
for si, sv := range vals {
switch t := sv.(type) {
case nil:
ivals[si] = "NULL"
case bool:
ivals[si] = parser.MakeDBool(parser.DBool(t)).String()
case int64:
ivals[si] = parser.NewDInt(parser.DInt(t)).String()
case float64:
ivals[si] = parser.NewDFloat(parser.DFloat(t)).String()
case string:
ivals[si] = parser.NewDString(t).String()
case []byte:
switch ct := coltypes[cols[si]]; ct {
case "INTERVAL":
ivals[si] = fmt.Sprintf("'%s'", t)
case "BYTES":
ivals[si] = parser.NewDBytes(parser.DBytes(t)).String()
default:
// STRING and DECIMAL types can have optional length
// suffixes, so only examine the prefix of the type.
if strings.HasPrefix(coltypes[cols[si]], "STRING") {
ivals[si] = parser.NewDString(string(t)).String()
} else if strings.HasPrefix(coltypes[cols[si]], "DECIMAL") {
ivals[si] = string(t)
} else {
panic(errors.Errorf("unknown []byte type: %s, %v: %s", t, cols[si], coltypes[cols[si]]))
}
}
case time.Time:
var d parser.Datum
ct := coltypes[cols[si]]
switch ct {
case "DATE":
d = parser.NewDDateFromTime(t, time.UTC)
case "TIMESTAMP":
d = parser.MakeDTimestamp(t, time.Nanosecond)
case "TIMESTAMP WITH TIME ZONE":
d = parser.MakeDTimestampTZ(t, time.Nanosecond)
default:
panic(errors.Errorf("unknown timestamp type: %s, %v: %s", t, cols[si], coltypes[cols[si]]))
}
ivals[si] = fmt.Sprintf("'%s'", d)
default:
panic(errors.Errorf("unknown field type: %T (%s)", t, cols[si]))
}
}
inserts = append(inserts, ivals)
i++
}
开发者ID:hvaara,项目名称:cockroach,代码行数:67,代码来源:dump.go
示例7: DecodeTableKey
// DecodeTableKey decodes a table key/value.
func DecodeTableKey(
a *DatumAlloc, valType parser.Type, key []byte, dir encoding.Direction,
) (parser.Datum, []byte, error) {
if (dir != encoding.Ascending) && (dir != encoding.Descending) {
return nil, nil, errors.Errorf("invalid direction: %d", dir)
}
var isNull bool
if key, isNull = encoding.DecodeIfNull(key); isNull {
return parser.DNull, key, nil
}
var rkey []byte
var err error
switch valType {
case parser.TypeBool:
var i int64
if dir == encoding.Ascending {
rkey, i, err = encoding.DecodeVarintAscending(key)
} else {
rkey, i, err = encoding.DecodeVarintDescending(key)
}
// No need to chunk allocate DBool as MakeDBool returns either
// parser.DBoolTrue or parser.DBoolFalse.
return parser.MakeDBool(parser.DBool(i != 0)), rkey, err
case parser.TypeInt:
var i int64
if dir == encoding.Ascending {
rkey, i, err = encoding.DecodeVarintAscending(key)
} else {
rkey, i, err = encoding.DecodeVarintDescending(key)
}
return a.NewDInt(parser.DInt(i)), rkey, err
case parser.TypeFloat:
var f float64
if dir == encoding.Ascending {
rkey, f, err = encoding.DecodeFloatAscending(key)
} else {
rkey, f, err = encoding.DecodeFloatDescending(key)
}
return a.NewDFloat(parser.DFloat(f)), rkey, err
case parser.TypeDecimal:
var d *inf.Dec
if dir == encoding.Ascending {
rkey, d, err = encoding.DecodeDecimalAscending(key, nil)
} else {
rkey, d, err = encoding.DecodeDecimalDescending(key, nil)
}
dd := a.NewDDecimal(parser.DDecimal{})
dd.Set(d)
return dd, rkey, err
case parser.TypeString:
var r string
if dir == encoding.Ascending {
rkey, r, err = encoding.DecodeUnsafeStringAscending(key, nil)
} else {
rkey, r, err = encoding.DecodeUnsafeStringDescending(key, nil)
}
return a.NewDString(parser.DString(r)), rkey, err
case parser.TypeBytes:
var r []byte
if dir == encoding.Ascending {
rkey, r, err = encoding.DecodeBytesAscending(key, nil)
} else {
rkey, r, err = encoding.DecodeBytesDescending(key, nil)
}
return a.NewDBytes(parser.DBytes(r)), rkey, err
case parser.TypeDate:
var t int64
if dir == encoding.Ascending {
rkey, t, err = encoding.DecodeVarintAscending(key)
} else {
rkey, t, err = encoding.DecodeVarintDescending(key)
}
return a.NewDDate(parser.DDate(t)), rkey, err
case parser.TypeTimestamp:
var t time.Time
if dir == encoding.Ascending {
rkey, t, err = encoding.DecodeTimeAscending(key)
} else {
rkey, t, err = encoding.DecodeTimeDescending(key)
}
return a.NewDTimestamp(parser.DTimestamp{Time: t}), rkey, err
case parser.TypeTimestampTZ:
var t time.Time
if dir == encoding.Ascending {
rkey, t, err = encoding.DecodeTimeAscending(key)
} else {
rkey, t, err = encoding.DecodeTimeDescending(key)
}
return a.NewDTimestampTZ(parser.DTimestampTZ{Time: t}), rkey, err
case parser.TypeInterval:
var d duration.Duration
if dir == encoding.Ascending {
rkey, d, err = encoding.DecodeDurationAscending(key)
} else {
rkey, d, err = encoding.DecodeDurationDescending(key)
}
return a.NewDInterval(parser.DInterval{Duration: d}), rkey, err
default:
return nil, nil, errors.Errorf("TODO(pmattis): decoded index key: %s", valType)
//.........这里部分代码省略.........
开发者ID:jmptrader,项目名称:cockroach,代码行数:101,代码来源:table.go
示例8: UnmarshalColumnValue
// UnmarshalColumnValue decodes the value from a key-value pair using the type
// expected by the column. An error is returned if the value's type does not
// match the column's type.
func UnmarshalColumnValue(
a *DatumAlloc, kind ColumnType_Kind, value *roachpb.Value,
) (parser.Datum, error) {
if value == nil {
return parser.DNull, nil
}
switch kind {
case ColumnType_BOOL:
v, err := value.GetBool()
if err != nil {
return nil, err
}
return parser.MakeDBool(parser.DBool(v)), nil
case ColumnType_INT:
v, err := value.GetInt()
if err != nil {
return nil, err
}
return a.NewDInt(parser.DInt(v)), nil
case ColumnType_FLOAT:
v, err := value.GetFloat()
if err != nil {
return nil, err
}
return a.NewDFloat(parser.DFloat(v)), nil
case ColumnType_DECIMAL:
v, err := value.GetDecimal()
if err != nil {
return nil, err
}
dd := a.NewDDecimal(parser.DDecimal{})
dd.Set(v)
return dd, nil
case ColumnType_STRING:
v, err := value.GetBytes()
if err != nil {
return nil, err
}
return a.NewDString(parser.DString(v)), nil
case ColumnType_BYTES:
v, err := value.GetBytes()
if err != nil {
return nil, err
}
return a.NewDBytes(parser.DBytes(v)), nil
case ColumnType_DATE:
v, err := value.GetInt()
if err != nil {
return nil, err
}
return a.NewDDate(parser.DDate(v)), nil
case ColumnType_TIMESTAMP:
v, err := value.GetTime()
if err != nil {
return nil, err
}
return a.NewDTimestamp(parser.DTimestamp{Time: v}), nil
case ColumnType_TIMESTAMPTZ:
v, err := value.GetTime()
if err != nil {
return nil, err
}
return a.NewDTimestampTZ(parser.DTimestampTZ{Time: v}), nil
case ColumnType_INTERVAL:
d, err := value.GetDuration()
if err != nil {
return nil, err
}
return a.NewDInterval(parser.DInterval{Duration: d}), nil
default:
return nil, errors.Errorf("unsupported column type: %s", kind)
}
}
开发者ID:jmptrader,项目名称:cockroach,代码行数:77,代码来源:table.go
示例9: decodeOidDatum
//.........这里部分代码省略.........
switch alloc.pgNum.sign {
case pgNumericPos:
case pgNumericNeg:
alloc.dd.Neg(&alloc.dd.Dec)
default:
return d, errors.Errorf("unsupported numeric sign: %d", alloc.pgNum.sign)
}
d = &alloc.dd
default:
return d, errors.Errorf("unsupported numeric format code: %d", code)
}
case oid.T_text, oid.T_varchar:
switch code {
case formatText, formatBinary:
d = parser.NewDString(string(b))
default:
return d, errors.Errorf("unsupported text format code: %d", code)
}
case oid.T_bytea:
switch code {
case formatText:
// http://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5667
// Code cribbed from github.com/lib/pq.
// We only support hex encoding.
if len(b) >= 2 && bytes.Equal(b[:2], []byte("\\x")) {
b = b[2:] // trim off leading "\\x"
result := make([]byte, hex.DecodedLen(len(b)))
_, err := hex.Decode(result, b)
if err != nil {
return d, err
}
d = parser.NewDBytes(parser.DBytes(result))
} else {
return d, errors.Errorf("unsupported bytea encoding: %q", b)
}
case formatBinary:
d = parser.NewDBytes(parser.DBytes(b))
default:
return d, errors.Errorf("unsupported bytea format code: %d", code)
}
case oid.T_timestamp:
switch code {
case formatText:
ts, err := parseTs(string(b))
if err != nil {
return d, errors.Errorf("could not parse string %q as timestamp", b)
}
d = parser.MakeDTimestamp(ts, time.Microsecond)
case formatBinary:
if len(b) < 8 {
return d, errors.Errorf("timestamp requires 8 bytes for binary format")
}
i := int64(binary.BigEndian.Uint64(b))
d = parser.MakeDTimestamp(pgBinaryToTime(i), time.Microsecond)
default:
return d, errors.Errorf("unsupported timestamp format code: %d", code)
}
case oid.T_timestamptz:
switch code {
case formatText:
ts, err := parseTs(string(b))
if err != nil {
return d, errors.Errorf("could not parse string %q as timestamp", b)
}
开发者ID:nvanbenschoten,项目名称:cockroach,代码行数:67,代码来源:types.go
示例10: RandDatum
// RandDatum generates a random Datum of the given type.
// If null is true, the datum can be DNull.
func RandDatum(rng *rand.Rand, typ ColumnType, null bool) parser.Datum {
if null && rng.Intn(10) == 0 {
return parser.DNull
}
switch typ.Kind {
case ColumnType_BOOL:
return parser.MakeDBool(rng.Intn(2) == 1)
case ColumnType_INT:
return parser.NewDInt(parser.DInt(rng.Int63()))
case ColumnType_FLOAT:
return parser.NewDFloat(parser.DFloat(rng.NormFloat64()))
case ColumnType_DECIMAL:
d := &parser.DDecimal{}
d.Dec.SetScale(inf.Scale(rng.Intn(40) - 20))
d.Dec.SetUnscaled(rng.Int63())
return d
case ColumnType_DATE:
return parser.NewDDate(parser.DDate(rng.Intn(10000)))
case ColumnType_TIMESTAMP:
return &parser.DTimestamp{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
case ColumnType_INTERVAL:
return &parser.DInterval{Duration: duration.Duration{Months: rng.Int63n(1000),
Days: rng.Int63n(1000),
Nanos: rng.Int63n(1000000),
}}
case ColumnType_STRING:
// Generate a random ASCII string.
p := make([]byte, rng.Intn(10))
for i := range p {
p[i] = byte(1 + rng.Intn(127))
}
return parser.NewDString(string(p))
case ColumnType_BYTES:
p := make([]byte, rng.Intn(10))
_, _ = rng.Read(p)
return parser.NewDBytes(parser.DBytes(p))
case ColumnType_TIMESTAMPTZ:
return &parser.DTimestampTZ{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
case ColumnType_COLLATEDSTRING:
if typ.Locale == nil {
panic("locale is required for COLLATEDSTRING")
}
// Generate a random Unicode string.
var buf bytes.Buffer
n := rng.Intn(10)
for i := 0; i < n; i++ {
var r rune
for {
r = rune(rng.Intn(unicode.MaxRune + 1))
if !unicode.Is(unicode.C, r) {
break
}
}
buf.WriteRune(r)
}
return parser.NewDCollatedString(buf.String(), *typ.Locale, &parser.CollationEnvironment{})
case ColumnType_INT_ARRAY:
// TODO(cuongdo): we don't support for persistence of arrays yet
return parser.DNull
default:
panic(fmt.Sprintf("invalid type %s", typ.String()))
}
}
开发者ID:BramGruneir,项目名称:cockroach,代码行数:65,代码来源:testutils.go
注:本文中的github.com/cockroachdb/cockroach/pkg/sql/parser.DBytes函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论