types

package
v1.1.0-beta.0...-57a73ea Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2024 License: Apache-2.0 Imports: 46 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KindNull          byte = 0
	KindInt64         byte = 1
	KindUint64        byte = 2
	KindFloat32       byte = 3
	KindFloat64       byte = 4
	KindString        byte = 5
	KindBytes         byte = 6
	KindBinaryLiteral byte = 7 // Used for BIT / HEX literals.
	KindMysqlDecimal  byte = 8
	KindMysqlDuration byte = 9
	KindMysqlEnum     byte = 10
	KindMysqlBit      byte = 11 // Used for BIT table column values.
	KindMysqlSet      byte = 12
	KindMysqlTime     byte = 13
	KindInterface     byte = 14
	KindMinNotNull    byte = 15
	KindMaxValue      byte = 16
	KindRaw           byte = 17
	KindMysqlJSON     byte = 18
	KindVectorFloat32 byte = 19
)

Kind constants.

View Source
const (
	DateTimeStr  = "datetime"
	DateStr      = "date"
	TimeStr      = "time"
	TimestampStr = "timestamp"
)

const strings for ErrWrongValue

View Source
const (
	// ETInt represents type INT in evaluation.
	ETInt = ast.ETInt
	// ETReal represents type REAL in evaluation.
	ETReal = ast.ETReal
	// ETDecimal represents type DECIMAL in evaluation.
	ETDecimal = ast.ETDecimal
	// ETString represents type STRING in evaluation.
	ETString = ast.ETString
	// ETDatetime represents type DATETIME in evaluation.
	ETDatetime = ast.ETDatetime
	// ETTimestamp represents type TIMESTAMP in evaluation.
	ETTimestamp = ast.ETTimestamp
	// ETDuration represents type DURATION in evaluation.
	ETDuration = ast.ETDuration
	// ETJson represents type JSON in evaluation.
	ETJson = ast.ETJson
	// ETVectorFloat32 represents type VectorFloat32 in evaluation.
	ETVectorFloat32 = ast.ETVectorFloat32
)
View Source
const (
	// UnspecifiedFsp is the unspecified fractional seconds part.
	UnspecifiedFsp = -1
	// MaxFsp is the maximum digit of fractional seconds part.
	MaxFsp = 6
	// MinFsp is the minimum digit of fractional seconds part.
	MinFsp = 0
	// DefaultFsp is the default digit of fractional seconds part.
	// MySQL use 0 as the default Fsp.
	DefaultFsp = 0
)
View Source
const (
	// JSONLiteralNil represents JSON null.
	JSONLiteralNil byte = 0x00
	// JSONLiteralTrue represents JSON true.
	JSONLiteralTrue byte = 0x01
	// JSONLiteralFalse represents JSON false.
	JSONLiteralFalse byte = 0x02
)
View Source
const (
	// 'all': 1 if all paths exist within the document, 0 otherwise.
	JSONContainsPathAll = "all"
	// 'one': 1 if at least one path exists within the document, 0 otherwise.
	JSONContainsPathOne = "one"
)

json_contains_path function type choices See: https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#function_json-contains-path

View Source
const (
	DateFormat = gotime.DateOnly
	TimeFormat = gotime.DateTime
	// TimeFSPFormat is time format with fractional seconds precision.
	TimeFSPFormat = "2006-01-02 15:04:05.000000"
	// UTCTimeFormat is used to parse and format gotime.
	UTCTimeFormat = "2006-01-02 15:04:05 UTC"
)

Time format without fractional seconds precision.

View Source
const (
	// MinYear is the minimum for mysql year type.
	MinYear int16 = 1901
	// MaxYear is the maximum for mysql year type.
	MaxYear int16 = 2155
	// MaxDuration is the maximum for duration.
	MaxDuration int64 = 838*10000 + 59*100 + 59
	// MinTime is the minimum for mysql time type.
	MinTime = -(838*gotime.Hour + 59*gotime.Minute + 59*gotime.Second)
	// MaxTime is the maximum for mysql time type.
	MaxTime = 838*gotime.Hour + 59*gotime.Minute + 59*gotime.Second
	// ZeroDatetimeStr is the string representation of a zero datetime.
	ZeroDatetimeStr = "0000-00-00 00:00:00"
	// ZeroDateStr is the string representation of a zero date.
	ZeroDateStr = "0000-00-00"

	// TimeMaxHour is the max hour for mysql time type.
	TimeMaxHour = 838
	// TimeMaxMinute is the max minute for mysql time type.
	TimeMaxMinute = 59
	// TimeMaxSecond is the max second for mysql time type.
	TimeMaxSecond = 59
	// TimeMaxValue is the maximum value for mysql time type.
	TimeMaxValue = TimeMaxHour*10000 + TimeMaxMinute*100 + TimeMaxSecond
	// TimeMaxValueSeconds is the maximum second value for mysql time type.
	TimeMaxValueSeconds = TimeMaxHour*3600 + TimeMaxMinute*60 + TimeMaxSecond
)
View Source
const (
	// YearIndex is index of 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	YearIndex = 0 + iota
	// MonthIndex is index of 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	MonthIndex
	// DayIndex is index of 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	DayIndex
	// HourIndex is index of 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	HourIndex
	// MinuteIndex is index of 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	MinuteIndex
	// SecondIndex is index of 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	SecondIndex
	// MicrosecondIndex is index of 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	MicrosecondIndex
)
View Source
const (
	// YearMonthMaxCnt is max parameters count 'YEARS-MONTHS' expr Format allowed
	YearMonthMaxCnt = 2
	// DayHourMaxCnt is max parameters count 'DAYS HOURS' expr Format allowed
	DayHourMaxCnt = 2
	// DayMinuteMaxCnt is max parameters count 'DAYS HOURS:MINUTES' expr Format allowed
	DayMinuteMaxCnt = 3
	// DaySecondMaxCnt is max parameters count 'DAYS HOURS:MINUTES:SECONDS' expr Format allowed
	DaySecondMaxCnt = 4
	// DayMicrosecondMaxCnt is max parameters count 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format allowed
	DayMicrosecondMaxCnt = 5
	// HourMinuteMaxCnt is max parameters count 'HOURS:MINUTES' expr Format allowed
	HourMinuteMaxCnt = 2
	// HourSecondMaxCnt is max parameters count 'HOURS:MINUTES:SECONDS' expr Format allowed
	HourSecondMaxCnt = 3
	// HourMicrosecondMaxCnt is max parameters count 'HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format allowed
	HourMicrosecondMaxCnt = 4
	// MinuteSecondMaxCnt is max parameters count 'MINUTES:SECONDS' expr Format allowed
	MinuteSecondMaxCnt = 2
	// MinuteMicrosecondMaxCnt is max parameters count 'MINUTES:SECONDS.MICROSECONDS' expr Format allowed
	MinuteMicrosecondMaxCnt = 3
	// SecondMicrosecondMaxCnt is max parameters count 'SECONDS.MICROSECONDS' expr Format allowed
	SecondMicrosecondMaxCnt = 2
	// TimeValueCnt is parameters count 'YEARS-MONTHS DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' expr Format
	TimeValueCnt = 7
)
View Source
const (
	// GoDurationDay is the gotime.Duration which equals to a Day.
	GoDurationDay = gotime.Hour * 24
	// GoDurationWeek is the gotime.Duration which equals to a Week.
	GoDurationWeek = GoDurationDay * 7
)

DefaultStmtFlags is the default flags for statement context with the flag `FlagAllowNegativeToUnsigned` set. TODO: make DefaultStmtFlags to be equal with StrictFlags, and setting flag `FlagAllowNegativeToUnsigned` is only for make the code to be equivalent with the old implement during refactoring.

View Source
const EmptyDatumSize = int64(unsafe.Sizeof(Datum{}))

EmptyDatumSize is the size of empty datum. 72 = 1 + 1 (byte) + 2 (uint16) + 4 (uint32) + 8 (int64) + 16 (string) + 24 ([]byte) + 16 (interface{})

View Source
const ErrorLength = 0

ErrorLength is error length for blob or text.

View Source
const MyDecimalStructSize = 40

MyDecimalStructSize is the struct size of MyDecimal.

View Source
const UnspecifiedLength = -1

UnspecifiedLength is unspecified length.

View Source
const VarStorageLen = ast.VarStorageLen

VarStorageLen indicates this column is a variable length column.

Variables

View Source
var (
	// ErrInvalidDefault is returned when meet a invalid default value.
	ErrInvalidDefault = parser_types.ErrInvalidDefault
	// ErrDataTooLong is returned when converts a string value that is longer than field type length.
	ErrDataTooLong = dbterror.ClassTypes.NewStd(mysql.ErrDataTooLong)
	// ErrIllegalValueForType is returned when value of type is illegal.
	ErrIllegalValueForType = dbterror.ClassTypes.NewStd(mysql.ErrIllegalValueForType)
	// ErrTruncated is returned when data has been truncated during conversion.
	ErrTruncated = dbterror.ClassTypes.NewStd(mysql.WarnDataTruncated)
	// ErrOverflow is returned when data is out of range for a field type.
	ErrOverflow = dbterror.ClassTypes.NewStd(mysql.ErrDataOutOfRange)
	// ErrDivByZero is return when do division by 0.
	ErrDivByZero = dbterror.ClassTypes.NewStd(mysql.ErrDivisionByZero)
	// ErrTooBigDisplayWidth is return when display width out of range for column.
	ErrTooBigDisplayWidth = dbterror.ClassTypes.NewStd(mysql.ErrTooBigDisplaywidth)
	// ErrTooBigFieldLength is return when column length too big for column.
	ErrTooBigFieldLength = dbterror.ClassTypes.NewStd(mysql.ErrTooBigFieldlength)
	// ErrTooBigSet is returned when too many strings for column.
	ErrTooBigSet = dbterror.ClassTypes.NewStd(mysql.ErrTooBigSet)
	// ErrTooBigScale is returned when type DECIMAL/NUMERIC scale is bigger than mysql.MaxDecimalScale.
	ErrTooBigScale = dbterror.ClassTypes.NewStd(mysql.ErrTooBigScale)
	// ErrTooBigPrecision is returned when type DECIMAL/NUMERIC or DATETIME precision is bigger than mysql.MaxDecimalWidth or types.MaxFsp
	ErrTooBigPrecision = dbterror.ClassTypes.NewStd(mysql.ErrTooBigPrecision)
	// ErrBadNumber is return when parsing an invalid binary decimal number.
	ErrBadNumber = dbterror.ClassTypes.NewStd(mysql.ErrBadNumber)
	// ErrInvalidFieldSize is returned when the precision of a column is out of range.
	ErrInvalidFieldSize = dbterror.ClassTypes.NewStd(mysql.ErrInvalidFieldSize)
	// ErrMBiggerThanD is returned when precision less than the scale.
	ErrMBiggerThanD = dbterror.ClassTypes.NewStd(mysql.ErrMBiggerThanD)
	// ErrWarnDataOutOfRange is returned when the value in a numeric column that is outside the permissible range of the column data type.
	// See https://dev.mysql.com/doc/refman/5.5/en/out-of-range-and-overflow.html for details
	ErrWarnDataOutOfRange = dbterror.ClassTypes.NewStd(mysql.ErrWarnDataOutOfRange)
	// ErrDuplicatedValueInType is returned when enum column has duplicated value.
	ErrDuplicatedValueInType = dbterror.ClassTypes.NewStd(mysql.ErrDuplicatedValueInType)
	// ErrDatetimeFunctionOverflow is returned when the calculation in datetime function cause overflow.
	ErrDatetimeFunctionOverflow = dbterror.ClassTypes.NewStd(mysql.ErrDatetimeFunctionOverflow)
	// ErrCastAsSignedOverflow is returned when positive out-of-range integer, and convert to its negative complement.
	ErrCastAsSignedOverflow = dbterror.ClassTypes.NewStd(mysql.ErrCastAsSignedOverflow)
	// ErrCastNegIntAsUnsigned is returned when a negative integer be casted to an unsigned int.
	ErrCastNegIntAsUnsigned = dbterror.ClassTypes.NewStd(mysql.ErrCastNegIntAsUnsigned)
	// ErrInvalidYearFormat is returned when the input is not a valid year format.
	ErrInvalidYearFormat = dbterror.ClassTypes.NewStd(mysql.ErrInvalidYearFormat)
	// ErrInvalidYear is returned when the input value is not a valid year.
	ErrInvalidYear = dbterror.ClassTypes.NewStd(mysql.ErrInvalidYear)
	// ErrTruncatedWrongVal is returned when data has been truncated during conversion.
	ErrTruncatedWrongVal = dbterror.ClassTypes.NewStd(mysql.ErrTruncatedWrongValue)
	// ErrInvalidWeekModeFormat is returned when the week mode is wrong.
	ErrInvalidWeekModeFormat = dbterror.ClassTypes.NewStd(mysql.ErrInvalidWeekModeFormat)
	// ErrWrongFieldSpec is returned when the column specifier incorrect.
	ErrWrongFieldSpec = dbterror.ClassTypes.NewStd(mysql.ErrWrongFieldSpec)
	// ErrSyntax is returned when the syntax is not allowed.
	ErrSyntax = dbterror.ClassTypes.NewStdErr(mysql.ErrParse, mysql.MySQLErrName[mysql.ErrSyntax])
	// ErrWrongValue is returned when the input value is in wrong format.
	ErrWrongValue = dbterror.ClassTypes.NewStdErr(mysql.ErrTruncatedWrongValue, mysql.MySQLErrName[mysql.ErrWrongValue])
	// ErrWrongValue2 is returned when the input value is in wrong format.
	ErrWrongValue2 = dbterror.ClassTypes.NewStdErr(mysql.ErrWrongValue, mysql.MySQLErrName[mysql.ErrWrongValue])
	// ErrWrongValueForType is returned when the input value is in wrong format for function.
	ErrWrongValueForType = dbterror.ClassTypes.NewStdErr(mysql.ErrWrongValueForType, mysql.MySQLErrName[mysql.ErrWrongValueForType])
	// ErrPartitionStatsMissing is returned when the partition-level stats is missing and the build global-level stats fails.
	// Put this error here is to prevent `import cycle not allowed`.
	ErrPartitionStatsMissing = dbterror.ClassTypes.NewStd(mysql.ErrPartitionStatsMissing)
	// ErrPartitionColumnStatsMissing is returned when the partition-level column stats is missing and the build global-level stats fails.
	// Put this error here is to prevent `import cycle not allowed`.
	ErrPartitionColumnStatsMissing = dbterror.ClassTypes.NewStd(mysql.ErrPartitionColumnStatsMissing)
	// ErrIncorrectDatetimeValue is returned when the input value is in wrong format for datetime.
	ErrIncorrectDatetimeValue = dbterror.ClassTypes.NewStd(mysql.ErrIncorrectDatetimeValue)
	// ErrJSONBadOneOrAllArg is returned when the one_or_all argument isn't 'one' or 'all'.
	ErrJSONBadOneOrAllArg = dbterror.ClassTypes.NewStd(mysql.ErrJSONBadOneOrAllArg)
	// ErrJSONVacuousPath is returned for path expressions that are not allowed in that context.
	ErrJSONVacuousPath = dbterror.ClassTypes.NewStd(mysql.ErrJSONVacuousPath)
)
View Source
var (
	// ExplainFormatBrief is the same as ExplainFormatRow, but it ignores explain ID suffix.
	ExplainFormatBrief = "brief"
	// ExplainFormatDOT indicates that using DotGraph to explain.
	ExplainFormatDOT = "dot"
	// ExplainFormatHint is to show hint information.
	ExplainFormatHint = "hint"
	// ExplainFormatJSON displays the information in JSON format.
	ExplainFormatJSON = "json"
	// ExplainFormatROW presents the output in tabular format.
	ExplainFormatROW = "row"
	// ExplainFormatVerbose display additional information regarding the plan.
	ExplainFormatVerbose = "verbose"
	// ExplainFormatTraditional is the same as ExplainFormatROW.
	ExplainFormatTraditional = "traditional"
	// ExplainFormatTrueCardCost indicates the optimizer to use true cardinality to calculate the cost.
	ExplainFormatTrueCardCost = "true_card_cost"
	// ExplainFormatBinary prints the proto for binary plan.
	ExplainFormatBinary = "binary"
	// ExplainFormatTiDBJSON warp the default result in JSON format
	ExplainFormatTiDBJSON = "tidb_json"
	// ExplainFormatCostTrace prints the cost and cost formula of each operator.
	ExplainFormatCostTrace = "cost_trace"
	// ExplainFormatPlanCache prints the reason why can't use non-prepared plan cache by warning
	ExplainFormatPlanCache = "plan_cache"

	// ExplainFormats stores the valid formats for explain statement, used by validator.
	ExplainFormats = []string{
		ExplainFormatBrief,
		ExplainFormatDOT,
		ExplainFormatHint,
		ExplainFormatJSON,
		ExplainFormatROW,
		ExplainFormatVerbose,
		ExplainFormatTraditional,
		ExplainFormatTrueCardCost,
		ExplainFormatBinary,
		ExplainFormatTiDBJSON,
		ExplainFormatCostTrace,
		ExplainFormatPlanCache,
	}
)
View Source
var (
	// ErrInvalidJSONText means invalid JSON text.
	ErrInvalidJSONText = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONText)
	// ErrInvalidJSONType means invalid JSON type.
	ErrInvalidJSONType = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONType)
	// ErrInvalidJSONTextInParam means invalid JSON text in arguments.
	ErrInvalidJSONTextInParam = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONTextInParam)
	// ErrInvalidJSONPath means invalid JSON path.
	ErrInvalidJSONPath = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONPath)
	// ErrInvalidJSONCharset means invalid JSON charset.
	ErrInvalidJSONCharset = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONCharset)
	// ErrInvalidJSONData means invalid JSON data.
	ErrInvalidJSONData = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONData)
	// ErrInvalidJSONPathMultipleSelection means invalid JSON path that contain wildcard characters or range selection.
	ErrInvalidJSONPathMultipleSelection = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONPathMultipleSelection)
	// ErrInvalidJSONContainsPathType means invalid JSON contains path type.
	ErrInvalidJSONContainsPathType = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONContainsPathType)
	// ErrJSONDocumentNULLKey means that json's key is null
	ErrJSONDocumentNULLKey = dbterror.ClassJSON.NewStd(mysql.ErrJSONDocumentNULLKey)
	// ErrJSONDocumentTooDeep means that json's depth is too deep.
	ErrJSONDocumentTooDeep = dbterror.ClassJSON.NewStd(mysql.ErrJSONDocumentTooDeep)
	// ErrJSONObjectKeyTooLong means JSON object with key length >= 65536 which is not yet supported.
	ErrJSONObjectKeyTooLong = dbterror.ClassTypes.NewStdErr(mysql.ErrJSONObjectKeyTooLong, mysql.MySQLErrName[mysql.ErrJSONObjectKeyTooLong])
	// ErrInvalidJSONPathArrayCell means invalid JSON path for an array cell.
	ErrInvalidJSONPathArrayCell = dbterror.ClassJSON.NewStd(mysql.ErrInvalidJSONPathArrayCell)
	// ErrUnsupportedSecondArgumentType means unsupported second argument type in json_objectagg
	ErrUnsupportedSecondArgumentType = dbterror.ClassJSON.NewStd(mysql.ErrUnsupportedSecondArgumentType)
)
View Source
var (
	// ZeroDuration is the zero value for Duration type.
	ZeroDuration = Duration{Duration: gotime.Duration(0), Fsp: DefaultFsp}

	// ZeroCoreTime is the zero value for Time type.
	ZeroTime = Time{}

	// ZeroDatetime is the zero value for datetime Time.
	ZeroDatetime = NewTime(ZeroCoreTime, mysql.TypeDatetime, DefaultFsp)

	// ZeroTimestamp is the zero value for timestamp Time.
	ZeroTimestamp = NewTime(ZeroCoreTime, mysql.TypeTimestamp, DefaultFsp)

	// ZeroDate is the zero value for date Time.
	ZeroDate = NewTime(ZeroCoreTime, mysql.TypeDate, DefaultFsp)
)

