sqltypes

package
v0.18.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2024 License: Apache-2.0 Imports: 28 Imported by: 147

Documentation

Overview

Package sqltypes implements interfaces and types that represent SQL values.

Index

Constants

View Source
const (
	ServerStatusInTrans            = 0x0001
	ServerStatusAutocommit         = 0x0002
	ServerMoreResultsExists        = 0x0008
	ServerStatusNoGoodIndexUsed    = 0x0010
	ServerStatusNoIndexUsed        = 0x0020
	ServerStatusCursorExists       = 0x0040
	ServerStatusLastRowSent        = 0x0080
	ServerStatusDbDropped          = 0x0100
	ServerStatusNoBackslashEscapes = 0x0200
	ServerStatusMetadataChanged    = 0x0400
	ServerQueryWasSlow             = 0x0800
	ServerPsOutParams              = 0x1000
	ServerStatusInTransReadonly    = 0x2000
	ServerSessionStateChanged      = 0x4000
)
View Source
const (
	TimestampFormat           = "2006-01-02 15:04:05"
	TimestampFormatPrecision3 = "2006-01-02 15:04:05.000"
	TimestampFormatPrecision6 = "2006-01-02 15:04:05.000000"
)

Vitess data types. These are idiomatically named synonyms for the querypb.Type values. Although these constants are interchangeable, they should be treated as different from querypb.Type. Use the synonyms only to refer to the type in Value. For proto variables, use the querypb.Type constants instead. The following is a complete listing of types that match each classification function in this API:

IsSigned(): INT8, INT16, INT24, INT32, INT64
IsFloat(): FLOAT32, FLOAT64
IsUnsigned(): UINT8, UINT16, UINT24, UINT32, UINT64, YEAR
IsIntegral(): INT8, UINT8, INT16, UINT16, INT24, UINT24, INT32, UINT32, INT64, UINT64, YEAR
IsText(): TEXT, VARCHAR, CHAR, HEXNUM, HEXVAL, BITNUM
IsNumber(): INT8, UINT8, INT16, UINT16, INT24, UINT24, INT32, UINT32, INT64, UINT64, FLOAT32, FLOAT64, YEAR, DECIMAL
IsQuoted(): TIMESTAMP, DATE, TIME, DATETIME, TEXT, BLOB, VARCHAR, VARBINARY, CHAR, BINARY, ENUM, SET, GEOMETRY, JSON
IsBinary(): BLOB, VARBINARY, BINARY
IsDate(): TIMESTAMP, DATE, TIME, DATETIME
IsNull(): NULL_TYPE

TODO(sougou): provide a categorization function that returns enums, which will allow for cleaner switch statements for those who want to cover types by their category.

Variables

View Source
var (
	// BvSchemaName is bind variable to be sent down to vttablet for schema name.
	BvSchemaName = "__vtschemaname"

	// BvReplaceSchemaName is bind variable to be sent down to vttablet to replace schema name.
	BvReplaceSchemaName = "__replacevtschemaname"

	// NullBindVariable is a bindvar with NULL value.
	NullBindVariable = &querypb.BindVariable{Type: querypb.Type_NULL_TYPE}
)
View Source
var (
	// NULL represents the NULL value.
	NULL = Value{}

	// DontEscape tells you if a character should not be escaped.
	DontEscape = byte(255)
	NullStr    = "null"
	NullBytes  = []byte(NullStr)

	// ErrIncompatibleTypeCast indicates a casting problem
	ErrIncompatibleTypeCast = errors.New("Cannot convert value to desired type")
)
View Source
var ErrBadTupleEncoding = errors.New("bad tuple encoding in sqltypes.Value")
View Source
var (
	// ErrNoSuchField indicates a search for a value by an unknown field/column name
	ErrNoSuchField = errors.New("No such field in RowNamedValues")
)
View Source
var RandomGenerators = map[Type]RandomGenerator{
	Null: func() Value {
		return NULL
	},
	Int8: func() Value {
		return NewInt8(int8(rand.Intn(255)))
	},
	Int32: func() Value {
		return NewInt32(rand.Int31())
	},
	Int64: func() Value {
		return NewInt64(rand.Int63())
	},
	Uint32: func() Value {
		return NewUint32(rand.Uint32())
	},
	Uint64: func() Value {
		return NewUint64(rand.Uint64())
	},
	Float64: func() Value {
		return NewFloat64(rand.ExpFloat64())
	},
	Decimal: func() Value {
		dec := fmt.Sprintf("%d.%d", rand.Intn(9999999999), rand.Intn(9999999999))
		if rand.Int()&0x1 == 1 {
			dec = "-" + dec
		}
		return NewDecimal(dec)
	},
	VarChar: func() Value {
		return NewVarChar(base64.StdEncoding.EncodeToString(randomBytes()))
	},
	VarBinary: func() Value {
		return NewVarBinary(string(randomBytes()))
	},
	Date: func() Value {
		return NewDate(randTime().Format(time.DateOnly))
	},
	Datetime: func() Value {
		return NewDatetime(randTime().Format(time.DateTime))
	},
	Timestamp: func() Value {
		return NewTimestamp(randTime().Format(time.DateTime))
	},
	Time: func() Value {
		return NewTime(randTime().Format(time.TimeOnly))
	},
	TypeJSON: func() Value {
		var j string
		switch rand.Intn(6) {
		case 0:
			j = "null"
		case 1:
			i := rand.Int63()
			if rand.Int()&0x1 == 1 {
				i = -i
			}
			j = strconv.FormatInt(i, 10)
		case 2:
			j = strconv.FormatFloat(rand.NormFloat64(), 'g', -1, 64)
		case 3:
			j = strconv.Quote(hex.EncodeToString(randomBytes()))
		case 4:
			j = "true"
		case 5:
			j = "false"
		}
		v, err := NewJSON(j)
		if err != nil {
			panic(err)
		}
		return v
	},
}
View Source
var SQLDecodeMap [256]byte

