types

package
v0.0.0-...-cb5f647 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: Apache-2.0 Imports: 27 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 (
	// 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 MyDecimalStructSize = 40

MyDecimalStructSize is the struct size of MyDecimal.

View Source
const (
	UnspecifiedLength = -1
)

UnspecifiedLength is unspecified length.

Variables

View Source
var (
	// 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)
	// ErrBadNumber is return when parsing an invalid binary decimal number.
	ErrBadNumber = dbterror.ClassTypes.NewStd(mysql.ErrBadNumber)
	// ErrDatetimeFunctionOverflow is returned when the calculation in datetime function cause overflow.
	ErrDatetimeFunctionOverflow = dbterror.ClassTypes.NewStd(mysql.ErrDatetimeFunctionOverflow)
	// ErrTruncatedWrongVal is returned when data has been truncated during conversion.
	ErrTruncatedWrongVal = dbterror.ClassTypes.NewStd(mysql.ErrTruncatedWrongValue)
	// ErrWrongValue is returned when the input value is in wrong format.
	ErrWrongValue = dbterror.ClassTypes.NewStdErr(mysql.ErrTruncatedWrongValue, mysql.MySQLErrName[mysql.ErrWrongValue])
)
View Source
var (
	// 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])
)
View Source
var ZeroCoreTime = CoreTime(0)

ZeroCoreTime is the zero value for TimeInternal type.

View Source
var (
	// ZeroCoreTime is the zero value for Time type.
	ZeroTime = Time{}
)

Zero values for different types.

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 CheckFsp

func CheckFsp(fsp int) (int, error)

CheckFsp checks whether fsp is in valid range.

func CheckVectorDimValid

func CheckVectorDimValid(dim int) error

CheckVectorDimValid checks if the vector's dimension is valid.

func DateDiff

func DateDiff(startTime, endTime CoreTime) int

DateDiff calculates number of days between two days.

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 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 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 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 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 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.

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 (BinaryJSON) ArrayGetElem

func (bj BinaryJSON) ArrayGetElem(idx int) BinaryJSON

ArrayGetElem gets the element of the index `idx`.

func (BinaryJSON) Copy

func (bj BinaryJSON) Copy() BinaryJSON

Copy makes a copy of the BinaryJSON

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) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface.

func (BinaryJSON) String

func (bj BinaryJSON) String() string

String implements fmt.Stringer interface.

func (*BinaryJSON) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface.

type BinaryLiteral

type BinaryLiteral []byte

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

func (BinaryLiteral) ToString

func (b BinaryLiteral) ToString() string

ToString returns the string representation for the literal.

type CoreTime

type CoreTime uint64

CoreTime is the internal struct type for Time.

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 (*Datum) GetBinaryLiteral

func (d *Datum) GetBinaryLiteral() BinaryLiteral

GetBinaryLiteral gets Bit value

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) 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) GetString

func (d *Datum) GetString() string

GetString gets string value.

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) Kind

func (d *Datum) Kind() byte

Kind gets the kind of the datum.

func (*Datum) SetBytes

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

SetBytes sets bytes value to datum.

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) SetLength

func (d *Datum) SetLength(l int)

SetLength sets the length of the datum.

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) SetMysqlJSON

func (d *Datum) SetMysqlJSON(b BinaryJSON)

SetMysqlJSON sets json.BinaryJSON value

func (*Datum) SetUint64

func (d *Datum) SetUint64(i uint64)

SetUint64 sets uint64 value.

func (*Datum) SetVectorFloat32

func (d *Datum) SetVectorFloat32(vec VectorFloat32)

SetVectorFloat32 sets VectorFloat32 value

func (*Datum) ToString

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

ToString gets the string representation of the datum.

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 (Duration) Hour

func (d Duration) Hour() int

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

type Enum

type Enum struct {
	Name  string
	Value uint64
}

Enum is for MySQL enum type.

func (Enum) String

func (e Enum) String() string

String implements fmt.Stringer 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 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 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 (*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 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 Set

type Set struct {
	Name  string
	Value uint64
}

Set is for MySQL Set type.

func (Set) String

func (e Set) String() string

String implements fmt.Stringer interface.

type Time

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

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

func NewTime

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

NewTime constructs time from core time, type and fsp.

func (Time) CoreTime

func (t Time) CoreTime() CoreTime

CoreTime returns core time.

func (*Time) SetFsp

func (t *Time) SetFsp(fsp int)

SetFsp updates the fsp in Time.

func (Time) Type

func (t Time) Type() uint8

Type returns type value.

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) 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) 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) IsZeroValue

func (v VectorFloat32) IsZeroValue() bool

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

func (VectorFloat32) Len

func (v VectorFloat32) Len() int

Len returns the length (dimension) of the vector.

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) 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.

Jump to

Keyboard shortcuts

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