Zero values for different types.

View Source
var (
	// MinDatetime is the minimum for Golang Time type.
	MinDatetime = FromDate(1, 1, 1, 0, 0, 0, 0)
	// MaxDatetime is the maximum for mysql datetime type.
	MaxDatetime = FromDate(9999, 12, 31, 23, 59, 59, 999999)

	// BoundTimezone is the timezone for min and max timestamp.
	BoundTimezone = gotime.UTC
	// MinTimestamp is the minimum for mysql timestamp type.
	MinTimestamp = NewTime(FromDate(1970, 1, 1, 0, 0, 1, 0), mysql.TypeTimestamp, DefaultFsp)
	// MaxTimestamp is the maximum for mysql timestamp type.
	MaxTimestamp = NewTime(FromDate(2038, 1, 19, 3, 14, 7, 999999), mysql.TypeTimestamp, DefaultFsp)

	// WeekdayNames lists names of weekdays, which are used in builtin time function `dayname`.
	WeekdayNames = []string{
		"Monday",
		"Tuesday",
		"Wednesday",
		"Thursday",
		"Friday",
		"Saturday",
		"Sunday",
	}

	// MonthNames lists names of months, which are used in builtin time function `monthname`.
	MonthNames = []string{
		"January", "February",
		"March", "April",
		"May", "June",
		"July", "August",
		"September", "October",
		"November", "December",
	}
)
View Source
var DefaultStmtNoWarningContext = NewContext(DefaultStmtFlags, time.UTC, contextutil.IgnoreWarn)

DefaultStmtNoWarningContext is the context with default statement flags without any other special configuration

View Source
var EmptyName = &FieldName{Hidden: true}

EmptyName is to occupy the position in the name slice. If it's set, that column's name is hidden.

View Source
var Hash64ForDatum func(h base.Hasher, d *Datum)

Hash64ForDatum is a hash function for initialized by codec package.

View Source
var IsTypeBlob = ast.IsTypeBlob

IsTypeBlob returns a boolean indicating whether the tp is a blob type.

View Source
var IsTypeChar = ast.IsTypeChar

IsTypeChar returns a boolean indicating whether the tp is the char type like a string type or a varchar type.

View Source
var IsTypeVector = ast.IsTypeVector

IsTypeVector returns whether tp is a vector type.

StrictContext is the most strict context which returns every error it meets

this context should never append warnings However, the implementation of `types` may still append some warnings. TODO: remove them in the future.

View Source
var TypeStr = ast.TypeStr

TypeStr converts tp to a string.

View Source
var TypeToStr = ast.TypeToStr

TypeToStr converts a field to a string. It is used for converting Text to Blob, or converting Char to Binary. Args:

tp: type enum
cs: charset
View Source
var ZeroBinaryLiteral = BinaryLiteral{}

ZeroBinaryLiteral is a BinaryLiteral literal with zero value.

View Source
var ZeroCoreTime = CoreTime(0)

ZeroCoreTime is the zero value for TimeInternal type.

View Source
var ZeroVectorFloat32 = InitVectorFloat32(0)

ZeroVectorFloat32 is a zero value of VectorFloat32.

Functions

func AddDate

func AddDate(year, month, day int64, ot gotime.Time) (nt gotime.Time, _ error)

AddDate fix gap between mysql and golang api When we execute select date_add('2018-01-31',interval 1 month) in mysql we got 2018-02-28 but in tidb we got 2018-03-03. Dig it and we found it's caused by golang api time.Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time , it says October 32 converts to November 1 ,it conflicts with mysql. See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-add

func AddDuration

func AddDuration(a time.Duration, b time.Duration) (time.Duration, error)

AddDuration adds time.Duration a and b if no overflow, otherwise returns error.

func AddInt64

func AddInt64(a int64, b int64) (int64, error)

AddInt64 adds int64 a and b if no overflow, otherwise returns error.

func AddInteger

func AddInteger(a uint64, b int64) (uint64, error)

AddInteger adds uint64 a and int64 b and returns uint64 if no overflow error.

func AddUint64

func AddUint64(a uint64, b uint64) (uint64, error)

AddUint64 adds uint64 a and b if no overflow, else returns error.

func AdjustYear

func AdjustYear(y int64, adjustZero bool) (int64, error)

AdjustYear is used for adjusting year and checking its validation.

func CheckFsp

func CheckFsp(fsp int) (int, error)

CheckFsp checks whether fsp is in valid range.

func CheckModifyTypeCompatible

func CheckModifyTypeCompatible(origin *FieldType, to *FieldType) (canReorg bool, err error)

CheckModifyTypeCompatible checks whether changes column type to another is compatible and can be changed. If types are compatible and can be directly changed, nil err will be returned; otherwise the types are incompatible. There are two cases when types incompatible: 1. returned canReorg == true: types can be changed by reorg 2. returned canReorg == false: type change not supported yet

func CheckVectorDimValid

func CheckVectorDimValid(dim int) error

CheckVectorDimValid checks if the vector's dimension is valid.

func CompareBinaryJSON

func CompareBinaryJSON(left, right BinaryJSON) int

CompareBinaryJSON compares two binary json objects. Returns -1 if left < right, 0 if left == right, else returns 1.

func CompareInt

func CompareInt(arg0 int64, isUnsigned0 bool, arg1 int64, isUnsigned1 bool) int

CompareInt return an integer comparing the integer x to y with signed or unsigned.

func CompareString

func CompareString(x, y, collation string) int

CompareString returns an integer comparing the string x to y with the specified collation and length.

func ContainsBinaryJSON

func ContainsBinaryJSON(obj, target BinaryJSON) bool

ContainsBinaryJSON check whether JSON document contains specific target according the following rules: 1) object contains a target object if and only if every key is contained in source object and the value associated with the target key is contained in the value associated with the source key; 2) array contains a target nonarray if and only if the target is contained in some element of the array; 3) array contains a target array if and only if every element is contained in some element of the array; 4) scalar contains a target scalar if and only if they are comparable and are equal;

func ConvertBetweenCharAndVarchar

func ConvertBetweenCharAndVarchar(oldCol, newCol byte) bool

ConvertBetweenCharAndVarchar is that Column type conversion between varchar to char need reorganization because 1. varchar -> char: char type is stored with the padding removed. All the indexes need to be rewritten. 2. char -> varchar: the index value encoding of secondary index on clustered primary key tables is different. These secondary indexes need to be rewritten.

func ConvertDecimalToUint

func ConvertDecimalToUint(d *MyDecimal, upperBound uint64, tp byte) (uint64, error)