SQLDecodeMap is the reverse of SQLEncodeMap

View Source
var SQLEncodeMap [256]byte

SQLEncodeMap specifies how to escape binary data with '\'. Complies to https://dev.mysql.com/doc/refman/5.7/en/string-literals.html Handling escaping of % and _ is different than other characters. When escaped in a like clause, they are supposed to be treated as literals Everywhere else, they evaluate to strings '\%' and '\_' respectively. In Vitess, the way we are choosing to handle this behaviour is to always preserve the escaping of % and _ as is in all the places and handle it like MySQL in our evaluation engine for Like.

Functions

func AreTypesEquivalent

func AreTypesEquivalent(mysqlTypeFromBinlog, mysqlTypeFromSchema querypb.Type) bool

AreTypesEquivalent returns whether two types are equivalent.

func BindVariablesEqual

func BindVariablesEqual(x, y map[string]*querypb.BindVariable) bool

BindVariablesEqual compares two maps of bind variables. For protobuf messages we have to use "proto.Equal".

func BitNumBindVariable added in v0.15.0

func BitNumBindVariable(v []byte) *querypb.BindVariable

BitNumBindVariable converts bytes representing a bit encoded string to a bind var.

func BoolBindVariable added in v0.8.0

func BoolBindVariable(v bool) *querypb.BindVariable

BoolBindVariable converts an bool to a int64 bind var.

func BufEncodeStringSQL added in v0.10.0

func BufEncodeStringSQL(buf *strings.Builder, val string)

BufEncodeStringSQL encodes the string into a strings.Builder

func BuildBindVariable

func BuildBindVariable(v any) (*querypb.BindVariable, error)

BuildBindVariable builds a *querypb.BindVariable from a valid input type.

func BuildBindVariables

func BuildBindVariables(in map[string]any) (map[string]*querypb.BindVariable, error)

BuildBindVariables builds a map[string]*querypb.BindVariable from a map[string]any

func BytesBindVariable

func BytesBindVariable(v []byte) *querypb.BindVariable

BytesBindVariable converts a []byte to a bind var.

func CopyBindVariables

func CopyBindVariables(bindVariables map[string]*querypb.BindVariable) map[string]*querypb.BindVariable

CopyBindVariables returns a shallow-copy of the given bindVariables map.

func DecimalBindVariable added in v0.13.0

func DecimalBindVariable(v DecimalString) *querypb.BindVariable

func EncodeStringSQL added in v0.10.0

func EncodeStringSQL(val string) string

EncodeStringSQL encodes the string as a SQL string.

func EventTokenMinimum

func EventTokenMinimum(ev1, ev2 *querypb.EventToken) *querypb.EventToken

EventTokenMinimum returns an event token that is guaranteed to happen before both provided EventToken objects. Note it doesn't parse the position, but rather only uses the timestamp. This is meant to be used for EventToken objects coming from different source shard.

func FieldsEqual

func FieldsEqual(f1, f2 []*querypb.Field) bool

FieldsEqual compares two arrays of fields. reflect.DeepEqual shouldn't be used because of the protos.

func Float64BindVariable

func Float64BindVariable(v float64) *querypb.BindVariable

Float64BindVariable converts a float64 to a bind var.

func FormatBindVariables

func FormatBindVariables(bindVariables map[string]*querypb.BindVariable, full, asJSON bool) string

FormatBindVariables returns a string representation of the bind variables.

If full is false, then large string or tuple values are truncated to only print the lengths.

