types

package
v0.0.0-...-40faf7d Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2016 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MinBitWidth = 1
	MaxBitWidth = 64
	// UnspecifiedBitWidth is the unspecified with if you want to calculate bit width dynamically.
	UnspecifiedBitWidth = -1
)

Min and Max bit width.

View Source
const (
	KindNull  byte = 0
	KindInt64 byte = iota + 1
	KindUint64
	KindFloat32
	KindFloat64
	KindString
	KindBytes
	KindMysqlBit
	KindMysqlDecimal
	KindMysqlDuration
	KindMysqlEnum
	KindMysqlHex
	KindMysqlSet
	KindMysqlTime
	KindRow
	KindInterface
	KindMinNotNull
	KindMaxValue
)

Kind constants.

View Source
const (
	// UnspecifiedFsp is the unspecified fractional seconds part.
	UnspecifiedFsp int = -1
	// MaxFsp is the maximum digit of fractional seconds part.
	MaxFsp int = 6
	// MinFsp is the minimum digit of fractional seconds part.
	MinFsp int = 0
	// DefaultFsp is the default digit of fractional seconds part.
	// MySQL use 0 as the default Fsp.
	DefaultFsp int = 0
)
View Source
const (
	MaxFraction = 30
	DivFracIncr = 4
)

constant values.

View Source
const (
	DateFormat = "2006-01-02"
	TimeFormat = "2006-01-02 15:04:05"
	// TimeFSPFormat is time format with fractional seconds precision.
	TimeFSPFormat = "2006-01-02 15:04:05.000000"
)

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

	// MinTime is the minimum for mysql time type.
	MinTime = -time.Duration(838*3600+59*60+59) * time.Second
	// MaxTime is the maximum for mysql time type.
	MaxTime = time.Duration(838*3600+59*60+59) * time.Second
)
View Source
const (
	UnspecifiedLength int = -1
)

UnspecifiedLength is unspecified length.

Variables

View Source
var (
	// ErrDataTooLong is returned when converts a string value that is longer than field type length.
	ErrDataTooLong = terror.ClassTypes.New(codeDataTooLong, "Data Too Long")
	// ErrTruncated is returned when data has been truncated during convertion.
	ErrTruncated = terror.ClassTypes.New(codeTruncated, "Data Truncated")
	// ErrOverflow is returned when data is out of range for a field type.
	ErrOverflow = terror.ClassTypes.New(codeOverflow, "Data Out Of Range")
	// ErrDivByZero is return when do division by 0.
	ErrDivByZero = terror.ClassTypes.New(codeDivByZero, "Division by 0")
	// ErrBadNumber is return when parsing an invalid binary decimal number.
	ErrBadNumber = terror.ClassTypes.New(codeBadNumber, "Bad Number")
)
View Source
var (
	ErrInvalidTimeFormat = errors.New("invalid time format")
	ErrInvalidYearFormat = errors.New("invalid year format")
	ErrInvalidYear       = errors.New("invalid year")
)

Portable analogs of some common call errors.

View Source
var (
	// ZeroDuration is the zero value for Duration type.
	ZeroDuration = Duration{Duration: time.Duration(0), Fsp: DefaultFsp}

	// ZeroTime is the zero value for time.Time type.
	ZeroTime = time.Date(0, 0, 0, 0, 0, 0, 0, time.Local)

	// ZeroDatetime is the zero value for datetime Time.
	ZeroDatetime = Time{
		Time: ZeroTime,
		Type: mysql.TypeDatetime,
		Fsp:  DefaultFsp,
	}

	// ZeroTimestamp is the zero value for timestamp Time.
	ZeroTimestamp = Time{
		Time: ZeroTime,
		Type: mysql.TypeTimestamp,
		Fsp:  DefaultFsp,
	}

	// ZeroDate is the zero value for date Time.
	ZeroDate = Time{
		Time: ZeroTime,
		Type: mysql.TypeDate,
		Fsp:  DefaultFsp,
	}
)

Zero values for different types.

View Source
var (
	// MinDatetime is the minimum for mysql datetime type.
	MinDatetime = time.Date(1000, 1, 1, 0, 0, 0, 0, time.Local)
	// MaxDatetime is the maximum for mysql datetime type.
	MaxDatetime = time.Date(9999, 12, 31, 23, 59, 59, 999999, time.Local)

	// MinTimestamp is the minimum for mysql timestamp type.
	MinTimestamp = time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC)
	// MaxTimestamp is the maximum for mysql timestamp type.
	MaxTimestamp = time.Date(2038, 1, 19, 3, 14, 7, 999999, time.UTC)

	// 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 ErrArithOverflow = errors.New("operation overflow")