ConvertDecimalToUint converts a decimal to a uint by converting it to a string first to avoid float overflow (#10181).

func ConvertFloatToInt

func ConvertFloatToInt(fval float64, lowerBound, upperBound int64, tp byte) (int64, error)

ConvertFloatToInt converts a float64 value to a int value. `tp` is used in err msg, if there is overflow, this func will report err according to `tp`

func ConvertFloatToUint

func ConvertFloatToUint(flags Flags, fval float64, upperBound uint64, tp byte) (uint64, error)

ConvertFloatToUint converts a float value to an uint value.

func ConvertIntToInt

func ConvertIntToInt(val int64, lowerBound int64, upperBound int64, tp byte) (int64, error)

ConvertIntToInt converts an int value to another int value of different precision.

func ConvertIntToUint

func ConvertIntToUint(flags Flags, val int64, upperBound uint64, tp byte) (uint64, error)

ConvertIntToUint converts an int value to an uint value.

func ConvertJSONToFloat

func ConvertJSONToFloat(ctx Context, j BinaryJSON) (float64, error)

ConvertJSONToFloat casts JSON into float64.

func ConvertJSONToInt

func ConvertJSONToInt(ctx Context, j BinaryJSON, unsigned bool, tp byte) (int64, error)

ConvertJSONToInt casts JSON into int by type.

func ConvertJSONToInt64

func ConvertJSONToInt64(ctx Context, j BinaryJSON, unsigned bool) (int64, error)

ConvertJSONToInt64 casts JSON into int64.

func ConvertUintToInt

func ConvertUintToInt(val uint64, upperBound int64, tp byte) (int64, error)

ConvertUintToInt converts an uint value to an int value.

func ConvertUintToUint

func ConvertUintToUint(val uint64, upperBound uint64, tp byte) (uint64, error)

ConvertUintToUint converts an uint value to another uint value of different precision.

func DateDiff

func DateDiff(startTime, endTime CoreTime) int

DateDiff calculates number of days between two days.

func DateFSP

func DateFSP(date string) (fsp int)

DateFSP gets fsp from date string.

func DateTimeIsOverflow

func DateTimeIsOverflow(ctx Context, date Time) (bool, error)

DateTimeIsOverflow returns if this date is overflow. See: https://dev.mysql.com/doc/refman/8.0/en/datetime.html

func DatumsContainNull

func DatumsContainNull(vals []Datum) bool

DatumsContainNull return true if any value is null

func DatumsToStrNoErr

func DatumsToStrNoErr(datums []Datum) string

DatumsToStrNoErr converts some datums to a formatted string. If an error occurs, it will print a log instead of returning an error.

func DatumsToString

func DatumsToString(datums []Datum, handleSpecialValue bool) (string, error)

DatumsToString converts several datums to formatted string.

func DecimalAdd

func DecimalAdd(from1, from2, to *MyDecimal) error

DecimalAdd adds two decimals, sets the result to 'to'. Note: DO NOT use `from1` or `from2` as `to` since the metadata of `to` may be changed during evaluating.

func DecimalBinSize

func DecimalBinSize(precision, frac int) (int, error)

DecimalBinSize returns the size of array to hold a binary representation of a decimal.

func DecimalDiv

func DecimalDiv(from1, from2, to *MyDecimal, fracIncr int) error

DecimalDiv does division of two decimals.

from1 - dividend from2 - divisor to - quotient fracIncr - increment of fraction

func DecimalLength2Precision

func DecimalLength2Precision(length int, scale int, hasUnsignedFlag bool) int

DecimalLength2Precision gets the precision.

func DecimalMod

func DecimalMod(from1, from2, to *MyDecimal) error

DecimalMod does modulus of two decimals.

    from1   - dividend
    from2   - divisor
    to      - modulus

RETURN VALUE
  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW/E_DEC_DIV_ZERO;

NOTES
  see do_div_mod()

DESCRIPTION
  the modulus R in    R = M mod N

 is defined as

   0 <= |R| < |M|
   sign R == sign M
   R = M - k*N, where k is integer

 thus, there's no requirement for M or N to be integers

func DecimalMul

func DecimalMul(from1, from2, to *MyDecimal) error

DecimalMul multiplies two decimals.

    from1, from2 - factors
    to      - product

RETURN VALUE
  E_DEC_OK/E_DEC_TRUNCATED/E_DEC_OVERFLOW;

NOTES
  in this implementation, with wordSize=4 we have digitsPerWord=9,
  and 63-digit number will take only 7 words (basically a 7-digit
  "base 999999999" number).  Thus there's no need in fast multiplication
  algorithms, 7-digit numbers can be multiplied with a naive O(n*n)
  method.

  XXX if this library is to be used with huge numbers of thousands of
  digits, fast multiplication must be implemented.

func DecimalPeak

func DecimalPeak(b []byte) (int, error)

DecimalPeak returns the length of the encoded decimal.

func DecimalSub

func DecimalSub(from1, from2, to *MyDecimal) error

DecimalSub subs one decimal from another, sets the result to 'to'.

func DefaultCharsetForType

func DefaultCharsetForType(tp byte) (defaultCharset string, defaultCollation string)

DefaultCharsetForType returns the default charset/collation for mysql type.

func DefaultTypeForValue

func DefaultTypeForValue(value any, tp *FieldType, char string, collate string)

DefaultTypeForValue returns the default FieldType for the value.

func DivInt64

func DivInt64(a int64, b int64) (int64, error)

DivInt64 divides int64 a with b, returns int64 if no overflow error. It just checks overflow, if b is zero, a "divide by zero" panic throws.

func DivIntWithUint

func DivIntWithUint(a int64, b uint64) (uint64, error)

DivIntWithUint divides int64 a with uint64 b, returns uint64 if no overflow error. It just checks overflow, if b is zero, a "divide by zero" panic throws.

func DivUintWithInt

func DivUintWithInt(a uint64, b int64) (uint64, error)

DivUintWithInt divides uint64 a with int64 b, returns uint64 if no overflow error. It just checks overflow, if b is zero, a "divide by zero" panic throws.

func EOFAsNil

func EOFAsNil(err error) error

EOFAsNil filtrates errors, If err is equal to io.EOF returns nil.

func EstimatedMemUsage

func EstimatedMemUsage(array []Datum, numOfRows int) int64

EstimatedMemUsage returns the estimated bytes consumed of a one-dimensional or two-dimensional datum array.

func ExtractDatetimeNum

func ExtractDatetimeNum(t *Time, unit string) (int64, error)

ExtractDatetimeNum extracts time value number from datetime unit and format.

func ExtractDurationNum

func ExtractDurationNum(d *Duration, unit string) (res int64, err error)

ExtractDurationNum extracts duration value number from duration unit and format.

func FormatIntWidthN

func FormatIntWidthN(num, n int) string

FormatIntWidthN uses to format int with width. Insufficient digits are filled by 0.

func GetFormatType

func GetFormatType(format string) (isDuration, isDate bool)

GetFormatType checks the type(Duration, Date or Datetime) of a format string.

func GetFracIndex

func GetFracIndex(s string) (index int)

GetFracIndex finds the last '.' for get fracStr, index = -1 means fracStr not found. but for format like '2019.01.01 00:00:00', the index should be -1.

It will not be affected by the time zone suffix. For format like '2020-01-01 12:00:00.123456+05:00' and `2020-01-01 12:00:00.123456-05:00`, the index should be 19. related issue https://github.com/pingcap/tidb/issues/35291 and https://github.com/pingcap/tidb/issues/49555

func GetFsp

func GetFsp(s string) int

GetFsp gets the fsp of a string.

func GetLastDay

func GetLastDay(year, month int) int

GetLastDay returns the last day of the month

func GetMaxFloat

func GetMaxFloat(flen int, decimal int) float64

GetMaxFloat gets the max float for given flen and decimal.

func GetTimezone

func GetTimezone(lit string) (idx int, tzSign, tzHour, tzSep, tzMinute string)

GetTimezone parses the trailing timezone information of a given time string literal. If idx = -1 is returned, it means timezone information not found, otherwise it indicates the index of the starting index of the timezone information. If the timezone contains sign, hour part and/or minute part, it will be returned as is, otherwise an empty string will be returned.

Supported syntax:

MySQL compatible: ((?P<tz_sign>[-+])(?P<tz_hour>[0-9]{2}):(?P<tz_minute>[0-9]{2})){0,1}$, see
  https://dev.mysql.com/doc/refman/8.0/en/time-zone-support.html and https://dev.mysql.com/doc/refman/8.0/en/datetime.html
  the first link specified that timezone information should be in "[H]H:MM, prefixed with a + or -" while the
  second link specified that for string literal, "hour values less than than 10, a leading zero is required.".
ISO-8601: Z|((((?P<tz_sign>[-+])(?P<tz_hour>[0-9]{2})(:(?P<tz_minute>[0-9]{2}){0,1}){0,1})|((?P<tz_minute>[0-9]{2}){0,1}){0,1}))$
  see https://www.cl.cam.ac.uk/~mgk25/iso-time.html

func InferParamTypeFromDatum

func InferParamTypeFromDatum(d *Datum, tp *FieldType)

InferParamTypeFromDatum is used for plan cache to infer the type of a parameter from its datum.

func InferParamTypeFromUnderlyingValue

func InferParamTypeFromUnderlyingValue(value any, tp *FieldType)

InferParamTypeFromUnderlyingValue is used for plan cache to infer the type of a parameter from its underlying value.

func IntegerSignedLowerBound

func IntegerSignedLowerBound(intType byte) int64

IntegerSignedLowerBound indicates the min int64 values of different mysql types.

func IntegerSignedUpperBound

func IntegerSignedUpperBound(intType byte) int64

IntegerSignedUpperBound indicates the max int64 values of different mysql types.

func IntegerUnsignedUpperBound

func IntegerUnsignedUpperBound(intType byte) uint64

IntegerUnsignedUpperBound indicates the max uint64 values of different mysql types.

func InvOp2

func InvOp2(x, y any, o opcode.Op) (any, error)

InvOp2 returns an invalid operation error.

func IsBinaryStr

func IsBinaryStr(ft *FieldType) bool

IsBinaryStr returns a boolean indicating whether the field type is a binary string type.

func IsClockUnit

func IsClockUnit(unit string) bool

IsClockUnit returns true when unit is interval unit with hour, minute, second or microsecond.

func IsDateFormat

func IsDateFormat(format string) bool

IsDateFormat returns true when the specified time format could contain only date.

func IsDateUnit

func IsDateUnit(unit string) bool

IsDateUnit returns true when unit is interval unit with year, quarter, month, week or day.

func IsMicrosecondUnit

func IsMicrosecondUnit(unit string) bool

IsMicrosecondUnit returns true when unit is interval unit with microsecond.

func IsNonBinaryStr

func IsNonBinaryStr(ft *FieldType) bool

IsNonBinaryStr returns a boolean indicating whether the field type is a non-binary string type.

func IsString

func IsString(tp byte) bool

IsString returns a boolean indicating whether the field type is a string type.

func IsStringKind

func IsStringKind(kind byte) bool

IsStringKind returns a boolean indicating whether the tp is a string type.

func IsTemporalWithDate

func IsTemporalWithDate(tp byte) bool

IsTemporalWithDate returns a boolean indicating whether the tp is time type with date.

func IsTypeBit

func IsTypeBit(ft *FieldType) bool

IsTypeBit returns a boolean indicating whether the tp is bit type.

func IsTypeFloat

func IsTypeFloat(tp byte) bool

IsTypeFloat indicates whether the type is TypeFloat

func IsTypeFractionable

func IsTypeFractionable(tp byte) bool

IsTypeFractionable returns a boolean indicating whether the tp can has time fraction.

func IsTypeInteger

func IsTypeInteger(tp byte) bool

IsTypeInteger returns a boolean indicating whether the tp is integer type.

func IsTypeNumeric

func IsTypeNumeric(tp byte) bool

IsTypeNumeric returns a boolean indicating whether the tp is numeric type.

func IsTypePrefixable

func IsTypePrefixable(tp byte) bool

IsTypePrefixable returns a boolean indicating whether an index on a column with the tp can be defined with a prefix.

func IsTypeTemporal

func IsTypeTemporal(tp byte) bool

IsTypeTemporal checks if a type is a temporal type.

func IsTypeTime

func IsTypeTime(tp byte) bool

IsTypeTime returns a boolean indicating whether the tp is time type like datetime, date or timestamp.

func IsTypeUnspecified

func IsTypeUnspecified(tp byte) bool

IsTypeUnspecified returns a boolean indicating whether the tp is the Unspecified type.

func IsTypeVarchar

func IsTypeVarchar(tp byte) bool

IsTypeVarchar returns a boolean indicating whether the tp is the varchar type like a varstring type or a varchar type.

func IsVarcharTooBigFieldLength

func IsVarcharTooBigFieldLength(colDefTpFlen int, colDefName, setCharset string) error

IsVarcharTooBigFieldLength check if the varchar type column exceeds the maximum length limit.

func KindStr

func KindStr(kind byte) (r string)

KindStr converts kind to a string.

func MulInt64

func MulInt64(a int64, b int64) (int64, error)

MulInt64 multiplies int64 a and b and returns int64 if no overflow error.

func MulInteger

func MulInteger(a uint64, b int64) (uint64, error)

MulInteger multiplies uint64 a and int64 b, and returns uint64 if no overflow error.

func MulUint64

func MulUint64(a uint64, b uint64) (uint64, error)

MulUint64 multiplies uint64 a and b and returns uint64 if no overflow error.

func NeedRestoredData

func NeedRestoredData(ft *FieldType) bool

NeedRestoredData returns if a type needs restored data. If the type is char and the collation is _bin, NeedRestoredData() returns false.

func OverlapsBinaryJSON

func OverlapsBinaryJSON(obj, target BinaryJSON) bool

OverlapsBinaryJSON is similar with ContainsBinaryJSON, but it checks the `OR` relationship.

func ParseDateFormat

func ParseDateFormat(format string) []string

ParseDateFormat parses a formatted date string and returns separated components.

func ParseDurationValue

func ParseDurationValue(unit string, format string) (y int64, m int64, d int64, n int64, fsp int, _ error)

ParseDurationValue parses time value from time unit and format. Returns y years m months d days + n nanoseconds Nanoseconds will no longer than one day.

func ParseFrac

func ParseFrac(s string, fsp int) (v int, overflow bool, err error)

ParseFrac parses the input string according to fsp, returns the microsecond, and also a bool value to indice overflow. eg: "999" fsp=2 will overflow.

func ParseYear

func ParseYear(str string) (int16, error)

ParseYear parses a formatted string and returns a year number.

func PeekBytesAsJSON

func PeekBytesAsJSON(b []byte) (n int, err error)

PeekBytesAsJSON trys to peek some bytes from b, until we can deserialize a JSON from those bytes.

func PeekBytesAsVectorFloat32

func PeekBytesAsVectorFloat32(b []byte) (n int, err error)

PeekBytesAsVectorFloat32 trys to peek some bytes from b, until we can deserialize a VectorFloat32 from those bytes.

func Precision2LengthNoTruncation

func Precision2LengthNoTruncation(length int, scale int, hasUnsignedFlag bool) int

Precision2LengthNoTruncation gets the length.

func ProduceFloatWithSpecifiedTp

func ProduceFloatWithSpecifiedTp(f float64, target *FieldType) (_ float64, err error)

ProduceFloatWithSpecifiedTp produces a new float64 according to `flen` and `decimal`.

func ProduceStrWithSpecifiedTp

func ProduceStrWithSpecifiedTp(s string, tp *FieldType, ctx Context, padZero bool) (_ string, err error)

ProduceStrWithSpecifiedTp produces a new string according to `flen` and `chs`. Param `padZero` indicates whether we should pad `\0` for `binary(flen)` type.

func Round

func Round(f float64, dec int) float64

Round rounds the argument f to dec decimal places. dec defaults to 0 if not specified. dec can be negative to cause dec digits left of the decimal point of the value f to become zero.

func RoundFloat

func RoundFloat(f float64) float64

RoundFloat rounds float val to the nearest even integer value with float64 format, like MySQL Round function. RoundFloat uses default rounding mode, see https://dev.mysql.com/doc/refman/5.7/en/precision-math-rounding.html so rounding use "round to nearest even". e.g, 1.5 -> 2, -1.5 -> -2.

func RoundFrac

func RoundFrac(t gotime.Time, fsp int) (gotime.Time, error)

RoundFrac rounds fractional seconds precision with new fsp and returns a new one. We will use the “round half up” rule, e.g, >= 0.5 -> 1, < 0.5 -> 0, so 2011:11:11 10:10:10.888888 round 0 -> 2011:11:11 10:10:11 and 2011:11:11 10:10:10.111111 round 0 -> 2011:11:11 10:10:10

func SetBinChsClnFlag

func SetBinChsClnFlag(ft *FieldType)

SetBinChsClnFlag sets charset, collation as 'binary' and adds binaryFlag to FieldType.

func SetTypeFlag

func SetTypeFlag(flag *uint, flagItem uint, on bool)

SetTypeFlag turns the flagItem on or off.

func SortDatums

func SortDatums(ctx Context, datums []Datum) error

SortDatums sorts a slice of datum.

func StrToDuration

func StrToDuration(ctx Context, str string, fsp int) (d Duration, t Time, isDuration bool, err error)

StrToDuration converts str to Duration. It returns Duration in normal case, and returns Time when str is in datetime format. when isDuration is true, the d is returned, when it is false, the t is returned. See https://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html.

func StrToFloat

func StrToFloat(ctx Context, str string, isFuncCast bool) (float64, error)

StrToFloat converts a string to a float64 at the best-effort.

func StrToInt

func StrToInt(ctx Context, str string, isFuncCast bool) (int64, error)

StrToInt converts a string to an integer at the best-effort.

func StrToUint

func StrToUint(ctx Context, str string, isFuncCast bool) (uint64, error)

StrToUint converts a string to an unsigned integer at the best-effort.

func SubDuration

func SubDuration(a time.Duration, b time.Duration) (time.Duration, error)

SubDuration subtracts time.Duration a with b and returns time.Duration if no overflow error.

func SubInt64

func SubInt64(a int64, b int64) (int64, error)

SubInt64 subtracts int64 a with b and returns int64 if no overflow error.

func SubIntWithUint

func SubIntWithUint(a int64, b uint64) (uint64, error)

SubIntWithUint subtracts int64 a with uint64 b and returns uint64 if no overflow error.

func SubUint64

func SubUint64(a uint64, b uint64) (uint64, error)

SubUint64 subtracts uint64 a with b and returns uint64 if no overflow error.

func SubUintWithInt

func SubUintWithInt(a uint64, b int64) (uint64, error)

SubUintWithInt subtracts uint64 a with int64 b and returns uint64 if no overflow error.

func TimestampDiff

func TimestampDiff(unit string, t1 Time, t2 Time) int64

TimestampDiff returns t2 - t1 where t1 and t2 are date or datetime expressions. The unit for the result (an integer) is given by the unit argument. The legal values for unit are "YEAR" "QUARTER" "MONTH" "DAY" "HOUR" "SECOND" and so on.

func ToString

func ToString(value any) (string, error)

ToString converts an interface to a string.

func Truncate

func Truncate(f float64, dec int) float64

Truncate truncates the argument f to dec decimal places. dec defaults to 0 if not specified. dec can be negative to cause dec digits left of the decimal point of the value f to become zero.

func TruncateFloat

func TruncateFloat(f float64, flen int, decimal int) (float64, error)

TruncateFloat tries to truncate f. If the result exceeds the max/min float that flen/decimal allowed, returns the max/min float allowed.

func TruncateFloatToString

func TruncateFloatToString(f float64, dec int) string

TruncateFloatToString is used to truncate float to string where dec is the number of digits after the decimal point.

func TruncateFrac

func TruncateFrac(t gotime.Time, fsp int) (gotime.Time, error)

TruncateFrac truncates fractional seconds precision with new fsp and returns a new one. 2011:11:11 10:10:10.888888 round 0 -> 2011:11:11 10:10:10 2011:11:11 10:10:10.111111 round 0 -> 2011:11:11 10:10:10

func TruncateOverflowMySQLTime

func TruncateOverflowMySQLTime(d gotime.Duration) (gotime.Duration, error)

TruncateOverflowMySQLTime truncates d when it overflows, and returns ErrTruncatedWrongVal.

func TryToFixFlenOfDatetime

func TryToFixFlenOfDatetime(resultTp *FieldType)

TryToFixFlenOfDatetime try to fix flen of Datetime for specific func or other field merge cases

func UnquoteString

func UnquoteString(str string) (string, error)

UnquoteString remove quotes in a string, including the quotes at the head and tail of string.

func VecCompareII

func VecCompareII(x, y, res []int64)

VecCompareII returns []int64 comparing the []int64 x to []int64 y

func VecCompareIU

func VecCompareIU(x []int64, y []uint64, res []int64)

VecCompareIU returns []int64 comparing the []int64 x to []uint64y

func VecCompareUI

func VecCompareUI(x []uint64, y, res []int64)

VecCompareUI returns []int64 comparing the []uint64 x to []int64y

func VecCompareUU

func VecCompareUU(x, y []uint64, res []int64)

VecCompareUU returns []int64 comparing the []uint64 x to []uint64 y

Types

type BinaryJSON

type BinaryJSON struct {
	TypeCode JSONTypeCode
	Value    []byte
}

BinaryJSON represents a binary encoded JSON object. It can be randomly accessed without deserialization.

func CreateBinaryJSON

func CreateBinaryJSON(in any) BinaryJSON

CreateBinaryJSON creates a BinaryJSON from interface.

func CreateBinaryJSONWithCheck

func CreateBinaryJSONWithCheck(in any) (BinaryJSON, error)

CreateBinaryJSONWithCheck creates a BinaryJSON from interface with error check.

func MergeBinaryJSON

func MergeBinaryJSON(bjs []BinaryJSON) BinaryJSON

MergeBinaryJSON merges multiple BinaryJSON into one according the following rules: 1) adjacent arrays are merged to a single array; 2) adjacent object are merged to a single object; 3) a scalar value is autowrapped as an array before merge; 4) an adjacent array and object are merged by autowrapping the object as an array.