If asJson is true, then the resulting string is a valid JSON representation, otherwise it is the golang printed map representation.

func HexNumBindVariable added in v0.12.1

func HexNumBindVariable(v []byte) *querypb.BindVariable

HexNumBindVariable converts bytes representing a hex number to a bind var.

func HexValBindVariable added in v0.12.1

func HexValBindVariable(v []byte) *querypb.BindVariable

HexValBindVariable converts bytes representing a hex encoded string to a bind var.

func IncludeFieldsOrDefault

func IncludeFieldsOrDefault(options *querypb.ExecuteOptions) querypb.ExecuteOptions_IncludedFields

IncludeFieldsOrDefault normalizes the passed Execution Options. It returns the default value if options is nil.

func Int32BindVariable

func Int32BindVariable(v int32) *querypb.BindVariable

Int32BindVariable converts an int32 to a bind var.

func Int64BindVariable

func Int64BindVariable(v int64) *querypb.BindVariable

Int64BindVariable converts an int64 to a bind var.

func Int8BindVariable

func Int8BindVariable(v int8) *querypb.BindVariable

Int8BindVariable converts an int8 to a bind var.

func IsBinary

func IsBinary(t querypb.Type) bool

IsBinary returns true if querypb.Type is a binary. If you have a Value object, use its member function.

func IsDate added in v0.13.0

func IsDate(t querypb.Type) bool

IsDate returns true if the type has a date component

func IsDateOrTime added in v0.17.0

func IsDateOrTime(t querypb.Type) bool

IsDateOrTime returns true if the type represents a date and/or time.

func IsDecimal added in v0.17.0

func IsDecimal(t querypb.Type) bool

IsDecimal returns true is querypb.Type is a decimal. If you have a Value object, use its member function.

func IsFloat

func IsFloat(t querypb.Type) bool

IsFloat returns true is querypb.Type is a floating point. If you have a Value object, use its member function.

func IsIntegral

func IsIntegral(t querypb.Type) bool

IsIntegral returns true if querypb.Type is an integral (signed/unsigned) that can be represented using up to 64 binary bits. If you have a Value object, use its member function.

func IsNull added in v0.13.0

func IsNull(t querypb.Type) bool

IsNull returns true if the type is NULL type

func IsNumber

func IsNumber(t querypb.Type) bool

IsNumber returns true if the type is any type of number.

func IsQuoted

func IsQuoted(t querypb.Type) bool

IsQuoted returns true if querypb.Type is a quoted text or binary. If you have a Value object, use its member function.

func IsSigned

func IsSigned(t querypb.Type) bool

IsSigned returns true if querypb.Type is a signed integral. If you have a Value object, use its member function.

func IsText

func IsText(t querypb.Type) bool

IsText returns true if querypb.Type is a text. If you have a Value object, use its member function.

func IsUnsigned

func IsUnsigned(t querypb.Type) bool

IsUnsigned returns true if querypb.Type is an unsigned integral. Caution: this is not the same as !IsSigned. If you have a Value object, use its member function.

func MakeTestFields

func MakeTestFields(names, types string) []*querypb.Field

MakeTestFields builds a []*querypb.Field for testing.

fields := sqltypes.MakeTestFields(
  "a|b",
  "int64|varchar",
)

The field types are as defined in querypb and are case insensitive. Column delimiters must be used only to sepearate strings and not at the beginning or the end.

func MySQLToType

func MySQLToType(mysqlType, flags int64) (typ querypb.Type, err error)

MySQLToType computes the vitess type from mysql type and flags.

func PrintResults

func PrintResults(results []*Result) string

PrintResults prints []*Results into a string. This function should only be used for testing.

func Proto3QueryResponsesEqual

func Proto3QueryResponsesEqual(r1, r2 []*querypb.ResultWithError) bool

Proto3QueryResponsesEqual compares two arrays of proto3 QueryResponse. reflect.DeepEqual shouldn't be used because of the protos.

func Proto3ResultsEqual

func Proto3ResultsEqual(r1, r2 []*querypb.QueryResult) bool

Proto3ResultsEqual compares two arrays of proto3 Result. reflect.DeepEqual shouldn't be used because of the protos.

func Proto3ValuesEqual

func Proto3ValuesEqual(v1, v2 []*querypb.Value) bool

Proto3ValuesEqual compares two arrays of proto3 Value.

func QueryResponsesEqual

func QueryResponsesEqual(r1, r2 []QueryResponse) bool

QueryResponsesEqual compares two arrays of QueryResponse. They contain protos, so we cannot use reflect.DeepEqual.

func QueryResponsesToProto3

func QueryResponsesToProto3(qr []QueryResponse) []*querypb.ResultWithError

QueryResponsesToProto3 converts []QueryResponse to proto3.