ErrArithOverflow is the error for arthimetic operation overflow.

View Source
var (
	// ErrValueTruncated is used when a value has been truncated during conversion.
	ErrValueTruncated = errors.New("value has been truncated")
)

Functions

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) (int64, error)

AdjustYear is used for adjusting year and checking its validation.

func Compare

func Compare(a, b interface{}) (int, error)

Compare returns an integer comparing the interface a with b. a > b -> 1 a = b -> 0 a < b -> -1

func CompareFloat64

func CompareFloat64(x, y float64) int

CompareFloat64 returns an integer comparing the float64 x to y.

func CompareInt64

func CompareInt64(x, y int64) int

CompareInt64 returns an integer comparing the int64 x to y.

func CompareString

func CompareString(x, y string) int

CompareString returns an integer comparing the string x to y.

func CompareUint64

func CompareUint64(x, y uint64) int

CompareUint64 returns an integer comparing the uint64 x to y.

func Convert

func Convert(val interface{}, target *FieldType) (v interface{}, err error)

Convert converts the val with type tp.

func DatumsToInterfaces

func DatumsToInterfaces(datums []Datum) []interface{}

DatumsToInterfaces converts a datum slice to interface slice.

func DecimalAdd

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

DecimalAdd adds two decimals, sets the result to 'to'.

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 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) (string, string)

DefaultCharsetForType returns the default charset/collation for mysql type.

func DefaultTypeForValue

func DefaultTypeForValue(value interface{}, tp *FieldType)

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 EqualDatums

func EqualDatums(a []Datum, b []Datum) (bool, error)

EqualDatums compare if a and b contains the same datum values.

func ExtractTimeNum

func ExtractTimeNum(unit string, t Time) (int64, error)

ExtractTimeNum extracts time value number from time unit and format.

func ExtractTimeValue

func ExtractTimeValue(unit string, format string) (int64, int64, int64, time.Duration, error)

ExtractTimeValue extracts time value from time unit and format.

func InvOp2

func InvOp2(x, y interface{}, o opcode.Op) (interface{}, error)

InvOp2 returns an invalid operation error.

func IsClockUnit

func IsClockUnit(unit string) bool

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

func IsDateFormat

func IsDateFormat(format string) bool

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

func IsTypeBlob

func IsTypeBlob(tp byte) bool

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

func IsTypeChar

func IsTypeChar(tp byte) bool

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

func MergeFieldType

func MergeFieldType(a byte, b byte) byte

MergeFieldType merges two MySQL type to a new type. This is used in hybrid field type expression. For example "select case c when 1 then 2 when 2 then 'tidb' from t;" The result field type of the case expression is the merged type of the two when clause. See https://github.com/mysql/mysql-server/blob/5.7/sql/field.cc#L1042

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 ParseHexStr

func ParseHexStr(s string) (string, error)

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

func ParseYear

func ParseYear(str string) (int16, error)

ParseYear parses a formatted string and returns a year number.

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 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 half away from zero". e.g, 1.5 -> 2, -1.5 -> -2.

func SortDatums

func SortDatums(datums []Datum) error

SortDatums sorts a slice of datum.

func StrToFloat

func StrToFloat(str string) (float64, error)

StrToFloat converts a string to a float64 in best effort.

func StrToInt

func StrToInt(str string) (int64, error)

StrToInt converts a string to an integer in best effort. TODO: handle overflow and add unittest.

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 ToString

func ToString(value interface{}) (string, error)

ToString converts an interface to a string.

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 TypeStr

func TypeStr(tp byte) (r string)

TypeStr converts tp to a string.

func TypeToStr

func TypeToStr(tp byte, cs string) (r string)

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

Types

type Bit

type Bit struct {
	// Value holds the value for bit type.
	Value uint64

	// Width is the display with for bit value.
	// e.g, with is 8, 0 is for 0b00000000.
	Width int
}

Bit is for mysql bit type.

func ParseBit

func ParseBit(s string, width int) (Bit, error)

ParseBit parses bit string. The string format can be b'val', B'val' or 0bval, val must be 0 or 1. Width is the display width for bit representation. -1 means calculating width dynamically, using following algorithm: (len("011101") + 7) & ^7, e.g, if bit string is 0b01, the above will return 8 for its bit width.

func (Bit) String

func (b Bit) String() string

String implements fmt.Stringer interface.

func (Bit) ToNumber

func (b Bit) ToNumber() float64