func MergePatchBinaryJSON

func MergePatchBinaryJSON(bjs []*BinaryJSON) (*BinaryJSON, error)

MergePatchBinaryJSON implements RFC7396 https://datatracker.ietf.org/doc/html/rfc7396

func ParseBinaryJSONFromString

func ParseBinaryJSONFromString(s string) (bj BinaryJSON, err error)

ParseBinaryJSONFromString parses a json from string.

func (BinaryJSON) ArrayGetElem

func (bj BinaryJSON) ArrayGetElem(idx int) BinaryJSON

ArrayGetElem gets the element of the index `idx`.

func (BinaryJSON) ArrayInsert

func (bj BinaryJSON) ArrayInsert(pathExpr JSONPathExpression, value BinaryJSON) (res BinaryJSON, err error)

ArrayInsert insert a BinaryJSON into the given array cell. All path expressions cannot contain * or ** wildcard. If any error occurs, the input won't be changed.

func (BinaryJSON) Copy

func (bj BinaryJSON) Copy() BinaryJSON

Copy makes a copy of the BinaryJSON

func (BinaryJSON) Extract

func (bj BinaryJSON) Extract(pathExprList []JSONPathExpression) (ret BinaryJSON, found bool)

Extract receives several path expressions as arguments, matches them in bj, and returns:

ret: target JSON matched any path expressions. maybe autowrapped as an array.
found: true if any path expressions matched.

func (BinaryJSON) GetDuration

func (bj BinaryJSON) GetDuration() Duration

GetDuration gets the duration value

func (BinaryJSON) GetElemCount

func (bj BinaryJSON) GetElemCount() int

GetElemCount gets the count of Object or Array.

func (BinaryJSON) GetElemDepth

func (bj BinaryJSON) GetElemDepth() int