func ResultToProto3

func ResultToProto3(qr *Result) *querypb.QueryResult

ResultToProto3 converts Result to proto3.

func ResultsEqual

func ResultsEqual(r1, r2 []Result) bool

ResultsEqual compares two arrays of Result. reflect.DeepEqual shouldn't be used because of the protos.

func ResultsEqualUnordered added in v0.12.0

func ResultsEqualUnordered(r1, r2 []Result) bool

ResultsEqualUnordered compares two unordered arrays of Result.

func ResultsToProto3

func ResultsToProto3(qr []Result) []*querypb.QueryResult

ResultsToProto3 converts []Result to proto3.

func RowToProto3

func RowToProto3(row []Value) *querypb.Row

RowToProto3 converts []Value to proto3.

func RowToProto3Inplace added in v0.11.0

func RowToProto3Inplace(row []Value, result *querypb.Row) int

RowToProto3Inplace converts []Value to proto3 and stores the conversion in the provided Row

func RowsEquals added in v0.16.7

func RowsEquals(want, got []Row) error

func RowsEqualsStr added in v0.16.7

func RowsEqualsStr(wantStr string, got []Row) error

func RowsToProto3

func RowsToProto3(rows [][]Value) []*querypb.Row

RowsToProto3 converts [][]Value to proto3.

func StringBindVariable

func StringBindVariable(v string) *querypb.BindVariable

StringBindVariable converts a string to a bind var.

func TestBindVariable

func TestBindVariable(v any) *querypb.BindVariable

TestBindVariable makes a *querypb.BindVariable from any. It panics on invalid input. This function should only be used for testing.

func TestRandomValues added in v0.18.0

func TestRandomValues() (Value, Value)

func TupleToProto added in v0.18.0

func TupleToProto(v []Value) *querypb.Value

func TypeToMySQL

func TypeToMySQL(typ querypb.Type) (mysqlType, flags int64)

TypeToMySQL returns the equivalent mysql type and flag for a vitess type.

func Uint32BindVariable added in v0.14.0

func Uint32BindVariable(v uint32) *querypb.BindVariable

Uint32BindVariable converts a uint32 to a bind var.

func Uint64BindVariable

func Uint64BindVariable(v uint64) *querypb.BindVariable

Uint64BindVariable converts a uint64 to a bind var.

func ValidateBindVariable

func ValidateBindVariable(bv *querypb.BindVariable) error

ValidateBindVariable returns an error if the bind variable has inconsistent fields.

func ValidateBindVariables

func ValidateBindVariables(bv map[string]*querypb.BindVariable) error

ValidateBindVariables validates a map[string]*querypb.BindVariable.

func ValueBindVariable

func ValueBindVariable(v Value) *querypb.BindVariable

ValueBindVariable converts a Value to a bind var.

func ValueToProto

func ValueToProto(v Value) *querypb.Value

ValueToProto converts Value to a *querypb.Value.

Types

type BinWriter

type BinWriter interface {
	Write([]byte) (int, error)
}

BinWriter interface is used for encoding values. Types like bytes.Buffer conform to this interface. We expect the writer objects to be in-memory buffers. So, we don't expect the write operations to fail.

type DecimalString added in v0.17.0

type DecimalString string

type NamedResult added in v0.8.0

type NamedResult struct {
	Fields       []*querypb.Field `json:"fields"`
	RowsAffected uint64           `json:"rows_affected"`
	InsertID     uint64           `json:"insert_id"`
	Rows         []RowNamedValues `json:"rows"`
}

NamedResult represents a query result with named values as opposed to ordinal values.

func ToNamedResult added in v0.8.0

func ToNamedResult(result *Result) (r *NamedResult)

ToNamedResult converts a Result struct into a new NamedResult struct

func (*NamedResult) Row added in v0.8.0

func (r *NamedResult) Row() RowNamedValues

Row assumes this result has exactly one row, and returns it, or else returns nil. It is useful for queries like: - select count(*) from ... - select @@read_only - select UNIX_TIMESTAMP() from dual

type QueryResponse

type QueryResponse struct {
	QueryResult *Result
	QueryError  error
}

QueryResponse represents a query response for ExecuteBatch.

func Proto3ToQueryReponses

func Proto3ToQueryReponses(qr []*querypb.ResultWithError) []QueryResponse

Proto3ToQueryReponses converts proto3 queryResponse to []QueryResponse.

type RandomGenerator added in v0.18.0

type RandomGenerator func() Value

type Result

type Result struct {
	Fields              []*querypb.Field `json:"fields"`
	RowsAffected        uint64           `json:"rows_affected"`
	InsertID            uint64           `json:"insert_id"`
	Rows                []Row            `json:"rows"`
	SessionStateChanges string           `json:"session_state_changes"`
	StatusFlags         uint16           `json:"status_flags"`
	Info                string           `json:"info"`
}