ToNumber changes bit type to float64 for numeric operation. MySQL treats bit as double type.

func (Bit) ToString

func (b Bit) ToString() string

ToString returns the binary string for bit type.

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 CalculateSum

func CalculateSum(sum Datum, v Datum) (Datum, error)

CalculateSum adds v to sum.

func CoerceArithmetic

func CoerceArithmetic(a Datum) (d Datum, err error)

CoerceArithmetic converts datum to appropriate datum for arithmetic computing.

func CoerceDatum

func CoerceDatum(a, b Datum) (x, y Datum, err error)

CoerceDatum changes type. If a or b is Float, changes the both to Float. Else if a or b is Decimal, changes the both to Decimal. Else if a or b is Uint and op is not div, mod, or intDiv changes the both to Uint.

func ComputeBitAnd

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

ComputeBitAnd computes the result of a & b.

func ComputeBitNeg

func ComputeBitNeg(a Datum) (d Datum, err error)

ComputeBitNeg computes the result of ~a.

func ComputeBitOr

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

ComputeBitOr computes the result of a | b.

func ComputeBitXor

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

ComputeBitXor computes the result of a ^ b.

func ComputeDiv

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

ComputeDiv computes the result of a/b.

func ComputeIntDiv

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

ComputeIntDiv computes the result of a / b, both a and b are integer.

func ComputeLeftShift

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

ComputeLeftShift computes the result of a >> b.

func ComputeMinus

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

ComputeMinus computes the result of a-b.

func ComputeMod

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

ComputeMod computes the result of a mod b.

func ComputeMul

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

ComputeMul computes the result of a*b.

func ComputePlus

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

ComputePlus computes the result of a+b.

func ComputeRightShift

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

ComputeRightShift computes the result of a << b.

func MakeDatums

func MakeDatums(args ...interface{}) []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 NewBytesDatum

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

NewBytesDatum creates a new Datum from a byte slice.

func NewDatum

func NewDatum(in interface{}) (d Datum)

NewDatum creates a new Datum from an interface{}.

func NewDecimalDatum

func NewDecimalDatum(dec *MyDecimal) (d Datum)

NewDecimalDatum creates a new Datum form 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 NewStringDatum

func NewStringDatum(s string) (d Datum)

NewStringDatum creates a new Datum from a string.

func NewUintDatum

func NewUintDatum(i uint64) (d Datum)

NewUintDatum creates a new Datum from an uint64 value.

func (*Datum) Cast

func (d *Datum) Cast(target *FieldType) (ad Datum, err error)

Cast casts datum to certain types.

func (*Datum) Collation

func (d *Datum) Collation() byte

Collation gets the collation of the datum.

func (*Datum) CompareDatum

func (d *Datum) CompareDatum(ad Datum) (int, error)

CompareDatum compares datum to another datum. TODO: return error properly.

func (*Datum) ConvertTo

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

ConvertTo converts a datum to the target field type.

func (*Datum) Frac

func (d *Datum) Frac() int

Frac gets the frac of the datum.

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() interface{}

GetInterface gets interface value.

func (*Datum) GetMysqlBit

func (d *Datum) GetMysqlBit() Bit

GetMysqlBit gets Bit 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) GetMysqlHex

func (d *Datum) GetMysqlHex() Hex

GetMysqlHex gets Hex 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) GetRow

func (d *Datum) GetRow() []Datum

GetRow gets row 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() interface{}

GetValue gets the value of the datum of any kind.

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

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

SetBytes sets bytes value to datum.

func (*Datum) SetBytesAsString

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

SetBytesAsString sets bytes value to datum as string type.

func (*Datum) SetCollation

func (d *Datum) SetCollation(collation byte)

SetCollation sets the collation of the datum.

func (*Datum) SetFloat32

func (d *Datum) SetFloat32(f float32)

SetFloat32 sets float32 value.

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 interface{})

SetInterface sets interface to datum.

func (*Datum) SetLength

func (d *Datum) SetLength(l int)

SetLength sets the length of the datum

func (*Datum) SetMysqlBit

func (d *Datum) SetMysqlBit(b Bit)

SetMysqlBit sets Bit 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)

SetMysqlEnum sets Enum value

func (*Datum) SetMysqlHex

func (d *Datum) SetMysqlHex(b Hex)

SetMysqlHex sets Hex value

func (*Datum) SetMysqlSet

func (d *Datum) SetMysqlSet(b Set)

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

func (d *Datum) SetRow(ds []Datum)

SetRow sets row value.

func (*Datum) SetString

func (d *Datum) SetString(s 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 interface{})