GetElemDepth for JSON_DEPTH Returns the maximum depth of a JSON document rules referenced by MySQL JSON_DEPTH function [https://dev.mysql.com/doc/refman/5.7/en/json-attribute-functions.html#function_json-depth] 1) An empty array, empty object, or scalar value has depth 1. 2) A nonempty array containing only elements of depth 1 or nonempty object containing only member values of depth 1 has depth 2. 3) Otherwise, a JSON document has depth greater than 2. e.g. depth of '{}', '[]', 'true': 1 e.g. depth of '[10, 20]', '[[], {}]': 2 e.g. depth of '[10, {"a": 20}]': 3

func (BinaryJSON) GetFloat64

func (bj BinaryJSON) GetFloat64() float64

GetFloat64 gets the float64 value.

func (BinaryJSON) GetInt64

func (bj BinaryJSON) GetInt64() int64

GetInt64 gets the int64 value.

func (BinaryJSON) GetKeys

func (bj BinaryJSON) GetKeys() BinaryJSON

GetKeys gets the keys of the object

func (BinaryJSON) GetOpaque

func (bj BinaryJSON) GetOpaque() Opaque

GetOpaque gets the opaque value

func (BinaryJSON) GetOpaqueFieldType

func (bj BinaryJSON) GetOpaqueFieldType() byte

GetOpaqueFieldType returns the type of opaque value

func (BinaryJSON) GetString

func (bj BinaryJSON) GetString() []byte

GetString gets the string value.

func (BinaryJSON) GetTime deprecated

func (bj BinaryJSON) GetTime() Time

GetTime gets the time value with default fsp

Deprecated: use GetTimeWithFsp instead. The `BinaryJSON` doesn't contain the fsp information, so the caller should always provide the fsp.

func (BinaryJSON) GetTimeWithFsp

func (bj BinaryJSON) GetTimeWithFsp(fsp int) Time

GetTimeWithFsp gets the time value with given fsp

func (BinaryJSON) GetUint64

func (bj BinaryJSON) GetUint64() uint64

GetUint64 gets the uint64 value.

func (BinaryJSON) GetValue

func (bj BinaryJSON) GetValue() any

GetValue return the primitive value of the JSON.

func (BinaryJSON) HashValue

func (bj BinaryJSON) HashValue(buf []byte) []byte

HashValue converts certain JSON values for aggregate comparisons. For example int64(3) == float64(3.0) Other than the numeric condition, this function has to construct a bidirectional map between hash value and the original representation

func (BinaryJSON) IsZero

func (bj BinaryJSON) IsZero() bool

IsZero return a boolean indicate whether BinaryJSON is Zero

func (BinaryJSON) MarshalJSON

func (bj BinaryJSON) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (BinaryJSON) Modify

func (bj BinaryJSON) Modify(pathExprList []JSONPathExpression, values []BinaryJSON, mt JSONModifyType) (retj BinaryJSON, err error)

Modify modifies a JSON object by insert, replace or set. All path expressions cannot contain * or ** wildcard. If any error occurs, the input won't be changed.

func (BinaryJSON) Remove

func (bj BinaryJSON) Remove(pathExprList []JSONPathExpression) (BinaryJSON, error)

Remove removes the elements indicated by pathExprList from JSON.

func (BinaryJSON) Search

func (bj BinaryJSON) Search(containType string, search string, escape byte, pathExpres []JSONPathExpression) (res BinaryJSON, isNull bool, err error)

Search for JSON_Search rules referenced by MySQL JSON_SEARCH function [https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#function_json-search]

func (BinaryJSON) String

func (bj BinaryJSON) String() string

String implements fmt.Stringer interface.

func (BinaryJSON) Type

func (bj BinaryJSON) Type() string

Type returns type of BinaryJSON as string.

func (*BinaryJSON) UnmarshalJSON

func (bj *BinaryJSON) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (BinaryJSON) Unquote

func (bj BinaryJSON) Unquote() (string, error)

Unquote is for JSON_UNQUOTE.

func (BinaryJSON) Walk

func (bj BinaryJSON) Walk(walkFn BinaryJSONWalkFunc, pathExprList ...JSONPathExpression) (err error)

Walk traverse BinaryJSON objects

type BinaryJSONWalkFunc

type BinaryJSONWalkFunc func(fullpath JSONPathExpression, bj BinaryJSON) (stop bool, err error)

BinaryJSONWalkFunc is used as callback function for BinaryJSON.Walk

type BinaryLiteral

type BinaryLiteral []byte

BinaryLiteral is the internal type for storing bit / hex literal type.

func NewBinaryLiteralFromUint

func NewBinaryLiteralFromUint(value uint64, byteSize int) BinaryLiteral

NewBinaryLiteralFromUint creates a new BinaryLiteral instance by the given uint value in BitEndian. byteSize will be used as the length of the new BinaryLiteral, with leading bytes filled to zero. If byteSize is -1, the leading zeros in new BinaryLiteral will be trimmed.

func ParseBitStr

func ParseBitStr(s string) (BinaryLiteral, error)

ParseBitStr parses bit string. The string format can be b'val', B'val' or 0bval, val must be 0 or 1. See https://dev.mysql.com/doc/refman/5.7/en/bit-value-literals.html

func ParseHexStr

func ParseHexStr(s string) (BinaryLiteral, error)

ParseHexStr parses hexadecimal string literal. See https://dev.mysql.com/doc/refman/5.7/en/hexadecimal-literals.html

func (BinaryLiteral) Compare

func (b BinaryLiteral) Compare(b2 BinaryLiteral) int

Compare compares BinaryLiteral to another one

func (BinaryLiteral) String

func (b BinaryLiteral) String() string

String implements fmt.Stringer interface.

func (BinaryLiteral) ToBitLiteralString

func (b BinaryLiteral) ToBitLiteralString(trimLeadingZero bool) string

ToBitLiteralString returns the bit literal representation for the literal.

func (BinaryLiteral) ToInt

func (b BinaryLiteral) ToInt(ctx Context) (uint64, error)

ToInt returns the int value for the literal.

func (BinaryLiteral) ToString

func (b BinaryLiteral) ToString() string

ToString returns the string representation for the literal.

type BitLiteral

type BitLiteral BinaryLiteral

BitLiteral is the bit literal type.

func NewBitLiteral

func NewBitLiteral(s string) (BitLiteral, error)

NewBitLiteral parses bit string as BitLiteral type.

func (BitLiteral) ToString

func (b BitLiteral) ToString() string

ToString implement ast.BinaryLiteral interface

type Context

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

Context provides the information when converting between different types.

func NewContext

func NewContext(flags Flags, loc *time.Location, handler contextutil.WarnAppender) Context

NewContext creates a new `Context`

func (*Context) AppendWarning

func (c *Context) AppendWarning(err error)

AppendWarning appends the error to warning. If the inner `warnHandler` is nil, do nothing.

func (*Context) Flags

func (c *Context) Flags() Flags

Flags returns the flags of the context

func (*Context) HandleTruncate

func (c *Context) HandleTruncate(err error) error

HandleTruncate ignores or returns the error based on the Context state.

func (*Context) Location

func (c *Context) Location() *time.Location

Location returns the location of the context

func (*Context) WithFlags

func (c *Context) WithFlags(f Flags) Context

WithFlags returns a new context with the flags set to the given value

func (*Context) WithLocation

func (c *Context) WithLocation(loc *time.Location) Context

WithLocation returns a new context with the given location

type CoreTime

type CoreTime uint64

CoreTime is the internal struct type for Time.

func FromDate

func FromDate(year int, month int, day int, hour int, minute int, second int, microsecond int) CoreTime

FromDate makes a internal time representation from the given date.

func FromDateChecked

func FromDateChecked(year, month, day, hour, minute, second, microsecond int) (CoreTime, bool)

FromDateChecked makes a internal time representation from the given date with field overflow check.

func FromGoTime

func FromGoTime(t gotime.Time) CoreTime

FromGoTime translates time.Time to mysql time internal representation.

func (CoreTime) AdjustedGoTime

func (t CoreTime) AdjustedGoTime(loc *gotime.Location) (gotime.Time, error)

AdjustedGoTime converts Time to GoTime and adjust for invalid DST times like during the DST change with increased offset, normally moving to Daylight Saving Time. see https://github.com/pingcap/tidb/issues/28739

func (CoreTime) Day

func (t CoreTime) Day() int

Day returns the day value.

func (CoreTime) GoTime

func (t CoreTime) GoTime(loc *gotime.Location) (gotime.Time, error)

GoTime converts Time to GoTime.

func (CoreTime) Hour

func (t CoreTime) Hour() int

Hour returns the hour value.

func (CoreTime) IsLeapYear

func (t CoreTime) IsLeapYear() bool

IsLeapYear returns if it's leap year.

func (CoreTime) Microsecond

func (t CoreTime) Microsecond() int

Microsecond returns the microsecond value.

func (CoreTime) Minute

func (t CoreTime) Minute() int

Minute returns the minute value.

func (CoreTime) Month

func (t CoreTime) Month() int

Month returns the month value.

func (CoreTime) Second

func (t CoreTime) Second() int

Second returns the second value.

func (CoreTime) String

func (t CoreTime) String() string

String implements fmt.Stringer.

func (CoreTime) Week

func (t CoreTime) Week(mode int) int

Week returns week value.

func (CoreTime) Weekday

func (t CoreTime) Weekday() gotime.Weekday

Weekday returns weekday value.

func (CoreTime) Year

func (t CoreTime) Year() int

Year returns the year value.

func (CoreTime) YearDay

func (t CoreTime) YearDay() int

YearDay returns year and day.

func (CoreTime) YearWeek

func (t CoreTime) YearWeek(mode int) (year int, week int)

YearWeek returns year and week.

type Datum

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

Datum is a data box holds different kind of data. It has better performance and is easier to use than `interface{}`.

func ChangeReverseResultByUpperLowerBound

func ChangeReverseResultByUpperLowerBound(
	ctx Context,
	retType *FieldType,
	res Datum,
	rType RoundingType) (Datum, error)

ChangeReverseResultByUpperLowerBound is for expression's reverse evaluation. Here is an example for what's effort for the function: CastRealAsInt(t.a),

		if the type of column `t.a` is mysql.TypeDouble, and there is a row that t.a == MaxFloat64
		then the cast function will arrive a result MaxInt64. But when we do the reverse evaluation,
     if the result is MaxInt64, and the rounding type is ceiling. Then we should get the MaxFloat64
     instead of float64(MaxInt64).

Another example: cast(1.1 as signed) = 1,

when we get the answer 1, we can only reversely evaluate 1.0 as the column value. So in this
case, we should judge whether the rounding type are ceiling. If it is, then we should plus one for
1.0 and get the reverse result 2.0.

func CloneRow

func CloneRow(dr []Datum) []Datum

CloneRow deep copies a Datum slice.

func ComputePlus

func ComputePlus(a, b Datum) (d Datum, err error)

ComputePlus computes the result of a+b.

func GetMaxValue

func GetMaxValue(ft *FieldType) (maxVal Datum)

GetMaxValue returns the max value datum for each type.

func GetMinValue

func GetMinValue(ft *FieldType) (minVal Datum)

GetMinValue returns the min value datum for each type.

func MakeDatums

func MakeDatums(args ...any) []Datum

MakeDatums creates datum slice from interfaces.

func MaxValueDatum

func MaxValueDatum() Datum

MaxValueDatum returns a datum represents max value.

func MinNotNullDatum

func MinNotNullDatum() Datum

MinNotNullDatum returns a datum represents minimum not null value.

func NewBinaryLiteralDatum

func NewBinaryLiteralDatum(b BinaryLiteral) (d Datum)

NewBinaryLiteralDatum creates a new BinaryLiteral Datum for a BinaryLiteral value.

func NewBytesDatum

func NewBytesDatum(b []byte) (d Datum)

NewBytesDatum creates a new Datum from a byte slice.

func NewCollateMysqlEnumDatum

func NewCollateMysqlEnumDatum(e Enum, collation string) (d Datum)

NewCollateMysqlEnumDatum create a new MysqlEnum Datum for a Enum value with collation information.

func NewCollationStringDatum

func NewCollationStringDatum(s string, collation string) (d Datum)

NewCollationStringDatum creates a new Datum from a string with collation.

func NewDatum

func NewDatum(in any) (d Datum)

NewDatum creates a new Datum from an interface{}.

func NewDecimalDatum

func NewDecimalDatum(dec *MyDecimal) (d Datum)

NewDecimalDatum creates a new Datum from a MyDecimal value.

func NewDurationDatum

func NewDurationDatum(dur Duration) (d Datum)

NewDurationDatum creates a new Datum from a Duration value.

func NewFloat32Datum

func NewFloat32Datum(f float32) (d Datum)

NewFloat32Datum creates a new Datum from a float32 value.

func NewFloat64Datum

func NewFloat64Datum(f float64) (d Datum)

NewFloat64Datum creates a new Datum from a float64 value.

func NewIntDatum

func NewIntDatum(i int64) (d Datum)

NewIntDatum creates a new Datum from an int64 value.

func NewJSONDatum

func NewJSONDatum(j BinaryJSON) (d Datum)

NewJSONDatum creates a new Datum from a BinaryJSON value

func NewMysqlBitDatum

func NewMysqlBitDatum(b BinaryLiteral) (d Datum)

NewMysqlBitDatum creates a new MysqlBit Datum for a BinaryLiteral value.

func NewMysqlEnumDatum

func NewMysqlEnumDatum(e Enum) (d Datum)

NewMysqlEnumDatum creates a new MysqlEnum Datum for a Enum value.

func NewMysqlSetDatum

func NewMysqlSetDatum(e Set, collation string) (d Datum)

NewMysqlSetDatum creates a new MysqlSet Datum for a Enum value.

func NewStringDatum

func NewStringDatum(s string) (d Datum)

NewStringDatum creates a new Datum from a string.

func NewTimeDatum

func NewTimeDatum(t Time) (d Datum)

NewTimeDatum creates a new Time from a Time value.

func NewUintDatum

func NewUintDatum(i uint64) (d Datum)

NewUintDatum creates a new Datum from an uint64 value.

func NewVectorFloat32Datum

func NewVectorFloat32Datum(v VectorFloat32) (d Datum)

NewVectorFloat32Datum creates a new Datum from a VectorFloat32 value

func (*Datum) Clone

func (d *Datum) Clone() *Datum

Clone create a deep copy of the Datum.

func (*Datum) Collation

func (d *Datum) Collation() string

Collation gets the collation of the datum.

func (*Datum) Compare

func (d *Datum) Compare(ctx Context, ad *Datum, comparer collate.Collator) (int, error)

Compare compares datum to another datum. Notes: don't rely on datum.collation to get the collator, it's tend to buggy.

func (*Datum) ConvertTo

func (d *Datum) ConvertTo(ctx Context, target *FieldType) (Datum, error)

ConvertTo converts a datum to the target field type. change this method need sync modification to type2Kind in rowcodec/types.go

func (*Datum) ConvertToMysqlYear

func (d *Datum) ConvertToMysqlYear(ctx Context, target *FieldType) (Datum, error)

ConvertToMysqlYear converts a datum to MySQLYear.

func (*Datum) Copy

func (d *Datum) Copy(dst *Datum)

Copy deep copies a Datum into destination.

func (*Datum) Equals

func (d *Datum) Equals(other any) bool

Equals implements base.HashEquals.<1st> interface.

func (Datum) EstimatedMemUsage

func (d Datum) EstimatedMemUsage() int64

EstimatedMemUsage returns the estimated bytes consumed of a Datum.

func (*Datum) Frac

func (d *Datum) Frac() int

Frac gets the frac of the datum.

func (*Datum) GetBinaryLiteral

func (d *Datum) GetBinaryLiteral() BinaryLiteral

GetBinaryLiteral gets Bit value

func (*Datum) GetBinaryLiteral4Cmp

func (d *Datum) GetBinaryLiteral4Cmp() BinaryLiteral

GetBinaryLiteral4Cmp gets Bit value, and remove it's prefix 0 for comparison.

func (*Datum) GetBinaryStringDecoded

func (d *Datum) GetBinaryStringDecoded(flags Flags, chs string) (string, error)

GetBinaryStringDecoded gets the string value decoded with given charset.

func (*Datum) GetBinaryStringEncoded

func (d *Datum) GetBinaryStringEncoded() string

GetBinaryStringEncoded gets the string value encoded with given charset.

func (*Datum) GetBytes

func (d *Datum) GetBytes() []byte

GetBytes gets bytes value.

func (*Datum) GetFloat32

func (d *Datum) GetFloat32() float32

GetFloat32 gets float32 value.

func (*Datum) GetFloat64

func (d *Datum) GetFloat64() float64

GetFloat64 gets float64 value.

func (*Datum) GetInt64

func (d *Datum) GetInt64() int64

GetInt64 gets int64 value.

func (*Datum) GetInterface

func (d *Datum) GetInterface() any

GetInterface gets interface value.

func (*Datum) GetMysqlBit

func (d *Datum) GetMysqlBit() BinaryLiteral

GetMysqlBit gets MysqlBit value

func (*Datum) GetMysqlDecimal

func (d *Datum) GetMysqlDecimal() *MyDecimal

GetMysqlDecimal gets decimal value

func (*Datum) GetMysqlDuration

func (d *Datum) GetMysqlDuration() Duration

GetMysqlDuration gets Duration value

func (*Datum) GetMysqlEnum

func (d *Datum) GetMysqlEnum() Enum

GetMysqlEnum gets Enum value

func (*Datum) GetMysqlJSON

func (d *Datum) GetMysqlJSON() BinaryJSON

GetMysqlJSON gets json.BinaryJSON value

func (*Datum) GetMysqlSet

func (d *Datum) GetMysqlSet() Set

GetMysqlSet gets Set value

func (*Datum) GetMysqlTime

func (d *Datum) GetMysqlTime() Time

GetMysqlTime gets types.Time value

func (*Datum) GetRaw

func (d *Datum) GetRaw() []byte

GetRaw gets raw value.

func (*Datum) GetString

func (d *Datum) GetString() string

GetString gets string value.

func (*Datum) GetStringWithCheck

func (d *Datum) GetStringWithCheck(flags Flags, chs string) (string, error)

GetStringWithCheck gets the string and checks if it is valid in a given charset.

func (*Datum) GetUint64

func (d *Datum) GetUint64() uint64

GetUint64 gets uint64 value.

func (*Datum) GetValue

func (d *Datum) GetValue() any

GetValue gets the value of the datum of any kind.

func (*Datum) GetVectorFloat32

func (d *Datum) GetVectorFloat32() VectorFloat32

GetVectorFloat32 gets VectorFloat32 value

func (*Datum) Hash64

func (d *Datum) Hash64(h base.Hasher)

Hash64 implements base.HashEquals<0th> interface.

func (*Datum) IsNull

func (d *Datum) IsNull() bool

IsNull checks if datum is null.

func (*Datum) Kind

func (d *Datum) Kind() byte

Kind gets the kind of the datum.

func (*Datum) Length

func (d *Datum) Length() int

Length gets the length of the datum.

func (*Datum) MarshalJSON

func (d *Datum) MarshalJSON() ([]byte, error)

MarshalJSON implements Marshaler.MarshalJSON interface.

func (*Datum) MemUsage

func (d *Datum) MemUsage() (sum int64)

MemUsage gets the memory usage of datum.

func (*Datum) SetAutoID

func (d *Datum) SetAutoID(id int64, flag uint)

SetAutoID set the auto increment ID according to its int flag. Don't use it directly, useless wrapped with setDatumAutoIDAndCast.

func (*Datum) SetBinaryLiteral

func (d *Datum) SetBinaryLiteral(b BinaryLiteral)

SetBinaryLiteral sets Bit value

func (*Datum) SetBytes

func (d *Datum) SetBytes(b []byte)

SetBytes sets bytes value to datum.

func (*Datum) SetBytesAsString

func (d *Datum) SetBytesAsString(b []byte, collation string, length uint32)

SetBytesAsString sets bytes value to datum as string type.

func (*Datum) SetCollation

func (d *Datum) SetCollation(collation string)

SetCollation sets the collation of the datum.

func (*Datum) SetFloat32

func (d *Datum) SetFloat32(f float32)

SetFloat32 sets float32 value.

func (*Datum) SetFloat32FromF64

func (d *Datum) SetFloat32FromF64(f float64)

SetFloat32FromF64 sets float32 values from f64

func (*Datum) SetFloat64

func (d *Datum) SetFloat64(f float64)

SetFloat64 sets float64 value.

func (*Datum) SetFrac

func (d *Datum) SetFrac(frac int)

SetFrac sets the frac of the datum.

func (*Datum) SetInt64

func (d *Datum) SetInt64(i int64)

SetInt64 sets int64 value.

func (*Datum) SetInterface

func (d *Datum) SetInterface(x any)

SetInterface sets interface to datum.

func (*Datum) SetLength

func (d *Datum) SetLength(l int)

SetLength sets the length of the datum.

func (*Datum) SetMinNotNull

func (d *Datum) SetMinNotNull()

SetMinNotNull sets datum to minNotNull value.

func (*Datum) SetMysqlBit

func (d *Datum) SetMysqlBit(b BinaryLiteral)

SetMysqlBit sets MysqlBit value

func (*Datum) SetMysqlDecimal

func (d *Datum) SetMysqlDecimal(b *MyDecimal)

SetMysqlDecimal sets decimal value

func (*Datum) SetMysqlDuration

func (d *Datum) SetMysqlDuration(b Duration)

SetMysqlDuration sets Duration value

func (*Datum) SetMysqlEnum

func (d *Datum) SetMysqlEnum(b Enum, collation string)

SetMysqlEnum sets Enum value

func (*Datum) SetMysqlJSON

func (d *Datum) SetMysqlJSON(b BinaryJSON)

SetMysqlJSON sets json.BinaryJSON value

func (*Datum) SetMysqlSet

func (d *Datum) SetMysqlSet(b Set, collation string)

SetMysqlSet sets Set value

func (*Datum) SetMysqlTime

func (d *Datum) SetMysqlTime(b Time)

SetMysqlTime sets types.Time value

func (*Datum) SetNull

func (d *Datum) SetNull()

SetNull sets datum to nil.

func (*Datum) SetRaw

func (d *Datum) SetRaw(b []byte)

SetRaw sets raw value.

func (*Datum) SetString

func (d *Datum) SetString(s string, collation string)

SetString sets string value.

func (*Datum) SetUint64

func (d *Datum) SetUint64(i uint64)

SetUint64 sets uint64 value.

func (*Datum) SetValue

func (d *Datum) SetValue(val any, tp *types.FieldType)

SetValue sets any kind of value.

func (*Datum) SetValueWithDefaultCollation

func (d *Datum) SetValueWithDefaultCollation(val any)

SetValueWithDefaultCollation sets any kind of value.

func (*Datum) SetVectorFloat32

func (d *Datum) SetVectorFloat32(vec VectorFloat32)

SetVectorFloat32 sets VectorFloat32 value

func (Datum) String

func (d Datum) String() string

String returns a human-readable description of Datum. It is intended only for debugging.

func (*Datum) ToBool

func (d *Datum) ToBool(ctx Context) (int64, error)

ToBool converts to a bool. We will use 1 for true, and 0 for false.

func (*Datum) ToBytes

func (d *Datum) ToBytes() ([]byte, error)

ToBytes gets the bytes representation of the datum.

func (*Datum) ToDecimal

func (d *Datum) ToDecimal(ctx Context) (*MyDecimal, error)

ToDecimal converts to a decimal.

func (*Datum) ToFloat64

func (d *Datum) ToFloat64(ctx Context) (float64, error)

ToFloat64 converts to a float64

func (*Datum) ToHashKey

func (d *Datum) ToHashKey() ([]byte, error)

ToHashKey gets the bytes representation of the datum considering collation.

func (*Datum) ToInt64

func (d *Datum) ToInt64(ctx Context) (int64, error)

ToInt64 converts to a int64.

func (*Datum) ToMysqlJSON

func (d *Datum) ToMysqlJSON() (j BinaryJSON, err error)

ToMysqlJSON is similar to convertToMysqlJSON, except the latter parses from string, but the former uses it as primitive.

func (*Datum) ToString

func (d *Datum) ToString() (string, error)

ToString gets the string representation of the datum.

func (*Datum) TruncatedStringify

func (d *Datum) TruncatedStringify() string

TruncatedStringify returns the %v representation of the datum but truncated (for example, for strings, only first 64 bytes is printed). This function is useful in contexts like EXPLAIN.

func (*Datum) UnmarshalJSON

func (d *Datum) UnmarshalJSON(data []byte) error

UnmarshalJSON implements Unmarshaler.UnmarshalJSON interface.

type Duration

type Duration struct {
	gotime.Duration
	// Fsp is short for Fractional Seconds Precision.
	// See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
	Fsp int
}

Duration is the type for MySQL TIME type.

func ExtractDurationValue

func ExtractDurationValue(unit string, format string) (Duration, error)

ExtractDurationValue extract the value from format to Duration.

func MaxMySQLDuration

func MaxMySQLDuration(fsp int) Duration

MaxMySQLDuration returns Duration with maximum mysql time.

func NewDuration

func NewDuration(hour, minute, second, microsecond int, fsp int) Duration

NewDuration construct duration with time.

func NumberToDuration

func NumberToDuration(number int64, fsp int) (Duration, error)

NumberToDuration converts number to Duration.

func ParseDuration

func ParseDuration(ctx Context, str string, fsp int) (Duration, bool, error)

ParseDuration parses the time form a formatted string with a fractional seconds part, returns the duration type Time value and bool to indicate whether the result is null. See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html

func (Duration) Add

func (d Duration) Add(v Duration) (Duration, error)

Add adds d to d, returns a duration value.

func (Duration) Compare

func (d Duration) Compare(o Duration) int

Compare returns an integer comparing the Duration instant t to o. If d is after o, returns 1, equal o, returns 0, before o, returns -1.

func (Duration) CompareString

func (d Duration) CompareString(ctx Context, str string) (int, error)

CompareString is like Compare, but parses str to Duration then compares.

func (Duration) ConvertToTime

func (d Duration) ConvertToTime(ctx Context, tp uint8) (Time, error)

ConvertToTime converts duration to Time. Tp is TypeDatetime, TypeTimestamp and TypeDate.

func (Duration) ConvertToTimeWithTimestamp

func (d Duration) ConvertToTimeWithTimestamp(ctx Context, tp uint8, ts gotime.Time) (Time, error)

ConvertToTimeWithTimestamp converts duration to Time by system timestamp. Tp is TypeDatetime, TypeTimestamp and TypeDate.

func (Duration) ConvertToYear

func (d Duration) ConvertToYear(ctx Context) (int64, error)

ConvertToYear converts duration to Year.

func (Duration) ConvertToYearFromNow

func (d Duration) ConvertToYearFromNow(ctx Context, now gotime.Time) (int64, error)

ConvertToYearFromNow converts duration to Year, with the `now` specified by the argument.

func (Duration) DurationFormat

func (d Duration) DurationFormat(layout string) (string, error)

DurationFormat returns a textual representation of the duration value formatted according to layout. See http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format

func (Duration) Hour

func (d Duration) Hour() int

Hour returns current hour. e.g, hour("11:11:11") -> 11

func (Duration) MicroSecond

func (d Duration) MicroSecond() int

MicroSecond returns current microsecond. e.g, hour("11:11:11.11") -> 110000

func (Duration) Minute

func (d Duration) Minute() int

Minute returns current minute. e.g, hour("11:11:11") -> 11

func (Duration) Neg

func (d Duration) Neg() Duration

Neg negative d, returns a duration value.

func (Duration) RoundFrac

func (d Duration) RoundFrac(fsp int, loc *gotime.Location) (Duration, error)

RoundFrac rounds fractional seconds precision with new fsp and returns a new one. We will use the “round half up” rule, e.g, >= 0.5 -> 1, < 0.5 -> 0, so 10:10:10.999999 round 0 -> 10:10:11 and 10:10:10.000000 round 0 -> 10:10:10

func (Duration) Second

func (d Duration) Second() int

Second returns current second. e.g, hour("11:11:11") -> 11

func (Duration) String

func (d Duration) String() string

String returns the time formatted using default TimeFormat and fsp.

func (Duration) Sub

func (d Duration) Sub(v Duration) (Duration, error)

Sub subtracts d to d, returns a duration value.

func (Duration) ToNumber

func (d Duration) ToNumber() *MyDecimal

ToNumber changes duration to number format. e.g, 10:10:10 -> 101010

type Enum

type Enum struct {
	Name  string
	Value uint64
}

Enum is for MySQL enum type.

func ParseEnum

func ParseEnum(elems []string, name string, collation string) (Enum, error)

ParseEnum creates a Enum with item name or value.

func ParseEnumName

func ParseEnumName(elems []string, name string, collation string) (Enum, error)

ParseEnumName creates a Enum with item name.

func ParseEnumValue

func ParseEnumValue(elems []string, number uint64) (Enum, error)

ParseEnumValue creates a Enum with special number.

func (Enum) Copy

func (e Enum) Copy() Enum

Copy deep copy an Enum.

func (Enum) String

func (e Enum) String() string

String implements fmt.Stringer interface.

func (Enum) ToNumber

func (e Enum) ToNumber() float64

ToNumber changes enum index to float64 for numeric operation.

type EvalType

type EvalType = ast.EvalType

EvalType indicates the specified types that arguments and result of a built-in function should be.

func AggregateEvalType

func AggregateEvalType(fts []*FieldType, flag *uint) EvalType

AggregateEvalType aggregates arguments' EvalType of a multi-argument function.

type FieldName

type FieldName struct {
	OrigTblName model.CIStr
	OrigColName model.CIStr
	DBName      model.CIStr
	TblName     model.CIStr
	ColName     model.CIStr

	Hidden bool

	// NotExplicitUsable is used for mark whether a column can be explicit used in SQL.
	// update stmt can write `writeable` column implicitly but cannot use non-public columns explicit.
	// e.g. update t set a = 10 where b = 10; which `b` is in `writeOnly` state
	NotExplicitUsable bool

	Redundant bool
}

FieldName records the names used for mysql protocol.

func (*FieldName) MemoryUsage

func (name *FieldName) MemoryUsage() (sum int64)

MemoryUsage return the memory usage of FieldName

func (*FieldName) String

func (name *FieldName) String() string

String implements Stringer interface.

type FieldType

type FieldType = ast.FieldType

FieldType records field type information.

func AggFieldType

func AggFieldType(tps []*FieldType) *FieldType

AggFieldType aggregates field types for a multi-argument function like `IF`, `IFNULL`, `COALESCE` whose return type is determined by the arguments' FieldTypes. Aggregation is performed by MergeFieldType function.

func NewFieldType

func NewFieldType(tp byte) *FieldType

NewFieldType returns a FieldType, with a type and other information about field type.

func NewFieldTypeWithCollation

func NewFieldTypeWithCollation(tp byte, collation string, length int) *FieldType

NewFieldTypeWithCollation returns a FieldType, with a type and other information about field type.

type FieldTypeBuilder

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

FieldTypeBuilder constructor

func NewFieldTypeBuilder

func NewFieldTypeBuilder() *FieldTypeBuilder

NewFieldTypeBuilder will allocate the builder on the heap.

func (*FieldTypeBuilder) AddFlag

func (b *FieldTypeBuilder) AddFlag(flag uint) *FieldTypeBuilder

AddFlag adds flag to the ft

func (*FieldTypeBuilder) Build

func (b *FieldTypeBuilder) Build() FieldType

Build returns the ft

func (*FieldTypeBuilder) BuildP

func (b *FieldTypeBuilder) BuildP() *FieldType

BuildP returns pointer of the ft

func (*FieldTypeBuilder) DelFlag

func (b *FieldTypeBuilder) DelFlag(flag uint) *FieldTypeBuilder

DelFlag deletes flag of the ft

func (*FieldTypeBuilder) GetCharset

func (b *FieldTypeBuilder) GetCharset() string

GetCharset returns charset of the ft

func (*FieldTypeBuilder) GetCollate

func (b *FieldTypeBuilder) GetCollate() string

GetCollate returns collation of the ft

func (*FieldTypeBuilder) GetDecimal

func (b *FieldTypeBuilder) GetDecimal() int

GetDecimal returns decimals of the ft

func (*FieldTypeBuilder) GetFlag

func (b *FieldTypeBuilder) GetFlag() uint

GetFlag returns flag of the ft

func (*FieldTypeBuilder) GetFlen

func (b *FieldTypeBuilder) GetFlen() int

GetFlen returns length of the ft

func (*FieldTypeBuilder) GetType

func (b *FieldTypeBuilder) GetType() byte

GetType returns type of the ft

func (*FieldTypeBuilder) SetArray

func (b *FieldTypeBuilder) SetArray(x bool) *FieldTypeBuilder

SetArray sets array of the ft

func (*FieldTypeBuilder) SetCharset

func (b *FieldTypeBuilder) SetCharset(charset string) *FieldTypeBuilder

SetCharset sets charset of the ft

func (*FieldTypeBuilder) SetCollate

func (b *FieldTypeBuilder) SetCollate(collate string) *FieldTypeBuilder

SetCollate sets collation of the ft

func (*FieldTypeBuilder) SetDecimal

func (b *FieldTypeBuilder) SetDecimal(decimal int) *FieldTypeBuilder

SetDecimal sets decimal of the ft

func (*FieldTypeBuilder) SetElems

func (b *FieldTypeBuilder) SetElems(elems []string) *FieldTypeBuilder

SetElems sets elements of the ft

func (*FieldTypeBuilder) SetFlag

func (b *FieldTypeBuilder) SetFlag(flag uint) *FieldTypeBuilder

SetFlag sets flag of the ft

func (*FieldTypeBuilder) SetFlen

func (b *FieldTypeBuilder) SetFlen(flen int) *FieldTypeBuilder

SetFlen sets length of the ft

func (*FieldTypeBuilder) SetType

func (b *FieldTypeBuilder) SetType(tp byte) *FieldTypeBuilder

SetType sets type of the ft

func (*FieldTypeBuilder) ToggleFlag

func (b *FieldTypeBuilder) ToggleFlag(flag uint) *FieldTypeBuilder

ToggleFlag toggles flag of the ft

type Flags

type Flags uint16

Flags indicate how to handle the conversion of a value.

const (
	// FlagIgnoreTruncateErr indicates to ignore the truncate error.
	// If this flag is set, `FlagTruncateAsWarning` will be ignored.
	FlagIgnoreTruncateErr Flags = 1 << iota
	// FlagTruncateAsWarning indicates to append the truncate error to warnings instead of returning it to user.
	FlagTruncateAsWarning
	// FlagAllowNegativeToUnsigned indicates to allow the casting from negative to unsigned int.
	// When this flag is not set by default, casting a negative value to unsigned results an overflow error.
	// Otherwise, a negative value will be cast to the corresponding unsigned value without any error.
	// For example, when casting -1 to an unsigned bigint with `FlagAllowNegativeToUnsigned` set,
	// we will get `18446744073709551615` which is the biggest unsigned value.
	FlagAllowNegativeToUnsigned
	// FlagIgnoreZeroDateErr indicates to ignore the zero-date error.
	// See: https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_no_zero_date for details about the "zero-date" error.
	// If this flag is set, `FlagZeroDateAsWarning` will be ignored.
	//
	// TODO: `FlagIgnoreZeroDateErr` and `FlagZeroDateAsWarning` don't represent the comments right now, because the
	// errors related with `time` and `duration` are handled directly according to SQL mode in many places (expression,
	// ddl ...). These error handling will be refined in the future. Currently, the `FlagZeroDateAsWarning` is not used,
	// and the `FlagIgnoreZeroDateErr` is used to allow or disallow casting zero to date in `alter` statement. See #25728
	// This flag is the reverse of `NoZeroDate` in #30507. It's set to `true` for most context, and is only set to
	// `false` for `alter` (and `create`) statements.
	FlagIgnoreZeroDateErr
	// FlagIgnoreZeroInDateErr indicates to ignore the zero-in-date error.
	// See: https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_no_zero_in_date for details about the "zero-in-date" error.
	FlagIgnoreZeroInDateErr
	// FlagIgnoreInvalidDateErr indicates to ignore the invalid-date error.
	// See: https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_allow_invalid_dates for details about the "invalid-date" error.
	FlagIgnoreInvalidDateErr
	// FlagSkipASCIICheck indicates to skip the ASCII check when converting the value to an ASCII string.
	FlagSkipASCIICheck
	// FlagSkipUTF8Check indicates to skip the UTF8 check when converting the value to an UTF8MB3 string.
	FlagSkipUTF8Check
	// FlagSkipUTF8MB4Check indicates to skip the UTF8MB4 check when converting the value to an UTF8 string.
	FlagSkipUTF8MB4Check
	// FlagCastTimeToYearThroughConcat indicates to cast time to year through concatenation. For example, `00:19:59` will be converted to '1959'
	FlagCastTimeToYearThroughConcat
)
const StrictFlags Flags = 0

StrictFlags is a flags with a fields unset and has the most strict behavior.

func (Flags) AllowNegativeToUnsigned

func (f Flags) AllowNegativeToUnsigned() bool

AllowNegativeToUnsigned indicates whether the flag `FlagAllowNegativeToUnsigned` is set

func (Flags) CastTimeToYearThroughConcat

func (f Flags) CastTimeToYearThroughConcat() bool

CastTimeToYearThroughConcat whether `FlagCastTimeToYearThroughConcat` is set

func (Flags) IgnoreInvalidDateErr

func (f Flags) IgnoreInvalidDateErr() bool

IgnoreInvalidDateErr indicates whether the flag `FlagIgnoreInvalidDateErr` is set

func (Flags) IgnoreTruncateErr

func (f Flags) IgnoreTruncateErr() bool

IgnoreTruncateErr indicates whether the flag `FlagIgnoreTruncateErr` is set

func (Flags) IgnoreZeroDateErr

func (f Flags) IgnoreZeroDateErr() bool

IgnoreZeroDateErr indicates whether the flag `FlagIgnoreZeroDateErr` is set

func (Flags) IgnoreZeroInDate

func (f Flags) IgnoreZeroInDate() bool

IgnoreZeroInDate indicates whether the flag `FlagIgnoreZeroInData` is set

func (Flags) SkipASCIICheck

func (f Flags) SkipASCIICheck() bool

SkipASCIICheck indicates whether the flag `FlagSkipASCIICheck` is set

func (Flags) SkipUTF8Check

func (f Flags) SkipUTF8Check() bool

SkipUTF8Check indicates whether the flag `FlagSkipUTF8Check` is set

func (Flags) SkipUTF8MB4Check

func (f Flags) SkipUTF8MB4Check() bool

SkipUTF8MB4Check indicates whether the flag `FlagSkipUTF8MB4Check` is set

func (Flags) TruncateAsWarning

func (f Flags) TruncateAsWarning() bool

TruncateAsWarning indicates whether the flag `FlagTruncateAsWarning` is set

func (Flags) WithAllowNegativeToUnsigned

func (f Flags) WithAllowNegativeToUnsigned(clip bool) Flags

WithAllowNegativeToUnsigned returns a new flags with `FlagAllowNegativeToUnsigned` set/unset according to the clip parameter

func (Flags) WithCastTimeToYearThroughConcat

func (f Flags) WithCastTimeToYearThroughConcat(flag bool) Flags

WithCastTimeToYearThroughConcat returns a new flags with `FlagCastTimeToYearThroughConcat` set/unset according to the flag parameter

func (Flags) WithIgnoreInvalidDateErr

func (f Flags) WithIgnoreInvalidDateErr(ignore bool) Flags

WithIgnoreInvalidDateErr returns a new flags with `FlagIgnoreInvalidDateErr` set/unset according to the ignore parameter

func (Flags) WithIgnoreTruncateErr

func (f Flags) WithIgnoreTruncateErr(ignore bool) Flags

WithIgnoreTruncateErr returns a new flags with `FlagIgnoreTruncateErr` set/unset according to the skip parameter

func (Flags) WithIgnoreZeroDateErr

func (f Flags) WithIgnoreZeroDateErr(ignore bool) Flags

WithIgnoreZeroDateErr returns a new flags with `FlagIgnoreZeroDateErr` set/unset according to the ignore parameter

func (Flags) WithIgnoreZeroInDate

func (f Flags) WithIgnoreZeroInDate(ignore bool) Flags

WithIgnoreZeroInDate returns a new flags with `FlagIgnoreZeroInDateErr` set/unset according to the ignore parameter

func (Flags) WithSkipSACIICheck

func (f Flags) WithSkipSACIICheck(skip bool) Flags

WithSkipSACIICheck returns a new flags with `FlagSkipASCIICheck` set/unset according to the skip parameter

func (Flags) WithSkipUTF8Check

func (f Flags) WithSkipUTF8Check(skip bool) Flags

WithSkipUTF8Check returns a new flags with `FlagSkipUTF8Check` set/unset according to the skip parameter

func (Flags) WithSkipUTF8MB4Check

func (f Flags) WithSkipUTF8MB4Check(skip bool) Flags

WithSkipUTF8MB4Check returns a new flags with `FlagSkipUTF8MB4Check` set/unset according to the skip parameter

func (Flags) WithTruncateAsWarning

func (f Flags) WithTruncateAsWarning(warn bool) Flags

WithTruncateAsWarning returns a new flags with `FlagTruncateAsWarning` set/unset according to the skip parameter

type HexLiteral

type HexLiteral BinaryLiteral

HexLiteral is the hex literal type.

func NewHexLiteral

func NewHexLiteral(s string) (HexLiteral, error)

NewHexLiteral parses hexadecimal string as HexLiteral type.

func (HexLiteral) ToString

func (b HexLiteral) ToString() string

ToString implement ast.BinaryLiteral interface

type JSONModifyType

type JSONModifyType byte

JSONModifyType is for modify a JSON. There are three valid values: JSONModifyInsert, JSONModifyReplace and JSONModifySet.

const (
	// JSONModifyInsert is for insert a new element into a JSON.
	// If an old elemList exists, it would NOT replace it.
	JSONModifyInsert JSONModifyType = 0x01
	// JSONModifyReplace is for replace an old elemList from a JSON.
	// If no elemList exists, it would NOT insert it.
	JSONModifyReplace JSONModifyType = 0x02
	// JSONModifySet = JSONModifyInsert | JSONModifyReplace
	JSONModifySet JSONModifyType = 0x03
)

type JSONPathExpression

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

JSONPathExpression is for JSON path expression.

func ParseJSONPathExpr

func ParseJSONPathExpr(pathExpr string) (JSONPathExpression, error)

ParseJSONPathExpr parses a JSON path expression. Returns a JSONPathExpression object which can be used in JSON_EXTRACT, JSON_SET and so on.

func (JSONPathExpression) CouldMatchMultipleValues

func (pe JSONPathExpression) CouldMatchMultipleValues() bool

CouldMatchMultipleValues returns true if pe contains any asterisk or range selection.

func (JSONPathExpression) String

func (pe JSONPathExpression) String() string

type JSONPathExpressionCache

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

JSONPathExpressionCache is a cache for JSONPathExpression.

type JSONTypeCode

type JSONTypeCode = byte

JSONTypeCode indicates JSON type.

const (
	// JSONTypeCodeObject indicates the JSON is an object.
	JSONTypeCodeObject JSONTypeCode = 0x01
	// JSONTypeCodeArray indicates the JSON is an array.
	JSONTypeCodeArray JSONTypeCode = 0x03
	// JSONTypeCodeLiteral indicates the JSON is a literal.
	JSONTypeCodeLiteral JSONTypeCode = 0x04
	// JSONTypeCodeInt64 indicates the JSON is a signed integer.
	JSONTypeCodeInt64 JSONTypeCode = 0x09
	// JSONTypeCodeUint64 indicates the JSON is a unsigned integer.
	JSONTypeCodeUint64 JSONTypeCode = 0x0a
	// JSONTypeCodeFloat64 indicates the JSON is a double float number.
	JSONTypeCodeFloat64 JSONTypeCode = 0x0b
	// JSONTypeCodeString indicates the JSON is a string.
	JSONTypeCodeString JSONTypeCode = 0x0c
	// JSONTypeCodeOpaque indicates the JSON is a opaque
	JSONTypeCodeOpaque JSONTypeCode = 0x0d
	// JSONTypeCodeDate indicates the JSON is a opaque
	JSONTypeCodeDate JSONTypeCode = 0x0e
	// JSONTypeCodeDatetime indicates the JSON is a opaque
	JSONTypeCodeDatetime JSONTypeCode = 0x0f
	// JSONTypeCodeTimestamp indicates the JSON is a opaque
	JSONTypeCodeTimestamp JSONTypeCode = 0x10
	// JSONTypeCodeDuration indicates the JSON is a opaque
	JSONTypeCodeDuration JSONTypeCode = 0x11
)

type MyDecimal

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

MyDecimal represents a decimal value.

func ConvertDatumToDecimal

func ConvertDatumToDecimal(ctx Context, d Datum) (*MyDecimal, error)

ConvertDatumToDecimal converts datum to decimal.

func ConvertJSONToDecimal

func ConvertJSONToDecimal(ctx Context, j BinaryJSON) (*MyDecimal, error)

ConvertJSONToDecimal casts JSON into decimal.

func DecimalNeg

func DecimalNeg(from *MyDecimal) *MyDecimal

DecimalNeg reverses decimal's sign.

func NewDecFromFloatForTest

func NewDecFromFloatForTest(f float64) *MyDecimal

NewDecFromFloatForTest creates a MyDecimal from float, as it returns no error, it should only be used in test.

func NewDecFromInt

func NewDecFromInt(i int64) *MyDecimal

NewDecFromInt creates a MyDecimal from int.

func NewDecFromStringForTest

func NewDecFromStringForTest(s string) *MyDecimal

NewDecFromStringForTest creates a MyDecimal from string, as it returns no error, it should only be used in test.

func NewDecFromUint

func NewDecFromUint(i uint64) *MyDecimal

NewDecFromUint creates a MyDecimal from uint.

func NewMaxOrMinDec

func NewMaxOrMinDec(negative bool, prec, frac int) *MyDecimal

NewMaxOrMinDec returns the max or min value decimal for given precision and fraction.

func ProduceDecWithSpecifiedTp

func ProduceDecWithSpecifiedTp(ctx Context, dec *MyDecimal, tp *FieldType) (_ *MyDecimal, err error)

ProduceDecWithSpecifiedTp produces a new decimal according to `flen` and `decimal`.

func (*MyDecimal) Compare

func (d *MyDecimal) Compare(to *MyDecimal) int

Compare compares one decimal to another, returns -1/0/1.

func (*MyDecimal) FromBin

func (d *MyDecimal) FromBin(bin []byte, precision, frac int) (binSize int, err error)

FromBin Restores decimal from its binary fixed-length representation.

func (*MyDecimal) FromFloat64

func (d *MyDecimal) FromFloat64(f float64) error

FromFloat64 creates a decimal from float64 value.

func (*MyDecimal) FromInt

func (d *MyDecimal) FromInt(val int64) *MyDecimal

FromInt sets the decimal value from int64.

func (*MyDecimal) FromString

func (d *MyDecimal) FromString(str []byte) error

FromString parses decimal from string.

func (*MyDecimal) FromUint

func (d *MyDecimal) FromUint(val uint64) *MyDecimal

FromUint sets the decimal value from uint64.

func (*MyDecimal) GetDigitsFrac

func (d *MyDecimal) GetDigitsFrac() int8

GetDigitsFrac returns the digitsFrac.

func (*MyDecimal) GetDigitsInt

func (d *MyDecimal) GetDigitsInt() int8

GetDigitsInt returns the digitsInt.

func (*MyDecimal) IsNegative

func (d *MyDecimal) IsNegative() bool

IsNegative returns whether a decimal is negative.

func (*MyDecimal) IsZero

func (d *MyDecimal) IsZero() bool

IsZero checks whether it's a zero decimal.

func (*MyDecimal) MarshalJSON

func (d *MyDecimal) MarshalJSON() ([]byte, error)

MarshalJSON implements Marshaler.MarshalJSON interface.

func (*MyDecimal) PrecisionAndFrac

func (d *MyDecimal) PrecisionAndFrac() (precision, frac int)

PrecisionAndFrac returns the internal precision and frac number.

func (*MyDecimal) Round

func (d *MyDecimal) Round(to *MyDecimal, frac int, roundMode RoundMode) (err error)

Round rounds the decimal to "frac" digits.

   to			- result buffer. d == to is allowed
   frac			- to what position after fraction point to round. can be negative!
   roundMode		- round to nearest even or truncate
			ModeHalfUp rounds normally.
			ModeTruncate just truncates the decimal.

NOTES

frac can be negative !
one TRUNCATED error (line XXX below) isn't treated very logical :(

RETURN VALUE

nil/ErrTruncated/ErrOverflow

func (*MyDecimal) Shift

func (d *MyDecimal) Shift(shift int) error

Shift shifts decimal digits in given number (with rounding if it need), shift > 0 means shift to left shift, shift < 0 means right shift. In fact it is multiplying on 10^shift.

RETURN

eDecOK          OK
eDecOverflow    operation lead to overflow, number is untoched
eDecTruncated   number was rounded to fit into buffer

func (*MyDecimal) String

func (d *MyDecimal) String() string

String returns the decimal string representation rounded to resultFrac.

func (*MyDecimal) ToBin

func (d *MyDecimal) ToBin(precision, frac int) ([]byte, error)

ToBin converts decimal to its binary fixed-length representation two representations of the same length can be compared with memcmp with the correct -1/0/+1 result

  PARAMS
		precision/frac - if precision is 0, internal value of the decimal will be used,
		then the encoded value is not memory comparable.

  NOTE
    the buffer is assumed to be of the size DecimalBinSize(precision, frac)

  RETURN VALUE
  	bin     - binary value
    errCode - eDecOK/eDecTruncate/eDecOverflow

  DESCRIPTION
    for storage decimal numbers are converted to the "binary" format.

    This format has the following properties:
      1. length of the binary representation depends on the {precision, frac}
      as provided by the caller and NOT on the digitsInt/digitsFrac of the decimal to
      convert.
      2. binary representations of the same {precision, frac} can be compared
      with memcmp - with the same result as DecimalCompare() of the original
      decimals (not taking into account possible precision loss during
      conversion).

    This binary format is as follows:
      1. First the number is converted to have a requested precision and frac.
      2. Every full digitsPerWord digits of digitsInt part are stored in 4 bytes
         as is
      3. The first digitsInt % digitesPerWord digits are stored in the reduced
         number of bytes (enough bytes to store this number of digits -
         see dig2bytes)
      4. same for frac - full word are stored as is,
         the last frac % digitsPerWord digits - in the reduced number of bytes.
      5. If the number is negative - every byte is inversed.
      5. The very first bit of the resulting byte array is inverted (because
         memcmp compares unsigned bytes, see property 2 above)

    Example:

      1234567890.1234

    internally is represented as 3 words

      1 234567890 123400000

    (assuming we want a binary representation with precision=14, frac=4)
    in hex it's

      00-00-00-01  0D-FB-38-D2  07-5A-EF-40

    now, middle word is full - it stores 9 decimal digits. It goes
    into binary representation as is:

      ...........  0D-FB-38-D2 ............

    First word has only one decimal digit. We can store one digit in
    one byte, no need to waste four:

                01 0D-FB-38-D2 ............

    now, last word. It's 123400000. We can store 1234 in two bytes:

                01 0D-FB-38-D2 04-D2

    So, we've packed 12 bytes number in 7 bytes.
    And now we invert the highest bit to get the final result:

                81 0D FB 38 D2 04 D2

    And for -1234567890.1234 it would be

                7E F2 04 C7 2D FB 2D

func (*MyDecimal) ToFloat64

func (d *MyDecimal) ToFloat64() (f float64, err error)

ToFloat64 converts decimal to float64 value.

func (*MyDecimal) ToHashKey

func (d *MyDecimal) ToHashKey() ([]byte, error)

ToHashKey removes the leading and trailing zeros and generates a hash key. Two Decimals dec0 and dec1 with different fraction will generate the same hash keys if dec0.Compare(dec1) == 0.

func (*MyDecimal) ToInt

func (d *MyDecimal) ToInt() (int64, error)

ToInt returns int part of the decimal, returns the result and errcode.

func (*MyDecimal) ToString

func (d *MyDecimal) ToString() (str []byte)

ToString converts decimal to its printable string representation without rounding.

RETURN VALUE

    str       - result string
    errCode   - eDecOK/eDecTruncate/eDecOverflow

func (*MyDecimal) ToUint

func (d *MyDecimal) ToUint() (uint64, error)

ToUint returns int part of the decimal, returns the result and errcode.

func (*MyDecimal) UnmarshalJSON

func (d *MyDecimal) UnmarshalJSON(data []byte) error

UnmarshalJSON implements Unmarshaler.UnmarshalJSON interface.

func (*MyDecimal) WriteBin

func (d *MyDecimal) WriteBin(precision, frac int, buf []byte) ([]byte, error)

WriteBin encode and write the binary encoded to target buffer

type NameSlice

type NameSlice []*FieldName

NameSlice is the slice of the *fieldName

func (NameSlice) FindAstColName

func (s NameSlice) FindAstColName(name *ast.ColumnName) bool

FindAstColName checks whether the given ast.ColumnName is appeared in this slice.

func (NameSlice) Shallow

func (s NameSlice) Shallow() NameSlice

Shallow is a shallow copy, only making a new slice.

type Opaque

type Opaque struct {
	// TypeCode is the same with database type code
	TypeCode byte
	// Buf is the underlying bytes of the data
	Buf []byte
}

Opaque represents a raw binary type

type RoundMode

type RoundMode int32

RoundMode is the type for round mode.

const (

	// Round up to the next integer if positive or down to the next integer if negative.
	ModeHalfUp RoundMode = 5
	// Truncate just truncates the decimal.
	ModeTruncate RoundMode = 10
	// Ceiling is not supported now.
	ModeCeiling RoundMode = 0
)

constant values.

type RoundingType

type RoundingType uint8

RoundingType is used to indicate the rounding type for reversing evaluation.

const (
	// Ceiling means rounding up.
	Ceiling RoundingType = iota
	// Floor means rounding down.
	Floor
)

type Set

type Set struct {
	Name  string
	Value uint64
}

Set is for MySQL Set type.

func ParseSet

func ParseSet(elems []string, name string, collation string) (Set, error)

ParseSet creates a Set with name or value.

func ParseSetName

func ParseSetName(elems []string, name string, collation string) (Set, error)

ParseSetName creates a Set with name.

func ParseSetValue

func ParseSetValue(elems []string, number uint64) (Set, error)

ParseSetValue creates a Set with special number.

func (Set) Copy

func (e Set) Copy() Set

Copy deep copy a Set.

func (Set) String

func (e Set) String() string

String implements fmt.Stringer interface.

func (Set) ToNumber

func (e Set) ToNumber() float64

ToNumber changes Set to float64 for numeric operation.

type Time

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

Time is the struct for handling datetime, timestamp and date.

func CurrentTime

func CurrentTime(tp uint8) Time

CurrentTime returns current time with type tp.

func NewTime

func NewTime(coreTime CoreTime, tp uint8, fsp int) Time

NewTime constructs time from core time, type and fsp.

func ParseDate

func ParseDate(ctx Context, str string) (Time, error)

ParseDate is a helper function wrapping ParseTime with date type.

func ParseDateFromNum

func ParseDateFromNum(ctx Context, num int64) (Time, error)

ParseDateFromNum is a helper function wrapping ParseTimeFromNum with date type.

func ParseDatetime

func ParseDatetime(ctx Context, str string) (Time, error)

ParseDatetime is a helper function wrapping ParseTime with datetime type and default fsp.

func ParseDatetimeFromNum

func ParseDatetimeFromNum(ctx Context, num int64) (Time, error)

ParseDatetimeFromNum is a helper function wrapping ParseTimeFromNum with datetime type and default fsp.

func ParseTime

func ParseTime(ctx Context, str string, tp byte, fsp int) (Time, error)

ParseTime parses a formatted string with type tp and specific fsp. Type is TypeDatetime, TypeTimestamp and TypeDate. Fsp is in range [0, 6]. MySQL supports many valid datetime format, but still has some limitation. If delimiter exists, the date part and time part is separated by a space or T, other punctuation character can be used as the delimiter between date parts or time parts. If no delimiter, the format must be YYYYMMDDHHMMSS or YYMMDDHHMMSS If we have fractional seconds part, we must use decimal points as the delimiter. The valid datetime range is from '1000-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999'. The valid timestamp range is from '1970-01-01 00:00:01.000000' to '2038-01-19 03:14:07.999999'. The valid date range is from '1000-01-01' to '9999-12-31' explicitTz is used to handle a data race of timeZone, refer to https://github.com/pingcap/tidb/issues/40710. It only works for timestamp now, be careful to use it!

func ParseTimeFromDecimal

func ParseTimeFromDecimal(ctx Context, dec *MyDecimal) (t Time, err error)

ParseTimeFromDecimal parses mysql time value from decimal. It is used in scenarios that distinguish date and datetime, e.g., date_add/sub() with first argument being decimal. For example, 20010203 parses to date (no HMS) and 20010203040506 parses to datetime (with HMS).

func ParseTimeFromFloat64

func ParseTimeFromFloat64(ctx Context, f float64) (Time, error)

ParseTimeFromFloat64 parses mysql time value from float64. It is used in scenarios that distinguish date and datetime, e.g., date_add/sub() with first argument being real. For example, 20010203 parses to date (no HMS) and 20010203040506 parses to datetime (with HMS).

func ParseTimeFromFloatString

func ParseTimeFromFloatString(ctx Context, str string, tp byte, fsp int) (Time, error)

ParseTimeFromFloatString is similar to ParseTime, except that it's used to parse a float converted string.

func ParseTimeFromInt64

func ParseTimeFromInt64(ctx Context, num int64) (Time, error)

ParseTimeFromInt64 parses mysql time value from int64.

func ParseTimeFromNum

func ParseTimeFromNum(ctx Context, num int64, tp byte, fsp int) (Time, error)

ParseTimeFromNum parses a formatted int64, returns the value which type is tp.

func ParseTimeFromYear

func ParseTimeFromYear(year int64) (Time, error)

ParseTimeFromYear parse a `YYYY` formed year to corresponded Datetime type. Note: the invoker must promise the `year` is in the range [MinYear, MaxYear].

func ParseTimestamp

func ParseTimestamp(ctx Context, str string) (Time, error)

ParseTimestamp is a helper function wrapping ParseTime with timestamp type and default fsp.

func ParseTimestampFromNum

func ParseTimestampFromNum(ctx Context, num int64) (Time, error)

ParseTimestampFromNum is a helper function wrapping ParseTimeFromNum with timestamp type and default fsp.

func StrToDateTime

func StrToDateTime(ctx Context, str string, fsp int) (Time, error)

StrToDateTime converts str to MySQL DateTime.

func TimeFromDays

func TimeFromDays(num int64) Time

TimeFromDays Converts a day number to a date.

func (*Time) Add

func (t *Time) Add(ctx Context, d Duration) (Time, error)

Add adds d to t, returns the result time value.

func (Time) Check

func (t Time) Check(ctx Context) error

Check function checks whether t matches valid Time format. If allowZeroInDate is false, it returns ErrZeroDate when month or day is zero. FIXME: See https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_in_date

func (Time) Clock

func (t Time) Clock() (hour int, minute int, second int)

Clock returns the hour, minute, and second within the day specified by t.

func (Time) Compare

func (t Time) Compare(o Time) int

Compare returns an integer comparing the time instant t to o. If t is after o, returns 1, equal o, returns 0, before o, returns -1.

func (Time) CompareString

func (t Time) CompareString(ctx Context, str string) (int, error)

CompareString is like Compare, but parses string to Time then compares.

func (Time) Convert

func (t Time) Convert(ctx Context, tp uint8) (Time, error)

Convert converts t with type tp.

func (*Time) ConvertTimeZone

func (t *Time) ConvertTimeZone(from, to *gotime.Location) error

ConvertTimeZone converts the time value from one timezone to another. The input time should be a valid timestamp.

func (Time) ConvertToDuration

func (t Time) ConvertToDuration() (Duration, error)

ConvertToDuration converts mysql datetime, timestamp and date to mysql time type. e.g, 2012-12-12T10:10:10 -> 10:10:10 2012-12-12 -> 0

func (Time) CoreTime

func (t Time) CoreTime() CoreTime

CoreTime returns core time.

func (Time) DateFormat

func (t Time) DateFormat(layout string) (string, error)

DateFormat returns a textual representation of the time value formatted according to layout. See http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format

func (Time) FillNumber

func (t Time) FillNumber(dec *MyDecimal)

FillNumber is the same as ToNumber, but reuses input decimal instead of allocating one.

func (*Time) FromPackedUint

func (t *Time) FromPackedUint(packed uint64) error

FromPackedUint decodes Time from a packed uint64 value.

func (Time) Fsp

func (t Time) Fsp() int

Fsp returns fsp value.

func (Time) InvalidZero

func (t Time) InvalidZero() bool

InvalidZero returns a boolean indicating whether the month or day is zero. Several functions are strict when passed a DATE() function value as their argument and reject incomplete dates with a day part of zero: CONVERT_TZ(), DATE_ADD(), DATE_SUB(), DAYOFYEAR(), TIMESTAMPDIFF(), TO_DAYS(), TO_SECONDS(), WEEK(), WEEKDAY(), WEEKOFYEAR(), YEARWEEK(). Mysql Doc: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

func (Time) IsZero

func (t Time) IsZero() bool

IsZero returns a boolean indicating whether the time is equal to ZeroCoreTime.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements Marshaler.MarshalJSON interface.

func (Time) RoundFrac

func (t Time) RoundFrac(ctx Context, fsp int) (Time, error)

RoundFrac rounds the fraction part of a time-type value according to `fsp`.

func (*Time) SetCoreTime

func (t *Time) SetCoreTime(ct CoreTime)

SetCoreTime updates core time.

func (*Time) SetFsp

func (t *Time) SetFsp(fsp int)

SetFsp updates the fsp in Time.

func (*Time) SetType

func (t *Time) SetType(tp uint8)

SetType updates the type in Time. Only DateTime/Date/Timestamp is valid.

func (*Time) StrToDate

func (t *Time) StrToDate(typeCtx Context, date, format string) bool

StrToDate converts date string according to format. See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format

func (Time) String

func (t Time) String() string

func (*Time) Sub

func (t *Time) Sub(ctx Context, t1 *Time) Duration

Sub subtracts t1 from t, returns a duration value. Note that sub should not be done on different time types.

func (Time) ToNumber

func (t Time) ToNumber() *MyDecimal

ToNumber returns a formatted number. e.g, 2012-12-12 -> 20121212 2012-12-12T10:10:10 -> 20121212101010 2012-12-12T10:10:10.123456 -> 20121212101010.123456

func (Time) ToPackedUint

func (t Time) ToPackedUint() (uint64, error)

ToPackedUint encodes Time to a packed uint64 value.

 1 bit  0
17 bits year*13+month   (year 0-9999, month 0-12)
 5 bits day             (0-31)
 5 bits hour            (0-23)
 6 bits minute          (0-59)
 6 bits second          (0-59)
24 bits microseconds    (0-999999)

Total: 64 bits = 8 bytes

0YYYYYYY.YYYYYYYY.YYdddddh.hhhhmmmm.mmssssss.ffffffff.ffffffff.ffffffff

func (Time) Type

func (t Time) Type() uint8

Type returns type value.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements Unmarshaler.UnmarshalJSON interface.

type VectorFloat32

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

VectorFloat32 represents a vector of float32.

Memory Format: 4 byte - Length 4 byte * N - Data in Float32

Normally, the data layout in storage (i.e. after serialization) is identical to the memory layout. However, in BigEndian machines, we have BigEndian in memory and always have LittleEndian in storage or during data exchange.

func CreateVectorFloat32

func CreateVectorFloat32(vector []float32) (VectorFloat32, error)

CreateVectorFloat32 creates a VectorFloat32. Returns error if there are invalid values like NaN and Inf.

func InitVectorFloat32

func InitVectorFloat32(dims int) VectorFloat32

InitVectorFloat32 initializes a vector with the given dimension. The values are initialized to zero.

func MustCreateVectorFloat32

func MustCreateVectorFloat32(v []float32) VectorFloat32

MustCreateVectorFloat32 creates a VectorFloat32. Panics if there are invalid values like NaN and Inf.

func ParseVectorFloat32

func ParseVectorFloat32(s string) (VectorFloat32, error)

ParseVectorFloat32 parses a string into a vector.

func ZeroCopyDeserializeVectorFloat32

func ZeroCopyDeserializeVectorFloat32(b []byte) (VectorFloat32, []byte, error)

ZeroCopyDeserializeVectorFloat32 deserializes the byte slice into a vector, without memory copy. Note: b must not be mutated, because this function does zero copy.

func (VectorFloat32) Add

Add adds two vectors. The vectors must have the same dimension.

func (VectorFloat32) CheckDimsFitColumn

func (v VectorFloat32) CheckDimsFitColumn(expectedFlen int) error

CheckDimsFitColumn checks if the vector has the expected dimension, which is defined by the column type or cast type.

func (VectorFloat32) Clone

func (v VectorFloat32) Clone() VectorFloat32

Clone returns a deep copy of the vector.

func (VectorFloat32) Compare

func (a VectorFloat32) Compare(b VectorFloat32) int

Compare returns an integer comparing two vectors. The result will be 0 if a==b, -1 if a < b, and +1 if a > b.

func (VectorFloat32) CosineDistance

func (a VectorFloat32) CosineDistance(b VectorFloat32) (float64, error)

CosineDistance returns the cosine distance between two vectors.

func (VectorFloat32) Elements

func (v VectorFloat32) Elements() []float32

Elements returns a mutable typed slice of the elements.

func (VectorFloat32) EstimatedMemUsage

func (v VectorFloat32) EstimatedMemUsage() int

EstimatedMemUsage returns the estimated memory usage.

func (VectorFloat32) InnerProduct

func (a VectorFloat32) InnerProduct(b VectorFloat32) (float64, error)

InnerProduct returns the inner product of two vectors.

func (VectorFloat32) IsZeroValue

func (v VectorFloat32) IsZeroValue() bool

IsZeroValue returns true if the vector is a zero value (which length is zero).

func (VectorFloat32) L1Distance

func (a VectorFloat32) L1Distance(b VectorFloat32) (float64, error)

L1Distance returns the L1 distance between two vectors.

func (VectorFloat32) L2Distance

func (a VectorFloat32) L2Distance(b VectorFloat32) (float64, error)

L2Distance returns the L2 distance between two vectors.

func (VectorFloat32) L2Norm

func (a VectorFloat32) L2Norm() float64

L2Norm returns the L2 norm of the vector.

func (VectorFloat32) L2SquaredDistance

func (a VectorFloat32) L2SquaredDistance(b VectorFloat32) (float64, error)

L2SquaredDistance returns the squared L2 distance between two vectors. This saves a sqrt calculation.

func (VectorFloat32) Len

func (v VectorFloat32) Len() int

Len returns the length (dimension) of the vector.

func (VectorFloat32) Mul

Mul multiplies two vectors. The vectors must have the same dimension.

func (VectorFloat32) NegativeInnerProduct

func (a VectorFloat32) NegativeInnerProduct(b VectorFloat32) (float64, error)

NegativeInnerProduct returns the negative inner product of two vectors.

func (VectorFloat32) SerializeTo

func (v VectorFloat32) SerializeTo(b []byte) []byte

SerializeTo serializes the vector into the byte slice.

func (VectorFloat32) SerializedSize

func (v VectorFloat32) SerializedSize() int

SerializedSize returns the size of the serialized data.

func (VectorFloat32) String

func (v VectorFloat32) String() string

String returns a string representation of the vector, which can be parsed later.

func (VectorFloat32) Sub

Sub subtracts two vectors. The vectors must have the same dimension.

func (VectorFloat32) TruncatedString

func (v VectorFloat32) TruncatedString() string

TruncatedString prints the vector in a truncated form, which is useful for outputting in logs or EXPLAIN statements.

func (VectorFloat32) ZeroCopySerialize

func (v VectorFloat32) ZeroCopySerialize() []byte

ZeroCopySerialize serializes the vector into a new byte slice, without memory copy.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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