Result represents a query result.

func CustomProto3ToResult

func CustomProto3ToResult(fields []*querypb.Field, qr *querypb.QueryResult) *Result

CustomProto3ToResult converts a proto3 Result to an internal data structure. This function takes a separate fields input because not all QueryResults contain the field info. In particular, only the first packet of streaming queries contain the field info.

func MakeTestResult

func MakeTestResult(fields []*querypb.Field, rows ...string) *Result

MakeTestResult builds a *sqltypes.Result object for testing.

result := sqltypes.MakeTestResult(
  fields,
  " 1|a",
  "10|abcd",
)

The field type values are set as the types for the rows built. Spaces are trimmed from row values. "null" is treated as NULL.

func MakeTestStreamingResults

func MakeTestStreamingResults(fields []*querypb.Field, rows ...string) []*Result

MakeTestStreamingResults builds a list of results for streaming.

  results := sqltypes.MakeStreamingResults(
    fields,
		 "1|a",
    "2|b",
    "---",
    "c|c",
  )

The first result contains only the fields. Subsequent results are built using the field types. Every input that starts with a "-" is treated as streaming delimiter for one result. A final delimiter must not be supplied.

func MarshalResult added in v0.18.0

func MarshalResult(v any) (*Result, error)

MarshalResult marshals the object into a Result object. It is semi-complete.

func Proto3ToResult

func Proto3ToResult(qr *querypb.QueryResult) *Result

Proto3ToResult converts a proto3 Result to an internal data structure. This function should be used only if the field info is populated in qr.

func Proto3ToResults

func Proto3ToResults(qr []*querypb.QueryResult) []Result

Proto3ToResults converts proto3 results to []Result.

func ReplaceFields added in v0.18.0

func ReplaceFields(result *Result, remap map[string]string) *Result

ReplaceFields remaps the fields and/or row columns of a given result. This is useful when you need to embed a struct to modify its marshalling behavior, then cleanup or otherwise transfer the redunant fields. For example:

| uuid | tablet | retries | migration_uuid | $$tablet | | abc | --- | 1 | abc | zone1-101 |

=> becomes

| migration_uuid | tablet | retries | | abc | zone1-101 | 1 |

func (*Result) AppendResult

func (result *Result) AppendResult(src *Result)

AppendResult will combine the Results Objects of one result to another result.Note currently it doesn't handle cases like if two results have different fields.We will enhance this function.

func (*Result) CachedSize added in v0.11.0

func (cached *Result) CachedSize(alloc bool) int64

func (*Result) Copy

func (result *Result) Copy() *Result

Copy creates a deep copy of Result.

func (*Result) Equal

func (result *Result) Equal(other *Result) bool

Equal compares the Result with another one. reflect.DeepEqual shouldn't be used because of the protos.

func (*Result) IsInTransaction added in v0.10.0

func (result *Result) IsInTransaction() bool

IsInTransaction returns true if the status flag has SERVER_STATUS_IN_TRANS set

func (*Result) IsMoreResultsExists added in v0.10.0

func (result *Result) IsMoreResultsExists() bool

IsMoreResultsExists returns true if the status flag has SERVER_MORE_RESULTS_EXISTS set

func (*Result) Metadata added in v0.16.0

func (result *Result) Metadata() *Result

Metadata creates a shallow copy of Result without the rows useful for sending as a first packet in streaming results.

func (*Result) Named added in v0.8.0

func (result *Result) Named() *NamedResult

Named returns a NamedResult based on this struct

func (*Result) Repair

func (result *Result) Repair(fields []*querypb.Field)

Repair fixes the type info in the rows to conform to the supplied field types.

func (*Result) ReplaceKeyspace added in v0.11.0

func (result *Result) ReplaceKeyspace(keyspace string)

ReplaceKeyspace replaces all the non-empty Database identifiers in the result set with the given keyspace name

func (*Result) ShallowCopy added in v0.16.0

func (result *Result) ShallowCopy() *Result

ShallowCopy creates a shallow copy of Result.

func (*Result) StripMetadata

func (result *Result) StripMetadata(incl querypb.ExecuteOptions_IncludedFields) *Result

StripMetadata will return a new Result that has the same Rows, but the Field objects will have their non-critical metadata emptied. Note we don't proto.Copy each Field for performance reasons, but we only copy the individual fields.

func (*Result) Truncate

func (result *Result) Truncate(l int) *Result

Truncate returns a new Result with all the rows truncated to the specified number of columns.

type ResultMarshaller added in v0.18.0

type ResultMarshaller interface {
	MarshalResult() (*Result, error)
}