SetValue sets any kind of value.

func (*Datum) ToBool

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

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

func (*Datum) ToDecimal

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

ToDecimal converts to a decimal.

func (*Datum) ToFloat64

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

ToFloat64 converts to a float64

func (*Datum) ToInt64

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

ToInt64 converts to a int64.

func (*Datum) ToString

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

ToString gets the string representation of the datum.

type Duration

type Duration struct {
	time.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 ParseDuration

func ParseDuration(str string, fsp int) (Duration, error)

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

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, return 1, equal o, return 0, before o, return -1.

func (Duration) CompareString

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

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

func (Duration) ConvertToTime

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

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

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

func (d Duration) RoundFrac(fsp int) (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) 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 ParseEnumName

func ParseEnumName(elems []string, name 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) 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 FieldType

type FieldType struct {
	Tp      byte
	Flag    uint
	Flen    int
	Decimal int
	Charset string
	Collate string
	// Elems is the element list for enum and set type.
	Elems []string
}

FieldType records field type information.

func NewFieldType

func NewFieldType(tp byte) *FieldType

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

func (*FieldType) CompactStr

func (ft *FieldType) CompactStr() string

CompactStr only considers Tp/CharsetBin/Flen/Deimal. This is used for showing column type in infoschema.

func (*FieldType) Init

func (ft *FieldType) Init(tp byte)

Init initializes the FieldType data.

func (*FieldType) String

func (ft *FieldType) String() string

String joins the information of FieldType and returns a string.

type Hex

type Hex struct {
	// Value holds numeric value for hexadecimal literal.
	Value int64
}

Hex is for mysql hexadecimal literal type.

func ParseHex

func ParseHex(s string) (Hex, error)

ParseHex parses hexadecimal literal string. The string format can be X'val', x'val' or 0xval. val must in (0...9, a...f, A...F).

func (Hex) String

func (h Hex) String() string

String implements fmt.Stringer interface.

func (Hex) ToNumber

func (h Hex) ToNumber() float64

ToNumber changes hexadecimal type to float64 for numeric operation. MySQL treats hexadecimal literal as double type.

func (Hex) ToString

func (h Hex) ToString() string

ToString returns the string representation for hexadecimal literal.

type MyDecimal

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

MyDecimal represents a decimal value.

func ConvertDatumToDecimal

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

ConvertDatumToDecimal converts datum to decimal.

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

func (d *MyDecimal) IsNegative() bool

IsNegative returns whether a decimal is negative.

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) (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!
mode   - round to nearest even or truncate

NOTES

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

RETURN VALUE

eDecOK/eDecTruncated

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() (float64, error)

ToFloat64 converts decimal to float64 value.

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.

type Set

type Set struct {
	Name  string
	Value uint64
}

Set is for MySQL Set type.

func ParseSetName

func ParseSetName(elems []string, name 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) 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 {
	time.Time
	Type uint8
	// Fsp is short for Fractional Seconds Precision.
	// See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
	Fsp int
}

Time is the struct for handling datetime, timestamp and date. TODO: check if need a NewTime function to set Fsp default value?

func CurrentTime

func CurrentTime(tp uint8) Time

CurrentTime returns current time with type tp.

func ParseDate

func ParseDate(str string) (Time, error)

ParseDate is a helper function wrapping ParseTime with date type.

func ParseDateFromNum

func ParseDateFromNum(num int64) (Time, error)

ParseDateFromNum is a helper function wrapping ParseTimeFromNum with date type.

func ParseDatetime

func ParseDatetime(str string) (Time, error)

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

func ParseDatetimeFromNum

func ParseDatetimeFromNum(num int64) (Time, error)

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

func ParseTime

func ParseTime(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 datatime 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'

func ParseTimeFromInt64

func ParseTimeFromInt64(num int64) (Time, error)

ParseTimeFromInt64 parses mysql time value from int64.

func ParseTimeFromNum

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

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

func ParseTimestamp

func ParseTimestamp(str string) (Time, error)

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

func ParseTimestampFromNum

func ParseTimestampFromNum(num int64) (Time, error)

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

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, return 1, equal o, return 0, before o, return -1.

func (Time) CompareString

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

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

func (Time) Convert

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

Convert converts t with type tp.

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

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

FromPackedUint decodes Time from a packed uint64 value.

func (Time) IsZero

func (t Time) IsZero() bool

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

func (Time) RoundFrac

func (t Time) RoundFrac(fsp int) (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 (Time) String

func (t Time) String() string

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

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

Jump to

Keyboard shortcuts

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