ResultMarshaller knows how to marshal itself into a Result.

type ResultStream

type ResultStream interface {
	// Recv returns the next result on the stream.
	// It will return io.EOF if the stream ended.
	Recv() (*Result, error)
}

ResultStream is an interface for receiving Result. It is used for RPC interfaces.

type Row added in v0.14.0

type Row = []Value

func ParseRows added in v0.16.7

func ParseRows(input string) ([]Row, error)

ParseRows parses the output generated by fmt.Sprintf("#v", rows), and reifies the original []sqltypes.Row NOTE: This is not meant for production use!

type RowMismatchError added in v0.16.7

type RowMismatchError struct {
	// contains filtered or unexported fields
}

func (*RowMismatchError) Error added in v0.16.7

func (e *RowMismatchError) Error() string

type RowNamedValues added in v0.8.0

type RowNamedValues map[string]Value

RowNamedValues contains a row's values as a map based on Field (aka table column) name

func (RowNamedValues) AsBool added in v0.8.0

func (r RowNamedValues) AsBool(fieldName string, def bool) bool

AsBool returns the named field as bool, or default value if nonexistent/error

func (RowNamedValues) AsBytes added in v0.13.0

func (r RowNamedValues) AsBytes(fieldName string, def []byte) []byte

AsBytes returns the named field as a byte array, or default value if nonexistent/error

func (RowNamedValues) AsFloat64 added in v0.10.0

func (r RowNamedValues) AsFloat64(fieldName string, def float64) float64

AsFloat64 returns the named field as float64, or default value if nonexistent/error

func (RowNamedValues) AsInt32 added in v0.17.0

func (r RowNamedValues) AsInt32(fieldName string, def int32) int32

func (RowNamedValues) AsInt64 added in v0.8.0

func (r RowNamedValues) AsInt64(fieldName string, def int64) int64

AsInt64 returns the named field as int64, or default value if nonexistent/error

func (RowNamedValues) AsString added in v0.8.0

func (r RowNamedValues) AsString(fieldName string, def string) string

AsString returns the named field as string, or default value if nonexistent/error

func (RowNamedValues) AsUint64 added in v0.8.0

func (r RowNamedValues) AsUint64(fieldName string, def uint64) uint64

AsUint64 returns the named field as uint64, or default value if nonexistent/error

func (RowNamedValues) ToBool added in v0.8.0

func (r RowNamedValues) ToBool(fieldName string) (bool, error)

ToBool returns the named field as bool

func (RowNamedValues) ToBytes added in v0.13.0

func (r RowNamedValues) ToBytes(fieldName string) ([]byte, error)

ToBytes returns the named field as a byte array

func (RowNamedValues) ToFloat64 added in v0.10.0

func (r RowNamedValues) ToFloat64(fieldName string) (float64, error)

ToFloat64 returns the named field as float64

func (RowNamedValues) ToInt added in v0.17.0

func (r RowNamedValues) ToInt(fieldName string) (int, error)

ToInt returns the named field as int

func (RowNamedValues) ToInt32 added in v0.17.0

func (r RowNamedValues) ToInt32(fieldName string) (int32, error)

func (RowNamedValues) ToInt64 added in v0.8.0

func (r RowNamedValues) ToInt64(fieldName string) (int64, error)

ToInt64 returns the named field as int64

func (RowNamedValues) ToString added in v0.8.0

func (r RowNamedValues) ToString(fieldName string) (string, error)

ToString returns the named field as string

func (RowNamedValues) ToUint64 added in v0.8.0

func (r RowNamedValues) ToUint64(fieldName string) (uint64, error)

ToUint64 returns the named field as uint64

type Type added in v0.14.0

type Type = querypb.Type

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value can store any SQL value. If the value represents an integral type, the bytes are always stored as a canonical representation that matches how MySQL returns such values.

func BindVariableToValue

func BindVariableToValue(bv *querypb.BindVariable) (Value, error)

BindVariableToValue converts a bind var into a Value.

func Cast added in v0.18.0

func Cast(v Value, typ Type) (Value, error)

Cast converts a Value to the target type.

func CopyRow

func CopyRow(r []Value) []Value

CopyRow makes a copy of the row.

func InterfaceToValue

func InterfaceToValue(goval any) (Value, error)

InterfaceToValue builds a value from a go type. Supported types are nil, int64, uint64, float64, string and []byte. This function is deprecated. Use the type-specific functions instead.

func MakeRowTrusted

func MakeRowTrusted(fields []*querypb.Field, row *querypb.Row) []Value

MakeRowTrusted converts a *querypb.Row to []Value based on the types in fields. It does not sanity check the values against the type. Every place this function is called, a comment is needed that explains why it's justified.

func MakeTrusted

func MakeTrusted(typ querypb.Type, val []byte) Value

MakeTrusted makes a new Value based on the type. This function should only be used if you know the value and type conform to the rules. Every place this function is called, a comment is needed that explains why it's justified. Exceptions: The current package and mysql package do not need comments. Other packages can also use the function to create VarBinary or VarChar values.

func NewBitNum added in v0.15.0

func NewBitNum(v []byte) Value

NewBitNum builds a BitNum Value.

func NewBoolean added in v0.18.0

func NewBoolean(v bool) Value

NewBoolean builds a Uint8 Value from a boolean.

func NewDate added in v0.13.0

func NewDate(v string) Value

NewDate builds a Date value.

func NewDatetime added in v0.13.0

func NewDatetime(v string) Value

NewDatetime builds a Datetime value.

func NewDecimal added in v0.13.0

func NewDecimal(v string) Value

NewDecimal builds a Decimal value.

func NewFloat32 added in v0.18.0

func NewFloat32(v float32) Value

NewFloat32 builds a Float32 Value.

func NewFloat64

func NewFloat64(v float64) Value

NewFloat64 builds an Float64 Value.

func NewHexNum added in v0.12.1

func NewHexNum(v []byte) Value

NewHexNum builds an Hex Value.

func NewHexVal added in v0.12.1

func NewHexVal(v []byte) Value

NewHexVal builds a HexVal Value.

func NewInt16 added in v0.18.0

func NewInt16(v int16) Value

NewInt16 builds a Int16 Value.

func NewInt32

func NewInt32(v int32) Value

NewInt32 builds an Int64 Value.

func NewInt64

func NewInt64(v int64) Value

NewInt64 builds an Int64 Value.

func NewInt8

func NewInt8(v int8) Value

NewInt8 builds an Int8 Value.

func NewIntegral

func NewIntegral(val string) (n Value, err error)

NewIntegral builds an integral type from a string representation. The type will be Int64 or Uint64. Int64 will be preferred where possible.

func NewJSON added in v0.17.0

func NewJSON(v string) (Value, error)

func NewTime added in v0.13.0

func NewTime(v string) Value

NewTime builds a Time value.

func NewTimestamp added in v0.13.0

func NewTimestamp(v string) Value

NewTimestamp builds a Timestamp value.

func NewUint16 added in v0.18.0

func NewUint16(v uint16) Value

NewUint16 builds a Uint16 Value.

func NewUint32

func NewUint32(v uint32) Value

NewUint32 builds an Uint32 Value.

func NewUint64

func NewUint64(v uint64) Value

NewUint64 builds an Uint64 Value.

func NewUint8 added in v0.18.0

func NewUint8(v uint8) Value

NewUint8 builds a Uint8 Value.

func NewValue

func NewValue(typ querypb.Type, val []byte) (v Value, err error)

NewValue builds a Value using typ and val. If the value and typ don't match, it returns an error.

func NewVarBinary

func NewVarBinary(v string) Value

NewVarBinary builds a VarBinary Value. The input is a string because it's the most common use case.

func NewVarChar

func NewVarChar(v string) Value

NewVarChar builds a VarChar Value.

func ProtoToValue

func ProtoToValue(v *querypb.Value) Value

ProtoToValue converts a *querypb.Value to a Value.

func TestTuple added in v0.18.0

func TestTuple(vals ...Value) Value

TestTuple builds a tuple Value from a list of Values. This function should only be used for testing.

func TestValue

func TestValue(typ querypb.Type, val string) Value

TestValue builds a Value from typ and val. This function should only be used for testing.

func (*Value) CachedSize added in v0.10.0

func (cached *Value) CachedSize(alloc bool) int64

func (Value) EncodeASCII

func (v Value) EncodeASCII(b BinWriter)

EncodeASCII encodes the value using 7-bit clean ascii bytes.

func (Value) EncodeSQL

func (v Value) EncodeSQL(b BinWriter)

EncodeSQL encodes the value into an SQL statement. Can be binary.

func (Value) EncodeSQLBytes2 added in v0.11.0

func (v Value) EncodeSQLBytes2(b *bytes2.Buffer)

EncodeSQLBytes2 is identical to EncodeSQL but it takes a bytes2.Buffer as its writer, so it can be inlined for performance.

func (Value) EncodeSQLStringBuilder added in v0.11.0

func (v Value) EncodeSQLStringBuilder(b *strings.Builder)

EncodeSQLStringBuilder is identical to EncodeSQL but it takes a strings.Builder as its writer, so it can be inlined for performance.

func (*Value) ForEachValue added in v0.18.0

func (v *Value) ForEachValue(each func(bv Value)) error

func (Value) IsBinary

func (v Value) IsBinary() bool

IsBinary returns true if Value is binary.

func (*Value) IsComparable added in v0.12.0

func (v *Value) IsComparable() bool

IsComparable returns true if the Value is null safe comparable without collation information.

func (Value) IsDate added in v0.18.0

func (v Value) IsDate() bool

IsDate returns true if Value is date.

func (Value) IsDateTime added in v0.9.0

func (v Value) IsDateTime() bool

IsDateTime returns true if Value is datetime.

func (Value) IsDecimal added in v0.17.0

func (v Value) IsDecimal() bool

IsDecimal returns true if Value is a decimal.

func (Value) IsFloat

func (v Value) IsFloat() bool

IsFloat returns true if Value is a float.

func (Value) IsIntegral

func (v Value) IsIntegral() bool

IsIntegral returns true if Value is an integral.

func (Value) IsNull

func (v Value) IsNull() bool

IsNull returns true if Value is null.

func (Value) IsQuoted

func (v Value) IsQuoted() bool

IsQuoted returns true if Value must be SQL-quoted.

func (Value) IsSigned

func (v Value) IsSigned() bool

IsSigned returns true if Value is a signed integral.

func (Value) IsText

func (v Value) IsText() bool

IsText returns true if Value is a collatable text.

func (Value) IsTime added in v0.17.0

func (v Value) IsTime() bool

IsTime returns true if Value is time.

func (Value) IsTimestamp added in v0.18.0

func (v Value) IsTimestamp() bool

IsTimestamp returns true if Value is date.

func (Value) IsUnsigned

func (v Value) IsUnsigned() bool

IsUnsigned returns true if Value is an unsigned integral.

func (Value) Len

func (v Value) Len() int

Len returns the length.

func (Value) MarshalJSON

func (v Value) MarshalJSON() ([]byte, error)

MarshalJSON should only be used for testing. It's not a complete implementation.

func (Value) Raw

func (v Value) Raw() []byte

Raw returns the internal representation of the value. For newer types, this may not match MySQL's representation.

func (Value) RawStr added in v0.13.0

func (v Value) RawStr() string

RawStr returns the internal representation of the value as a string instead of a byte slice. This is equivalent to calling `string(v.Raw())` but does not allocate.

func (Value) String

func (v Value) String() string

String returns a printable version of the value.

func (Value) ToBool added in v0.8.0

func (v Value) ToBool() (bool, error)

ToBool returns the value as a bool value

func (Value) ToBytes

func (v Value) ToBytes() ([]byte, error)

ToBytes returns the value as MySQL would return it as []byte. In contrast, Raw returns the internal representation of the Value, which may not match MySQL's representation for hex encoded binary data or newer types. If the value is not convertible like in the case of Expression, it returns an error.

func (Value) ToCastInt64 added in v0.18.0

func (v Value) ToCastInt64() (int64, error)

ToCastInt64 returns the best effort value as MySQL would return it as a int64.

func (Value) ToCastUint64 added in v0.18.0

func (v Value) ToCastUint64() (uint64, error)

ToCastUint64 returns the best effort value as MySQL would return it as a uint64.

func (Value) ToFloat64 added in v0.9.0

func (v Value) ToFloat64() (float64, error)

ToFloat64 returns the value as MySQL would return it as a float64.

func (Value) ToInt added in v0.17.0

func (v Value) ToInt() (int, error)

ToInt returns the value as MySQL would return it as a int.

func (Value) ToInt32 added in v0.17.0

func (v Value) ToInt32() (int32, error)

func (Value) ToInt64 added in v0.8.0

func (v Value) ToInt64() (int64, error)

ToInt64 returns the value as MySQL would return it as a int64.

func (Value) ToString

func (v Value) ToString() string

ToString returns the value as MySQL would return it as string. If the value is not convertible like in the case of Expression, it returns nil.

func (Value) ToUint16 added in v0.17.0

func (v Value) ToUint16() (uint16, error)

ToUint16 returns the value as MySQL would return it as a uint16.

func (Value) ToUint32 added in v0.17.0

func (v Value) ToUint32() (uint32, error)

func (Value) ToUint64 added in v0.8.0

func (v Value) ToUint64() (uint64, error)

ToUint64 returns the value as MySQL would return it as a uint64.

func (Value) Type

func (v Value) Type() querypb.Type

Type returns the type of Value.

func (*Value) UnmarshalJSON

func (v *Value) UnmarshalJSON(b []byte) error

UnmarshalJSON should only be used for testing. It's not a complete implementation.

type ValueMarshaller added in v0.18.0

type ValueMarshaller interface {
	MarshalSQL(typ querypb.Type) ([]byte, error)
}

ValueMarshaller knows how to marshal itself into the bytes for a column of a particular type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL