repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
chrislusf/gleam
sql/plan/range.go
buildIndexRanges
func (r *rangeBuilder) buildIndexRanges(rangePoints []rangePoint, tp *types.FieldType) []*IndexRange { indexRanges := make([]*IndexRange, 0, len(rangePoints)/2) for i := 0; i < len(rangePoints); i += 2 { startPoint := r.convertPoint(rangePoints[i], tp) endPoint := r.convertPoint(rangePoints[i+1], tp) less, err := rangePointLess(r.sc, startPoint, endPoint) if err != nil { r.err = errors.Trace(err) } if !less { continue } ir := &IndexRange{ LowVal: []types.Datum{startPoint.value}, LowExclude: startPoint.excl, HighVal: []types.Datum{endPoint.value}, HighExclude: endPoint.excl, } indexRanges = append(indexRanges, ir) } return indexRanges }
go
func (r *rangeBuilder) buildIndexRanges(rangePoints []rangePoint, tp *types.FieldType) []*IndexRange { indexRanges := make([]*IndexRange, 0, len(rangePoints)/2) for i := 0; i < len(rangePoints); i += 2 { startPoint := r.convertPoint(rangePoints[i], tp) endPoint := r.convertPoint(rangePoints[i+1], tp) less, err := rangePointLess(r.sc, startPoint, endPoint) if err != nil { r.err = errors.Trace(err) } if !less { continue } ir := &IndexRange{ LowVal: []types.Datum{startPoint.value}, LowExclude: startPoint.excl, HighVal: []types.Datum{endPoint.value}, HighExclude: endPoint.excl, } indexRanges = append(indexRanges, ir) } return indexRanges }
[ "func", "(", "r", "*", "rangeBuilder", ")", "buildIndexRanges", "(", "rangePoints", "[", "]", "rangePoint", ",", "tp", "*", "types", ".", "FieldType", ")", "[", "]", "*", "IndexRange", "{", "indexRanges", ":=", "make", "(", "[", "]", "*", "IndexRange", ",", "0", ",", "len", "(", "rangePoints", ")", "/", "2", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "rangePoints", ")", ";", "i", "+=", "2", "{", "startPoint", ":=", "r", ".", "convertPoint", "(", "rangePoints", "[", "i", "]", ",", "tp", ")", "\n", "endPoint", ":=", "r", ".", "convertPoint", "(", "rangePoints", "[", "i", "+", "1", "]", ",", "tp", ")", "\n", "less", ",", "err", ":=", "rangePointLess", "(", "r", ".", "sc", ",", "startPoint", ",", "endPoint", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "err", "=", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "!", "less", "{", "continue", "\n", "}", "\n", "ir", ":=", "&", "IndexRange", "{", "LowVal", ":", "[", "]", "types", ".", "Datum", "{", "startPoint", ".", "value", "}", ",", "LowExclude", ":", "startPoint", ".", "excl", ",", "HighVal", ":", "[", "]", "types", ".", "Datum", "{", "endPoint", ".", "value", "}", ",", "HighExclude", ":", "endPoint", ".", "excl", ",", "}", "\n", "indexRanges", "=", "append", "(", "indexRanges", ",", "ir", ")", "\n", "}", "\n", "return", "indexRanges", "\n", "}" ]
// buildIndexRanges build index ranges from range points. // Only the first column in the index is built, extra column ranges will be appended by // appendIndexRanges.
[ "buildIndexRanges", "build", "index", "ranges", "from", "range", "points", ".", "Only", "the", "first", "column", "in", "the", "index", "is", "built", "extra", "column", "ranges", "will", "be", "appended", "by", "appendIndexRanges", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/range.go#L450-L471
train
chrislusf/gleam
sql/util/filesort/filesort.go
Less
func (fs *FileSorter) Less(i, j int) bool { l := fs.buf[i].key r := fs.buf[j].key ret, err := lessThan(fs.sc, l, r, fs.byDesc) if fs.err == nil { fs.err = err } return ret }
go
func (fs *FileSorter) Less(i, j int) bool { l := fs.buf[i].key r := fs.buf[j].key ret, err := lessThan(fs.sc, l, r, fs.byDesc) if fs.err == nil { fs.err = err } return ret }
[ "func", "(", "fs", "*", "FileSorter", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "l", ":=", "fs", ".", "buf", "[", "i", "]", ".", "key", "\n", "r", ":=", "fs", ".", "buf", "[", "j", "]", ".", "key", "\n", "ret", ",", "err", ":=", "lessThan", "(", "fs", ".", "sc", ",", "l", ",", "r", ",", "fs", ".", "byDesc", ")", "\n", "if", "fs", ".", "err", "==", "nil", "{", "fs", ".", "err", "=", "err", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Less implements sort.Interface Less interface.
[ "Less", "implements", "sort", ".", "Interface", "Less", "interface", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/filesort/filesort.go#L216-L224
train
chrislusf/gleam
sql/util/filesort/filesort.go
flushToFile
func (fs *FileSorter) flushToFile() error { var ( err error outputFile *os.File outputByte []byte ) sort.Sort(fs) if fs.err != nil { return errors.Trace(fs.err) } fileName := fs.getUniqueFileName() outputFile, err = os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return errors.Trace(err) } defer outputFile.Close() for _, row := range fs.buf { var body []byte var head = make([]byte, 8) body, err = codec.EncodeKey(body, row.key...) if err != nil { return errors.Trace(err) } body, err = codec.EncodeKey(body, row.val...) if err != nil { return errors.Trace(err) } body, err = codec.EncodeKey(body, types.NewIntDatum(row.handle)) if err != nil { return errors.Trace(err) } binary.BigEndian.PutUint64(head, uint64(len(body))) outputByte = append(outputByte, head...) outputByte = append(outputByte, body...) } _, err = outputFile.Write(outputByte) if err != nil { return errors.Trace(err) } fs.files = append(fs.files, fileName) fs.buf = fs.buf[:0] return nil }
go
func (fs *FileSorter) flushToFile() error { var ( err error outputFile *os.File outputByte []byte ) sort.Sort(fs) if fs.err != nil { return errors.Trace(fs.err) } fileName := fs.getUniqueFileName() outputFile, err = os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return errors.Trace(err) } defer outputFile.Close() for _, row := range fs.buf { var body []byte var head = make([]byte, 8) body, err = codec.EncodeKey(body, row.key...) if err != nil { return errors.Trace(err) } body, err = codec.EncodeKey(body, row.val...) if err != nil { return errors.Trace(err) } body, err = codec.EncodeKey(body, types.NewIntDatum(row.handle)) if err != nil { return errors.Trace(err) } binary.BigEndian.PutUint64(head, uint64(len(body))) outputByte = append(outputByte, head...) outputByte = append(outputByte, body...) } _, err = outputFile.Write(outputByte) if err != nil { return errors.Trace(err) } fs.files = append(fs.files, fileName) fs.buf = fs.buf[:0] return nil }
[ "func", "(", "fs", "*", "FileSorter", ")", "flushToFile", "(", ")", "error", "{", "var", "(", "err", "error", "\n", "outputFile", "*", "os", ".", "File", "\n", "outputByte", "[", "]", "byte", "\n", ")", "\n", "sort", ".", "Sort", "(", "fs", ")", "\n", "if", "fs", ".", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "fs", ".", "err", ")", "\n", "}", "\n", "fileName", ":=", "fs", ".", "getUniqueFileName", "(", ")", "\n", "outputFile", ",", "err", "=", "os", ".", "OpenFile", "(", "fileName", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "defer", "outputFile", ".", "Close", "(", ")", "\n", "for", "_", ",", "row", ":=", "range", "fs", ".", "buf", "{", "var", "body", "[", "]", "byte", "\n", "var", "head", "=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "body", ",", "err", "=", "codec", ".", "EncodeKey", "(", "body", ",", "row", ".", "key", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "body", ",", "err", "=", "codec", ".", "EncodeKey", "(", "body", ",", "row", ".", "val", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "body", ",", "err", "=", "codec", ".", "EncodeKey", "(", "body", ",", "types", ".", "NewIntDatum", "(", "row", ".", "handle", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "head", ",", "uint64", "(", "len", "(", "body", ")", ")", ")", "\n", "outputByte", "=", "append", "(", "outputByte", ",", "head", "...", ")", "\n", "outputByte", "=", "append", "(", "outputByte", ",", "body", "...", ")", "\n", "}", "\n", "_", ",", "err", "=", "outputFile", ".", "Write", "(", "outputByte", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "fs", ".", "files", "=", "append", "(", "fs", ".", "files", ",", "fileName", ")", "\n", "fs", ".", "buf", "=", "fs", ".", "buf", "[", ":", "0", "]", "\n", "return", "nil", "\n", "}" ]
// Flush the buffer to file if it is full.
[ "Flush", "the", "buffer", "to", "file", "if", "it", "is", "full", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/filesort/filesort.go#L233-L284
train
chrislusf/gleam
sql/util/filesort/filesort.go
fetchNextRow
func (fs *FileSorter) fetchNextRow(index int) (*comparableRow, error) { var ( err error n int head = make([]byte, 8) dcod = make([]types.Datum, 0, fs.keySize+fs.valSize+1) ) n, err = fs.fds[index].Read(head) if err == io.EOF { return nil, nil } if err != nil { return nil, errors.Trace(err) } if n != 8 { return nil, errors.New("incorrect header") } rowSize := int(binary.BigEndian.Uint64(head)) rowBytes := make([]byte, rowSize) n, err = fs.fds[index].Read(rowBytes) if err != nil { return nil, errors.Trace(err) } if n != rowSize { return nil, errors.New("incorrect row") } dcod, err = codec.Decode(rowBytes, fs.keySize+fs.valSize+1) if err != nil { return nil, errors.Trace(err) } return &comparableRow{ key: dcod[:fs.keySize], val: dcod[fs.keySize : fs.keySize+fs.valSize], handle: dcod[fs.keySize+fs.valSize:][0].GetInt64(), }, nil }
go
func (fs *FileSorter) fetchNextRow(index int) (*comparableRow, error) { var ( err error n int head = make([]byte, 8) dcod = make([]types.Datum, 0, fs.keySize+fs.valSize+1) ) n, err = fs.fds[index].Read(head) if err == io.EOF { return nil, nil } if err != nil { return nil, errors.Trace(err) } if n != 8 { return nil, errors.New("incorrect header") } rowSize := int(binary.BigEndian.Uint64(head)) rowBytes := make([]byte, rowSize) n, err = fs.fds[index].Read(rowBytes) if err != nil { return nil, errors.Trace(err) } if n != rowSize { return nil, errors.New("incorrect row") } dcod, err = codec.Decode(rowBytes, fs.keySize+fs.valSize+1) if err != nil { return nil, errors.Trace(err) } return &comparableRow{ key: dcod[:fs.keySize], val: dcod[fs.keySize : fs.keySize+fs.valSize], handle: dcod[fs.keySize+fs.valSize:][0].GetInt64(), }, nil }
[ "func", "(", "fs", "*", "FileSorter", ")", "fetchNextRow", "(", "index", "int", ")", "(", "*", "comparableRow", ",", "error", ")", "{", "var", "(", "err", "error", "\n", "n", "int", "\n", "head", "=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "dcod", "=", "make", "(", "[", "]", "types", ".", "Datum", ",", "0", ",", "fs", ".", "keySize", "+", "fs", ".", "valSize", "+", "1", ")", "\n", ")", "\n", "n", ",", "err", "=", "fs", ".", "fds", "[", "index", "]", ".", "Read", "(", "head", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "n", "!=", "8", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"incorrect header\"", ")", "\n", "}", "\n", "rowSize", ":=", "int", "(", "binary", ".", "BigEndian", ".", "Uint64", "(", "head", ")", ")", "\n", "rowBytes", ":=", "make", "(", "[", "]", "byte", ",", "rowSize", ")", "\n", "n", ",", "err", "=", "fs", ".", "fds", "[", "index", "]", ".", "Read", "(", "rowBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "n", "!=", "rowSize", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"incorrect row\"", ")", "\n", "}", "\n", "dcod", ",", "err", "=", "codec", ".", "Decode", "(", "rowBytes", ",", "fs", ".", "keySize", "+", "fs", ".", "valSize", "+", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "comparableRow", "{", "key", ":", "dcod", "[", ":", "fs", ".", "keySize", "]", ",", "val", ":", "dcod", "[", "fs", ".", "keySize", ":", "fs", ".", "keySize", "+", "fs", ".", "valSize", "]", ",", "handle", ":", "dcod", "[", "fs", ".", "keySize", "+", "fs", ".", "valSize", ":", "]", "[", "0", "]", ".", "GetInt64", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// Fetch the next row given the source file index.
[ "Fetch", "the", "next", "row", "given", "the", "source", "file", "index", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/filesort/filesort.go#L321-L360
train
chrislusf/gleam
sql/util/filesort/filesort.go
externalSort
func (fs *FileSorter) externalSort() (*comparableRow, error) { if !fs.fetched { if len(fs.buf) > 0 { err := fs.flushToFile() if err != nil { return nil, errors.Trace(err) } } heap.Init(fs.rowHeap) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } err := fs.openAllFiles() if err != nil { return nil, errors.Trace(err) } for id := range fs.fds { row, err := fs.fetchNextRow(id) if err != nil { return nil, errors.Trace(err) } if row == nil { return nil, errors.New("file is empty") } im := &item{ index: id, value: row, } heap.Push(fs.rowHeap, im) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } } fs.fetched = true } if fs.rowHeap.Len() > 0 { im := heap.Pop(fs.rowHeap).(*item) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } row, err := fs.fetchNextRow(im.index) if err != nil { return nil, errors.Trace(err) } if row != nil { im := &item{ index: im.index, value: row, } heap.Push(fs.rowHeap, im) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } } return im.value, nil } return nil, nil }
go
func (fs *FileSorter) externalSort() (*comparableRow, error) { if !fs.fetched { if len(fs.buf) > 0 { err := fs.flushToFile() if err != nil { return nil, errors.Trace(err) } } heap.Init(fs.rowHeap) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } err := fs.openAllFiles() if err != nil { return nil, errors.Trace(err) } for id := range fs.fds { row, err := fs.fetchNextRow(id) if err != nil { return nil, errors.Trace(err) } if row == nil { return nil, errors.New("file is empty") } im := &item{ index: id, value: row, } heap.Push(fs.rowHeap, im) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } } fs.fetched = true } if fs.rowHeap.Len() > 0 { im := heap.Pop(fs.rowHeap).(*item) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } row, err := fs.fetchNextRow(im.index) if err != nil { return nil, errors.Trace(err) } if row != nil { im := &item{ index: im.index, value: row, } heap.Push(fs.rowHeap, im) if fs.rowHeap.err != nil { return nil, errors.Trace(fs.rowHeap.err) } } return im.value, nil } return nil, nil }
[ "func", "(", "fs", "*", "FileSorter", ")", "externalSort", "(", ")", "(", "*", "comparableRow", ",", "error", ")", "{", "if", "!", "fs", ".", "fetched", "{", "if", "len", "(", "fs", ".", "buf", ")", ">", "0", "{", "err", ":=", "fs", ".", "flushToFile", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "heap", ".", "Init", "(", "fs", ".", "rowHeap", ")", "\n", "if", "fs", ".", "rowHeap", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "fs", ".", "rowHeap", ".", "err", ")", "\n", "}", "\n", "err", ":=", "fs", ".", "openAllFiles", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "for", "id", ":=", "range", "fs", ".", "fds", "{", "row", ",", "err", ":=", "fs", ".", "fetchNextRow", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "row", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"file is empty\"", ")", "\n", "}", "\n", "im", ":=", "&", "item", "{", "index", ":", "id", ",", "value", ":", "row", ",", "}", "\n", "heap", ".", "Push", "(", "fs", ".", "rowHeap", ",", "im", ")", "\n", "if", "fs", ".", "rowHeap", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "fs", ".", "rowHeap", ".", "err", ")", "\n", "}", "\n", "}", "\n", "fs", ".", "fetched", "=", "true", "\n", "}", "\n", "if", "fs", ".", "rowHeap", ".", "Len", "(", ")", ">", "0", "{", "im", ":=", "heap", ".", "Pop", "(", "fs", ".", "rowHeap", ")", ".", "(", "*", "item", ")", "\n", "if", "fs", ".", "rowHeap", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "fs", ".", "rowHeap", ".", "err", ")", "\n", "}", "\n", "row", ",", "err", ":=", "fs", ".", "fetchNextRow", "(", "im", ".", "index", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "row", "!=", "nil", "{", "im", ":=", "&", "item", "{", "index", ":", "im", ".", "index", ",", "value", ":", "row", ",", "}", "\n", "heap", ".", "Push", "(", "fs", ".", "rowHeap", ",", "im", ")", "\n", "if", "fs", ".", "rowHeap", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "fs", ".", "rowHeap", ".", "err", ")", "\n", "}", "\n", "}", "\n", "return", "im", ".", "value", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// Perform external file sort.
[ "Perform", "external", "file", "sort", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/filesort/filesort.go#L446-L514
train
chrislusf/gleam
sql/util/types/hex.go
ToString
func (h Hex) ToString() string { s := fmt.Sprintf("%x", h.Value) if len(s)%2 != 0 { s = "0" + s } // should never error. b, _ := hex.DecodeString(s) return string(b) }
go
func (h Hex) ToString() string { s := fmt.Sprintf("%x", h.Value) if len(s)%2 != 0 { s = "0" + s } // should never error. b, _ := hex.DecodeString(s) return string(b) }
[ "func", "(", "h", "Hex", ")", "ToString", "(", ")", "string", "{", "s", ":=", "fmt", ".", "Sprintf", "(", "\"%x\"", ",", "h", ".", "Value", ")", "\n", "if", "len", "(", "s", ")", "%", "2", "!=", "0", "{", "s", "=", "\"0\"", "+", "s", "\n", "}", "\n", "b", ",", "_", ":=", "hex", ".", "DecodeString", "(", "s", ")", "\n", "return", "string", "(", "b", ")", "\n", "}" ]
// ToString returns the string representation for hexadecimal literal.
[ "ToString", "returns", "the", "string", "representation", "for", "hexadecimal", "literal", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/hex.go#L48-L57
train
chrislusf/gleam
sql/executor/adapter.go
Exec
func (a *Statement) Exec(ctx context.Context) (*flow.Dataset, error) { a.startTime = time.Now() b := newExecutorBuilder(ctx, a.InfoSchema) exe := b.build(a.Plan) if b.err != nil { return nil, errors.Trace(b.err) } if exe == nil { return nil, fmt.Errorf("Failed to build execution plan %v", plan.ToString(a.Plan)) } return exe.Exec(), nil }
go
func (a *Statement) Exec(ctx context.Context) (*flow.Dataset, error) { a.startTime = time.Now() b := newExecutorBuilder(ctx, a.InfoSchema) exe := b.build(a.Plan) if b.err != nil { return nil, errors.Trace(b.err) } if exe == nil { return nil, fmt.Errorf("Failed to build execution plan %v", plan.ToString(a.Plan)) } return exe.Exec(), nil }
[ "func", "(", "a", "*", "Statement", ")", "Exec", "(", "ctx", "context", ".", "Context", ")", "(", "*", "flow", ".", "Dataset", ",", "error", ")", "{", "a", ".", "startTime", "=", "time", ".", "Now", "(", ")", "\n", "b", ":=", "newExecutorBuilder", "(", "ctx", ",", "a", ".", "InfoSchema", ")", "\n", "exe", ":=", "b", ".", "build", "(", "a", ".", "Plan", ")", "\n", "if", "b", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "b", ".", "err", ")", "\n", "}", "\n", "if", "exe", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Failed to build execution plan %v\"", ",", "plan", ".", "ToString", "(", "a", ".", "Plan", ")", ")", "\n", "}", "\n", "return", "exe", ".", "Exec", "(", ")", ",", "nil", "\n", "}" ]
// Exec implements the ast.Statement Exec interface. // This function builds an Executor from a plan. If the Executor doesn't return result, // like the INSERT, UPDATE statements, it executes in this function, if the Executor returns // result, execution is done after this function returns, in the returned ast.RecordSet Next method.
[ "Exec", "implements", "the", "ast", ".", "Statement", "Exec", "interface", ".", "This", "function", "builds", "an", "Executor", "from", "a", "plan", ".", "If", "the", "Executor", "doesn", "t", "return", "result", "like", "the", "INSERT", "UPDATE", "statements", "it", "executes", "in", "this", "function", "if", "the", "Executor", "returns", "result", "execution", "is", "done", "after", "this", "function", "returns", "in", "the", "returned", "ast", ".", "RecordSet", "Next", "method", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/executor/adapter.go#L32-L47
train
chrislusf/gleam
flow/dataset_union.go
Union
func (this *Dataset) Union(name string, others []*Dataset, isParallel bool) *Dataset { ret := this.Flow.NewNextDataset(len(this.Shards)) inputs := []*Dataset{this} inputs = append(inputs, others...) step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret) step.SetInstruction(name, instruction.NewUnion(isParallel)) return ret }
go
func (this *Dataset) Union(name string, others []*Dataset, isParallel bool) *Dataset { ret := this.Flow.NewNextDataset(len(this.Shards)) inputs := []*Dataset{this} inputs = append(inputs, others...) step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret) step.SetInstruction(name, instruction.NewUnion(isParallel)) return ret }
[ "func", "(", "this", "*", "Dataset", ")", "Union", "(", "name", "string", ",", "others", "[", "]", "*", "Dataset", ",", "isParallel", "bool", ")", "*", "Dataset", "{", "ret", ":=", "this", ".", "Flow", ".", "NewNextDataset", "(", "len", "(", "this", ".", "Shards", ")", ")", "\n", "inputs", ":=", "[", "]", "*", "Dataset", "{", "this", "}", "\n", "inputs", "=", "append", "(", "inputs", ",", "others", "...", ")", "\n", "step", ":=", "this", ".", "Flow", ".", "MergeDatasets1ShardTo1Step", "(", "inputs", ",", "ret", ")", "\n", "step", ".", "SetInstruction", "(", "name", ",", "instruction", ".", "NewUnion", "(", "isParallel", ")", ")", "\n", "return", "ret", "\n", "}" ]
// Union union multiple Datasets as one Dataset
[ "Union", "union", "multiple", "Datasets", "as", "one", "Dataset" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_union.go#L8-L15
train
chrislusf/gleam
distributed/agent/agent_grpc_server.go
Cleanup
func (as *AgentServer) Cleanup(ctx context.Context, cleanupRequest *pb.CleanupRequest) (*pb.CleanupResponse, error) { log.Println("cleaning up", cleanupRequest.GetFlowHashCode()) dir := path.Join(*as.Option.Dir, fmt.Sprintf("%d", cleanupRequest.GetFlowHashCode())) os.RemoveAll(dir) return &pb.CleanupResponse{}, nil }
go
func (as *AgentServer) Cleanup(ctx context.Context, cleanupRequest *pb.CleanupRequest) (*pb.CleanupResponse, error) { log.Println("cleaning up", cleanupRequest.GetFlowHashCode()) dir := path.Join(*as.Option.Dir, fmt.Sprintf("%d", cleanupRequest.GetFlowHashCode())) os.RemoveAll(dir) return &pb.CleanupResponse{}, nil }
[ "func", "(", "as", "*", "AgentServer", ")", "Cleanup", "(", "ctx", "context", ".", "Context", ",", "cleanupRequest", "*", "pb", ".", "CleanupRequest", ")", "(", "*", "pb", ".", "CleanupResponse", ",", "error", ")", "{", "log", ".", "Println", "(", "\"cleaning up\"", ",", "cleanupRequest", ".", "GetFlowHashCode", "(", ")", ")", "\n", "dir", ":=", "path", ".", "Join", "(", "*", "as", ".", "Option", ".", "Dir", ",", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "cleanupRequest", ".", "GetFlowHashCode", "(", ")", ")", ")", "\n", "os", ".", "RemoveAll", "(", "dir", ")", "\n", "return", "&", "pb", ".", "CleanupResponse", "{", "}", ",", "nil", "\n", "}" ]
// Cleanup remove all files related to a particular flow
[ "Cleanup", "remove", "all", "files", "related", "to", "a", "particular", "flow" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/agent/agent_grpc_server.go#L82-L89
train
chrislusf/gleam
distributed/agent/agent_grpc_server.go
Execute
func (as *AgentServer) Execute(request *pb.ExecutionRequest, stream pb.GleamAgent_ExecuteServer) error { dir := path.Join(*as.Option.Dir, fmt.Sprintf("%d", request.GetInstructionSet().GetFlowHashCode()), request.GetDir()) os.MkdirAll(dir, 0755) allocated := *request.GetResource() as.plusAllocated(allocated) defer as.minusAllocated(allocated) request.InstructionSet.AgentAddress = fmt.Sprintf("%s:%d", *as.Option.Host, *as.Option.Port) statsChan := createStatsChanByInstructionSet(request.InstructionSet) defer deleteStatsChanByInstructionSet(request.InstructionSet) return as.executeCommand(stream, request, dir, statsChan) }
go
func (as *AgentServer) Execute(request *pb.ExecutionRequest, stream pb.GleamAgent_ExecuteServer) error { dir := path.Join(*as.Option.Dir, fmt.Sprintf("%d", request.GetInstructionSet().GetFlowHashCode()), request.GetDir()) os.MkdirAll(dir, 0755) allocated := *request.GetResource() as.plusAllocated(allocated) defer as.minusAllocated(allocated) request.InstructionSet.AgentAddress = fmt.Sprintf("%s:%d", *as.Option.Host, *as.Option.Port) statsChan := createStatsChanByInstructionSet(request.InstructionSet) defer deleteStatsChanByInstructionSet(request.InstructionSet) return as.executeCommand(stream, request, dir, statsChan) }
[ "func", "(", "as", "*", "AgentServer", ")", "Execute", "(", "request", "*", "pb", ".", "ExecutionRequest", ",", "stream", "pb", ".", "GleamAgent_ExecuteServer", ")", "error", "{", "dir", ":=", "path", ".", "Join", "(", "*", "as", ".", "Option", ".", "Dir", ",", "fmt", ".", "Sprintf", "(", "\"%d\"", ",", "request", ".", "GetInstructionSet", "(", ")", ".", "GetFlowHashCode", "(", ")", ")", ",", "request", ".", "GetDir", "(", ")", ")", "\n", "os", ".", "MkdirAll", "(", "dir", ",", "0755", ")", "\n", "allocated", ":=", "*", "request", ".", "GetResource", "(", ")", "\n", "as", ".", "plusAllocated", "(", "allocated", ")", "\n", "defer", "as", ".", "minusAllocated", "(", "allocated", ")", "\n", "request", ".", "InstructionSet", ".", "AgentAddress", "=", "fmt", ".", "Sprintf", "(", "\"%s:%d\"", ",", "*", "as", ".", "Option", ".", "Host", ",", "*", "as", ".", "Option", ".", "Port", ")", "\n", "statsChan", ":=", "createStatsChanByInstructionSet", "(", "request", ".", "InstructionSet", ")", "\n", "defer", "deleteStatsChanByInstructionSet", "(", "request", ".", "InstructionSet", ")", "\n", "return", "as", ".", "executeCommand", "(", "stream", ",", "request", ",", "dir", ",", "statsChan", ")", "\n", "}" ]
// Execute executes a request and stream stdout and stderr back
[ "Execute", "executes", "a", "request", "and", "stream", "stdout", "and", "stderr", "back" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/agent/agent_grpc_server.go#L92-L110
train
chrislusf/gleam
distributed/agent/agent_grpc_server.go
CollectExecutionStatistics
func (as *AgentServer) CollectExecutionStatistics(stream pb.GleamAgent_CollectExecutionStatisticsServer) error { var statsChan chan *pb.ExecutionStat for { stats, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } if statsChan == nil { statsChan = getStatsChan(stats.FlowHashCode, stats.Stats[0].GetStepId(), stats.Stats[0].GetTaskId()) } statsChan <- stats // fmt.Printf("received stats: %+v\n", stats) } }
go
func (as *AgentServer) CollectExecutionStatistics(stream pb.GleamAgent_CollectExecutionStatisticsServer) error { var statsChan chan *pb.ExecutionStat for { stats, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } if statsChan == nil { statsChan = getStatsChan(stats.FlowHashCode, stats.Stats[0].GetStepId(), stats.Stats[0].GetTaskId()) } statsChan <- stats // fmt.Printf("received stats: %+v\n", stats) } }
[ "func", "(", "as", "*", "AgentServer", ")", "CollectExecutionStatistics", "(", "stream", "pb", ".", "GleamAgent_CollectExecutionStatisticsServer", ")", "error", "{", "var", "statsChan", "chan", "*", "pb", ".", "ExecutionStat", "\n", "for", "{", "stats", ",", "err", ":=", "stream", ".", "Recv", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "statsChan", "==", "nil", "{", "statsChan", "=", "getStatsChan", "(", "stats", ".", "FlowHashCode", ",", "stats", ".", "Stats", "[", "0", "]", ".", "GetStepId", "(", ")", ",", "stats", ".", "Stats", "[", "0", "]", ".", "GetTaskId", "(", ")", ")", "\n", "}", "\n", "statsChan", "<-", "stats", "\n", "}", "\n", "}" ]
// Collect stat from "gleam execute" process
[ "Collect", "stat", "from", "gleam", "execute", "process" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/agent/agent_grpc_server.go#L113-L132
train
chrislusf/gleam
distributed/agent/agent_grpc_server.go
Delete
func (as *AgentServer) Delete(ctx context.Context, deleteRequest *pb.DeleteDatasetShardRequest) (*pb.DeleteDatasetShardResponse, error) { log.Println("deleting", deleteRequest.Name) as.storageBackend.DeleteNamedDatasetShard(deleteRequest.Name) as.inMemoryChannels.Cleanup(deleteRequest.Name) return &pb.DeleteDatasetShardResponse{}, nil }
go
func (as *AgentServer) Delete(ctx context.Context, deleteRequest *pb.DeleteDatasetShardRequest) (*pb.DeleteDatasetShardResponse, error) { log.Println("deleting", deleteRequest.Name) as.storageBackend.DeleteNamedDatasetShard(deleteRequest.Name) as.inMemoryChannels.Cleanup(deleteRequest.Name) return &pb.DeleteDatasetShardResponse{}, nil }
[ "func", "(", "as", "*", "AgentServer", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "deleteRequest", "*", "pb", ".", "DeleteDatasetShardRequest", ")", "(", "*", "pb", ".", "DeleteDatasetShardResponse", ",", "error", ")", "{", "log", ".", "Println", "(", "\"deleting\"", ",", "deleteRequest", ".", "Name", ")", "\n", "as", ".", "storageBackend", ".", "DeleteNamedDatasetShard", "(", "deleteRequest", ".", "Name", ")", "\n", "as", ".", "inMemoryChannels", ".", "Cleanup", "(", "deleteRequest", ".", "Name", ")", "\n", "return", "&", "pb", ".", "DeleteDatasetShardResponse", "{", "}", ",", "nil", "\n", "}" ]
// Delete deletes a particular dataset shard
[ "Delete", "deletes", "a", "particular", "dataset", "shard" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/agent/agent_grpc_server.go#L135-L142
train
chrislusf/gleam
distributed/master/ui/svg_writer.go
collectStepOutputDatasetSize
func collectStepOutputDatasetSize(status *pb.FlowExecutionStatus, stepId int32) (counter int64) { for _, tg := range status.TaskGroups { for _, execution := range tg.Executions { if execution.ExecutionStat == nil { continue } for _, stat := range execution.ExecutionStat.Stats { if stat.StepId == stepId { counter += stat.OutputCounter } } } } return counter }
go
func collectStepOutputDatasetSize(status *pb.FlowExecutionStatus, stepId int32) (counter int64) { for _, tg := range status.TaskGroups { for _, execution := range tg.Executions { if execution.ExecutionStat == nil { continue } for _, stat := range execution.ExecutionStat.Stats { if stat.StepId == stepId { counter += stat.OutputCounter } } } } return counter }
[ "func", "collectStepOutputDatasetSize", "(", "status", "*", "pb", ".", "FlowExecutionStatus", ",", "stepId", "int32", ")", "(", "counter", "int64", ")", "{", "for", "_", ",", "tg", ":=", "range", "status", ".", "TaskGroups", "{", "for", "_", ",", "execution", ":=", "range", "tg", ".", "Executions", "{", "if", "execution", ".", "ExecutionStat", "==", "nil", "{", "continue", "\n", "}", "\n", "for", "_", ",", "stat", ":=", "range", "execution", ".", "ExecutionStat", ".", "Stats", "{", "if", "stat", ".", "StepId", "==", "stepId", "{", "counter", "+=", "stat", ".", "OutputCounter", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "counter", "\n", "}" ]
// may be more efficient to map stepId=>size
[ "may", "be", "more", "efficient", "to", "map", "stepId", "=", ">", "size" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/master/ui/svg_writer.go#L185-L199
train
chrislusf/gleam
sql/util/types/mytime.go
DateDiff
func DateDiff(startTime, endTime TimeInternal) int { return calcDaynr(startTime.Year(), startTime.Month(), startTime.Day()) - calcDaynr(endTime.Year(), endTime.Month(), endTime.Day()) }
go
func DateDiff(startTime, endTime TimeInternal) int { return calcDaynr(startTime.Year(), startTime.Month(), startTime.Day()) - calcDaynr(endTime.Year(), endTime.Month(), endTime.Day()) }
[ "func", "DateDiff", "(", "startTime", ",", "endTime", "TimeInternal", ")", "int", "{", "return", "calcDaynr", "(", "startTime", ".", "Year", "(", ")", ",", "startTime", ".", "Month", "(", ")", ",", "startTime", ".", "Day", "(", ")", ")", "-", "calcDaynr", "(", "endTime", ".", "Year", "(", ")", ",", "endTime", ".", "Month", "(", ")", ",", "endTime", ".", "Day", "(", ")", ")", "\n", "}" ]
// DateDiff calculates number of days between two days.
[ "DateDiff", "calculates", "number", "of", "days", "between", "two", "days", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/mytime.go#L188-L190
train
chrislusf/gleam
sql/expression/builtin_like.go
compilePattern
func compilePattern(pattern string, escape byte) (patChars, patTypes []byte) { var lastAny bool patChars = make([]byte, len(pattern)) patTypes = make([]byte, len(pattern)) patLen := 0 for i := 0; i < len(pattern); i++ { var tp byte var c = pattern[i] switch c { case escape: lastAny = false tp = patMatch if i < len(pattern)-1 { i++ c = pattern[i] if c == escape || c == '_' || c == '%' { // valid escape. } else { // invalid escape, fall back to escape byte // mysql will treat escape character as the origin value even // the escape sequence is invalid in Go or C. // e.g, \m is invalid in Go, but in MySQL we will get "m" for select '\m'. // Following case is correct just for escape \, not for others like +. // TODO: add more checks for other escapes. i-- c = escape } } case '_': lastAny = false tp = patOne case '%': if lastAny { continue } lastAny = true tp = patAny default: lastAny = false tp = patMatch } patChars[patLen] = c patTypes[patLen] = tp patLen++ } for i := 0; i < patLen-1; i++ { if (patTypes[i] == patAny) && (patTypes[i+1] == patOne) { patTypes[i] = patOne patTypes[i+1] = patAny } } patChars = patChars[:patLen] patTypes = patTypes[:patLen] return }
go
func compilePattern(pattern string, escape byte) (patChars, patTypes []byte) { var lastAny bool patChars = make([]byte, len(pattern)) patTypes = make([]byte, len(pattern)) patLen := 0 for i := 0; i < len(pattern); i++ { var tp byte var c = pattern[i] switch c { case escape: lastAny = false tp = patMatch if i < len(pattern)-1 { i++ c = pattern[i] if c == escape || c == '_' || c == '%' { // valid escape. } else { // invalid escape, fall back to escape byte // mysql will treat escape character as the origin value even // the escape sequence is invalid in Go or C. // e.g, \m is invalid in Go, but in MySQL we will get "m" for select '\m'. // Following case is correct just for escape \, not for others like +. // TODO: add more checks for other escapes. i-- c = escape } } case '_': lastAny = false tp = patOne case '%': if lastAny { continue } lastAny = true tp = patAny default: lastAny = false tp = patMatch } patChars[patLen] = c patTypes[patLen] = tp patLen++ } for i := 0; i < patLen-1; i++ { if (patTypes[i] == patAny) && (patTypes[i+1] == patOne) { patTypes[i] = patOne patTypes[i+1] = patAny } } patChars = patChars[:patLen] patTypes = patTypes[:patLen] return }
[ "func", "compilePattern", "(", "pattern", "string", ",", "escape", "byte", ")", "(", "patChars", ",", "patTypes", "[", "]", "byte", ")", "{", "var", "lastAny", "bool", "\n", "patChars", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "pattern", ")", ")", "\n", "patTypes", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "pattern", ")", ")", "\n", "patLen", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "pattern", ")", ";", "i", "++", "{", "var", "tp", "byte", "\n", "var", "c", "=", "pattern", "[", "i", "]", "\n", "switch", "c", "{", "case", "escape", ":", "lastAny", "=", "false", "\n", "tp", "=", "patMatch", "\n", "if", "i", "<", "len", "(", "pattern", ")", "-", "1", "{", "i", "++", "\n", "c", "=", "pattern", "[", "i", "]", "\n", "if", "c", "==", "escape", "||", "c", "==", "'_'", "||", "c", "==", "'%'", "{", "}", "else", "{", "i", "--", "\n", "c", "=", "escape", "\n", "}", "\n", "}", "\n", "case", "'_'", ":", "lastAny", "=", "false", "\n", "tp", "=", "patOne", "\n", "case", "'%'", ":", "if", "lastAny", "{", "continue", "\n", "}", "\n", "lastAny", "=", "true", "\n", "tp", "=", "patAny", "\n", "default", ":", "lastAny", "=", "false", "\n", "tp", "=", "patMatch", "\n", "}", "\n", "patChars", "[", "patLen", "]", "=", "c", "\n", "patTypes", "[", "patLen", "]", "=", "tp", "\n", "patLen", "++", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "patLen", "-", "1", ";", "i", "++", "{", "if", "(", "patTypes", "[", "i", "]", "==", "patAny", ")", "&&", "(", "patTypes", "[", "i", "+", "1", "]", "==", "patOne", ")", "{", "patTypes", "[", "i", "]", "=", "patOne", "\n", "patTypes", "[", "i", "+", "1", "]", "=", "patAny", "\n", "}", "\n", "}", "\n", "patChars", "=", "patChars", "[", ":", "patLen", "]", "\n", "patTypes", "=", "patTypes", "[", ":", "patLen", "]", "\n", "return", "\n", "}" ]
// Handle escapes and wild cards convert pattern characters and pattern types.
[ "Handle", "escapes", "and", "wild", "cards", "convert", "pattern", "characters", "and", "pattern", "types", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/builtin_like.go#L41-L95
train
chrislusf/gleam
sql/util/codec/codec.go
peek
func peek(b []byte) (length int, err error) { if len(b) < 1 { return 0, errors.New("invalid encoded key") } flag := b[0] length++ b = b[1:] var l int switch flag { case NilFlag: case intFlag, uintFlag, floatFlag, durationFlag: // Those types are stored in 8 bytes. l = 8 case bytesFlag: l, err = peekBytes(b, false) case compactBytesFlag: l, err = peekCompactBytes(b) case decimalFlag: l, err = types.DecimalPeak(b) case varintFlag: l, err = peekVarint(b) case uvarintFlag: l, err = peekUvarint(b) default: return 0, errors.Errorf("invalid encoded key flag %v", flag) } if err != nil { return 0, errors.Trace(err) } length += l return }
go
func peek(b []byte) (length int, err error) { if len(b) < 1 { return 0, errors.New("invalid encoded key") } flag := b[0] length++ b = b[1:] var l int switch flag { case NilFlag: case intFlag, uintFlag, floatFlag, durationFlag: // Those types are stored in 8 bytes. l = 8 case bytesFlag: l, err = peekBytes(b, false) case compactBytesFlag: l, err = peekCompactBytes(b) case decimalFlag: l, err = types.DecimalPeak(b) case varintFlag: l, err = peekVarint(b) case uvarintFlag: l, err = peekUvarint(b) default: return 0, errors.Errorf("invalid encoded key flag %v", flag) } if err != nil { return 0, errors.Trace(err) } length += l return }
[ "func", "peek", "(", "b", "[", "]", "byte", ")", "(", "length", "int", ",", "err", "error", ")", "{", "if", "len", "(", "b", ")", "<", "1", "{", "return", "0", ",", "errors", ".", "New", "(", "\"invalid encoded key\"", ")", "\n", "}", "\n", "flag", ":=", "b", "[", "0", "]", "\n", "length", "++", "\n", "b", "=", "b", "[", "1", ":", "]", "\n", "var", "l", "int", "\n", "switch", "flag", "{", "case", "NilFlag", ":", "case", "intFlag", ",", "uintFlag", ",", "floatFlag", ",", "durationFlag", ":", "l", "=", "8", "\n", "case", "bytesFlag", ":", "l", ",", "err", "=", "peekBytes", "(", "b", ",", "false", ")", "\n", "case", "compactBytesFlag", ":", "l", ",", "err", "=", "peekCompactBytes", "(", "b", ")", "\n", "case", "decimalFlag", ":", "l", ",", "err", "=", "types", ".", "DecimalPeak", "(", "b", ")", "\n", "case", "varintFlag", ":", "l", ",", "err", "=", "peekVarint", "(", "b", ")", "\n", "case", "uvarintFlag", ":", "l", ",", "err", "=", "peekUvarint", "(", "b", ")", "\n", "default", ":", "return", "0", ",", "errors", ".", "Errorf", "(", "\"invalid encoded key flag %v\"", ",", "flag", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "length", "+=", "l", "\n", "return", "\n", "}" ]
// peeks the first encoded value from b and returns its length.
[ "peeks", "the", "first", "encoded", "value", "from", "b", "and", "returns", "its", "length", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/codec/codec.go#L226-L257
train
chrislusf/gleam
flow/dataset_hint.go
Hint
func (d *Dataset) Hint(options ...DasetsetHint) *Dataset { for _, option := range options { option(d) } return d }
go
func (d *Dataset) Hint(options ...DasetsetHint) *Dataset { for _, option := range options { option(d) } return d }
[ "func", "(", "d", "*", "Dataset", ")", "Hint", "(", "options", "...", "DasetsetHint", ")", "*", "Dataset", "{", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "d", ")", "\n", "}", "\n", "return", "d", "\n", "}" ]
// Hint adds options for previous dataset.
[ "Hint", "adds", "options", "for", "previous", "dataset", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_hint.go#L6-L11
train
chrislusf/gleam
flow/dataset_hint.go
TotalSize
func TotalSize(n int64) DasetsetHint { return func(d *Dataset) { d.Meta.TotalSize = n } }
go
func TotalSize(n int64) DasetsetHint { return func(d *Dataset) { d.Meta.TotalSize = n } }
[ "func", "TotalSize", "(", "n", "int64", ")", "DasetsetHint", "{", "return", "func", "(", "d", "*", "Dataset", ")", "{", "d", ".", "Meta", ".", "TotalSize", "=", "n", "\n", "}", "\n", "}" ]
// TotalSize hints the total size in MB for all the partitions. // This is usually used when sorting is needed.
[ "TotalSize", "hints", "the", "total", "size", "in", "MB", "for", "all", "the", "partitions", ".", "This", "is", "usually", "used", "when", "sorting", "is", "needed", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_hint.go#L15-L19
train
chrislusf/gleam
flow/dataset_hint.go
PartitionSize
func PartitionSize(n int64) DasetsetHint { return func(d *Dataset) { d.Meta.TotalSize = n * int64(len(d.GetShards())) } }
go
func PartitionSize(n int64) DasetsetHint { return func(d *Dataset) { d.Meta.TotalSize = n * int64(len(d.GetShards())) } }
[ "func", "PartitionSize", "(", "n", "int64", ")", "DasetsetHint", "{", "return", "func", "(", "d", "*", "Dataset", ")", "{", "d", ".", "Meta", ".", "TotalSize", "=", "n", "*", "int64", "(", "len", "(", "d", ".", "GetShards", "(", ")", ")", ")", "\n", "}", "\n", "}" ]
// PartitionSize hints the partition size in MB. // This is usually used when sorting is needed.
[ "PartitionSize", "hints", "the", "partition", "size", "in", "MB", ".", "This", "is", "usually", "used", "when", "sorting", "is", "needed", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_hint.go#L23-L27
train
chrislusf/gleam
flow/dataset_hint.go
OnDisk
func (d *Dataset) OnDisk(fn func(*Dataset) *Dataset) *Dataset { ret := fn(d) var parents, currents []*Dataset currents = append(currents, ret) for { for _, t := range currents { isFirstDataset, isLastDataset := false, false if t == ret { isLastDataset = true } else if t.Step.OutputDataset != nil { t.Step.OutputDataset.Meta.OnDisk = ModeOnDisk } for _, p := range t.Step.InputDatasets { if p != d { parents = append(parents, p) } else { isFirstDataset = true } } if !isFirstDataset && !isLastDataset { t.Step.Meta.IsRestartable = true } } if len(parents) == 0 { break } currents = parents parents = nil } return ret }
go
func (d *Dataset) OnDisk(fn func(*Dataset) *Dataset) *Dataset { ret := fn(d) var parents, currents []*Dataset currents = append(currents, ret) for { for _, t := range currents { isFirstDataset, isLastDataset := false, false if t == ret { isLastDataset = true } else if t.Step.OutputDataset != nil { t.Step.OutputDataset.Meta.OnDisk = ModeOnDisk } for _, p := range t.Step.InputDatasets { if p != d { parents = append(parents, p) } else { isFirstDataset = true } } if !isFirstDataset && !isLastDataset { t.Step.Meta.IsRestartable = true } } if len(parents) == 0 { break } currents = parents parents = nil } return ret }
[ "func", "(", "d", "*", "Dataset", ")", "OnDisk", "(", "fn", "func", "(", "*", "Dataset", ")", "*", "Dataset", ")", "*", "Dataset", "{", "ret", ":=", "fn", "(", "d", ")", "\n", "var", "parents", ",", "currents", "[", "]", "*", "Dataset", "\n", "currents", "=", "append", "(", "currents", ",", "ret", ")", "\n", "for", "{", "for", "_", ",", "t", ":=", "range", "currents", "{", "isFirstDataset", ",", "isLastDataset", ":=", "false", ",", "false", "\n", "if", "t", "==", "ret", "{", "isLastDataset", "=", "true", "\n", "}", "else", "if", "t", ".", "Step", ".", "OutputDataset", "!=", "nil", "{", "t", ".", "Step", ".", "OutputDataset", ".", "Meta", ".", "OnDisk", "=", "ModeOnDisk", "\n", "}", "\n", "for", "_", ",", "p", ":=", "range", "t", ".", "Step", ".", "InputDatasets", "{", "if", "p", "!=", "d", "{", "parents", "=", "append", "(", "parents", ",", "p", ")", "\n", "}", "else", "{", "isFirstDataset", "=", "true", "\n", "}", "\n", "}", "\n", "if", "!", "isFirstDataset", "&&", "!", "isLastDataset", "{", "t", ".", "Step", ".", "Meta", ".", "IsRestartable", "=", "true", "\n", "}", "\n", "}", "\n", "if", "len", "(", "parents", ")", "==", "0", "{", "break", "\n", "}", "\n", "currents", "=", "parents", "\n", "parents", "=", "nil", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// OnDisk ensure the intermediate dataset are persisted to disk. // This allows executors to run not in parallel if executors are limited.
[ "OnDisk", "ensure", "the", "intermediate", "dataset", "are", "persisted", "to", "disk", ".", "This", "allows", "executors", "to", "run", "not", "in", "parallel", "if", "executors", "are", "limited", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_hint.go#L31-L63
train
chrislusf/gleam
sql/ast/misc.go
Accept
func (n *AdminStmt) Accept(v Visitor) (Node, bool) { newNode, skipChildren := v.Enter(n) if skipChildren { return v.Leave(newNode) } n = newNode.(*AdminStmt) for i, val := range n.Tables { node, ok := val.Accept(v) if !ok { return n, false } n.Tables[i] = node.(*TableName) } return v.Leave(n) }
go
func (n *AdminStmt) Accept(v Visitor) (Node, bool) { newNode, skipChildren := v.Enter(n) if skipChildren { return v.Leave(newNode) } n = newNode.(*AdminStmt) for i, val := range n.Tables { node, ok := val.Accept(v) if !ok { return n, false } n.Tables[i] = node.(*TableName) } return v.Leave(n) }
[ "func", "(", "n", "*", "AdminStmt", ")", "Accept", "(", "v", "Visitor", ")", "(", "Node", ",", "bool", ")", "{", "newNode", ",", "skipChildren", ":=", "v", ".", "Enter", "(", "n", ")", "\n", "if", "skipChildren", "{", "return", "v", ".", "Leave", "(", "newNode", ")", "\n", "}", "\n", "n", "=", "newNode", ".", "(", "*", "AdminStmt", ")", "\n", "for", "i", ",", "val", ":=", "range", "n", ".", "Tables", "{", "node", ",", "ok", ":=", "val", ".", "Accept", "(", "v", ")", "\n", "if", "!", "ok", "{", "return", "n", ",", "false", "\n", "}", "\n", "n", ".", "Tables", "[", "i", "]", "=", "node", ".", "(", "*", "TableName", ")", "\n", "}", "\n", "return", "v", ".", "Leave", "(", "n", ")", "\n", "}" ]
// Accept implements Node Accpet interface.
[ "Accept", "implements", "Node", "Accpet", "interface", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/ast/misc.go#L475-L491
train
chrislusf/gleam
sql/ast/misc.go
Full
func (i Ident) Full(ctx context.Context) (full Ident) { full.Name = i.Name if i.Schema.O != "" { full.Schema = i.Schema } else { full.Schema = model.NewCIStr(ctx.GetSessionVars().CurrentDB) } return }
go
func (i Ident) Full(ctx context.Context) (full Ident) { full.Name = i.Name if i.Schema.O != "" { full.Schema = i.Schema } else { full.Schema = model.NewCIStr(ctx.GetSessionVars().CurrentDB) } return }
[ "func", "(", "i", "Ident", ")", "Full", "(", "ctx", "context", ".", "Context", ")", "(", "full", "Ident", ")", "{", "full", ".", "Name", "=", "i", ".", "Name", "\n", "if", "i", ".", "Schema", ".", "O", "!=", "\"\"", "{", "full", ".", "Schema", "=", "i", ".", "Schema", "\n", "}", "else", "{", "full", ".", "Schema", "=", "model", ".", "NewCIStr", "(", "ctx", ".", "GetSessionVars", "(", ")", ".", "CurrentDB", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Full returns an Ident which set schema to the current schema if it is empty.
[ "Full", "returns", "an", "Ident", "which", "set", "schema", "to", "the", "current", "schema", "if", "it", "is", "empty", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/ast/misc.go#L583-L591
train
chrislusf/gleam
sql/ast/misc.go
String
func (i Ident) String() string { if i.Schema.O == "" { return i.Name.O } return fmt.Sprintf("%s.%s", i.Schema, i.Name) }
go
func (i Ident) String() string { if i.Schema.O == "" { return i.Name.O } return fmt.Sprintf("%s.%s", i.Schema, i.Name) }
[ "func", "(", "i", "Ident", ")", "String", "(", ")", "string", "{", "if", "i", ".", "Schema", ".", "O", "==", "\"\"", "{", "return", "i", ".", "Name", ".", "O", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%s.%s\"", ",", "i", ".", "Schema", ",", "i", ".", "Name", ")", "\n", "}" ]
// String implements fmt.Stringer interface
[ "String", "implements", "fmt", ".", "Stringer", "interface" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/ast/misc.go#L594-L599
train
chrislusf/gleam
plugins/file/csv/generic_csv_reader.go
error
func (r *Reader) error(err error) error { return &ParseError{ Line: r.line, Column: r.column, Err: err, } }
go
func (r *Reader) error(err error) error { return &ParseError{ Line: r.line, Column: r.column, Err: err, } }
[ "func", "(", "r", "*", "Reader", ")", "error", "(", "err", "error", ")", "error", "{", "return", "&", "ParseError", "{", "Line", ":", "r", ".", "line", ",", "Column", ":", "r", ".", "column", ",", "Err", ":", "err", ",", "}", "\n", "}" ]
// error creates a new ParseError based on err.
[ "error", "creates", "a", "new", "ParseError", "based", "on", "err", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/plugins/file/csv/generic_csv_reader.go#L129-L135
train
chrislusf/gleam
plugins/file/csv/generic_csv_reader.go
ReadAll
func (r *Reader) ReadAll() (records [][]string, err error) { for { record, err := r.Read() if err == io.EOF { return records, nil } if err != nil { return nil, err } records = append(records, record) } }
go
func (r *Reader) ReadAll() (records [][]string, err error) { for { record, err := r.Read() if err == io.EOF { return records, nil } if err != nil { return nil, err } records = append(records, record) } }
[ "func", "(", "r", "*", "Reader", ")", "ReadAll", "(", ")", "(", "records", "[", "]", "[", "]", "string", ",", "err", "error", ")", "{", "for", "{", "record", ",", "err", ":=", "r", ".", "Read", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "records", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "records", "=", "append", "(", "records", ",", "record", ")", "\n", "}", "\n", "}" ]
// ReadAll reads all the remaining records from r. // Each record is a slice of fields. // A successful call returns err == nil, not err == EOF. Because ReadAll is // defined to read until EOF, it does not treat end of file as an error to be // reported.
[ "ReadAll", "reads", "all", "the", "remaining", "records", "from", "r", ".", "Each", "record", "is", "a", "slice", "of", "fields", ".", "A", "successful", "call", "returns", "err", "==", "nil", "not", "err", "==", "EOF", ".", "Because", "ReadAll", "is", "defined", "to", "read", "until", "EOF", "it", "does", "not", "treat", "end", "of", "file", "as", "an", "error", "to", "be", "reported", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/plugins/file/csv/generic_csv_reader.go#L166-L177
train
chrislusf/gleam
plugins/file/csv/generic_csv_reader.go
readRune
func (r *Reader) readRune() (rune, error) { r1, _, err := r.r.ReadRune() // Handle \r\n here. We make the simplifying assumption that // anytime \r is followed by \n that it can be folded to \n. // We will not detect files which contain both \r\n and bare \n. if r1 == '\r' { r1, _, err = r.r.ReadRune() if err == nil { if r1 != '\n' { r.r.UnreadRune() r1 = '\r' } } } r.column++ return r1, err }
go
func (r *Reader) readRune() (rune, error) { r1, _, err := r.r.ReadRune() // Handle \r\n here. We make the simplifying assumption that // anytime \r is followed by \n that it can be folded to \n. // We will not detect files which contain both \r\n and bare \n. if r1 == '\r' { r1, _, err = r.r.ReadRune() if err == nil { if r1 != '\n' { r.r.UnreadRune() r1 = '\r' } } } r.column++ return r1, err }
[ "func", "(", "r", "*", "Reader", ")", "readRune", "(", ")", "(", "rune", ",", "error", ")", "{", "r1", ",", "_", ",", "err", ":=", "r", ".", "r", ".", "ReadRune", "(", ")", "\n", "if", "r1", "==", "'\\r'", "{", "r1", ",", "_", ",", "err", "=", "r", ".", "r", ".", "ReadRune", "(", ")", "\n", "if", "err", "==", "nil", "{", "if", "r1", "!=", "'\\n'", "{", "r", ".", "r", ".", "UnreadRune", "(", ")", "\n", "r1", "=", "'\\r'", "\n", "}", "\n", "}", "\n", "}", "\n", "r", ".", "column", "++", "\n", "return", "r1", ",", "err", "\n", "}" ]
// readRune reads one rune from r, folding \r\n to \n and keeping track // of how far into the line we have read. r.column will point to the start // of this rune, not the end of this rune.
[ "readRune", "reads", "one", "rune", "from", "r", "folding", "\\", "r", "\\", "n", "to", "\\", "n", "and", "keeping", "track", "of", "how", "far", "into", "the", "line", "we", "have", "read", ".", "r", ".", "column", "will", "point", "to", "the", "start", "of", "this", "rune", "not", "the", "end", "of", "this", "rune", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/plugins/file/csv/generic_csv_reader.go#L182-L199
train
chrislusf/gleam
plugins/file/csv/generic_csv_reader.go
skip
func (r *Reader) skip(delim rune) error { for { r1, err := r.readRune() if err != nil { return err } if r1 == delim { return nil } } }
go
func (r *Reader) skip(delim rune) error { for { r1, err := r.readRune() if err != nil { return err } if r1 == delim { return nil } } }
[ "func", "(", "r", "*", "Reader", ")", "skip", "(", "delim", "rune", ")", "error", "{", "for", "{", "r1", ",", "err", ":=", "r", ".", "readRune", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "r1", "==", "delim", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// skip reads runes up to and including the rune delim or until error.
[ "skip", "reads", "runes", "up", "to", "and", "including", "the", "rune", "delim", "or", "until", "error", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/plugins/file/csv/generic_csv_reader.go#L202-L212
train
chrislusf/gleam
plugins/file/csv/generic_csv_reader.go
parseRecord
func (r *Reader) parseRecord() (fields []string, err error) { // Each record starts on a new line. We increment our line // number (lines start at 1, not 0) and set column to -1 // so as we increment in readRune it points to the character we read. r.line++ r.column = -1 // Peek at the first rune. If it is an error we are done. // If we are support comments and it is the comment character // then skip to the end of line. r1, _, err := r.r.ReadRune() if err != nil { return nil, err } if r.Comment != 0 && r1 == r.Comment { return nil, r.skip('\n') } r.r.UnreadRune() // At this point we have at least one field. for { haveField, delim, err := r.parseField() if haveField { fields = append(fields, r.field.String()) } if delim == '\n' || err == io.EOF { return fields, err } else if err != nil { return nil, err } } }
go
func (r *Reader) parseRecord() (fields []string, err error) { // Each record starts on a new line. We increment our line // number (lines start at 1, not 0) and set column to -1 // so as we increment in readRune it points to the character we read. r.line++ r.column = -1 // Peek at the first rune. If it is an error we are done. // If we are support comments and it is the comment character // then skip to the end of line. r1, _, err := r.r.ReadRune() if err != nil { return nil, err } if r.Comment != 0 && r1 == r.Comment { return nil, r.skip('\n') } r.r.UnreadRune() // At this point we have at least one field. for { haveField, delim, err := r.parseField() if haveField { fields = append(fields, r.field.String()) } if delim == '\n' || err == io.EOF { return fields, err } else if err != nil { return nil, err } } }
[ "func", "(", "r", "*", "Reader", ")", "parseRecord", "(", ")", "(", "fields", "[", "]", "string", ",", "err", "error", ")", "{", "r", ".", "line", "++", "\n", "r", ".", "column", "=", "-", "1", "\n", "r1", ",", "_", ",", "err", ":=", "r", ".", "r", ".", "ReadRune", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "r", ".", "Comment", "!=", "0", "&&", "r1", "==", "r", ".", "Comment", "{", "return", "nil", ",", "r", ".", "skip", "(", "'\\n'", ")", "\n", "}", "\n", "r", ".", "r", ".", "UnreadRune", "(", ")", "\n", "for", "{", "haveField", ",", "delim", ",", "err", ":=", "r", ".", "parseField", "(", ")", "\n", "if", "haveField", "{", "fields", "=", "append", "(", "fields", ",", "r", ".", "field", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "delim", "==", "'\\n'", "||", "err", "==", "io", ".", "EOF", "{", "return", "fields", ",", "err", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}" ]
// parseRecord reads and parses a single csv record from r.
[ "parseRecord", "reads", "and", "parses", "a", "single", "csv", "record", "from", "r", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/plugins/file/csv/generic_csv_reader.go#L215-L248
train
chrislusf/gleam
sql/expression/scalar_function.go
NewFunction
func NewFunction(ctx context.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) { fc, ok := funcs[funcName] if !ok { return nil, errFunctionNotExists.GenByArgs(funcName) } funcArgs := make([]Expression, len(args)) copy(funcArgs, args) f, err := fc.getFunction(funcArgs, ctx) if err != nil { return nil, errors.Trace(err) } return &ScalarFunction{ FuncName: model.NewCIStr(funcName), RetType: retType, Function: f, }, nil }
go
func NewFunction(ctx context.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) { fc, ok := funcs[funcName] if !ok { return nil, errFunctionNotExists.GenByArgs(funcName) } funcArgs := make([]Expression, len(args)) copy(funcArgs, args) f, err := fc.getFunction(funcArgs, ctx) if err != nil { return nil, errors.Trace(err) } return &ScalarFunction{ FuncName: model.NewCIStr(funcName), RetType: retType, Function: f, }, nil }
[ "func", "NewFunction", "(", "ctx", "context", ".", "Context", ",", "funcName", "string", ",", "retType", "*", "types", ".", "FieldType", ",", "args", "...", "Expression", ")", "(", "Expression", ",", "error", ")", "{", "fc", ",", "ok", ":=", "funcs", "[", "funcName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errFunctionNotExists", ".", "GenByArgs", "(", "funcName", ")", "\n", "}", "\n", "funcArgs", ":=", "make", "(", "[", "]", "Expression", ",", "len", "(", "args", ")", ")", "\n", "copy", "(", "funcArgs", ",", "args", ")", "\n", "f", ",", "err", ":=", "fc", ".", "getFunction", "(", "funcArgs", ",", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "&", "ScalarFunction", "{", "FuncName", ":", "model", ".", "NewCIStr", "(", "funcName", ")", ",", "RetType", ":", "retType", ",", "Function", ":", "f", ",", "}", ",", "nil", "\n", "}" ]
// NewFunction creates a new scalar function or constant.
[ "NewFunction", "creates", "a", "new", "scalar", "function", "or", "constant", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/scalar_function.go#L65-L81
train
chrislusf/gleam
distributed/driver/scheduler/market/cda_market.go
AddDemand
func (m *Market) AddDemand(r Requirement, bid float64, retChan chan Supply) { m.Lock.Lock() defer m.Lock.Unlock() if len(m.Supplies) > 0 { supply, matched := m.pickBestSupplyFor(r) if matched { retChan <- supply close(retChan) return } } m.Demands = append(m.Demands, Demand{ Requirement: r, Bid: bid, ReturnChan: retChan, }) m.hasDemands.Signal() }
go
func (m *Market) AddDemand(r Requirement, bid float64, retChan chan Supply) { m.Lock.Lock() defer m.Lock.Unlock() if len(m.Supplies) > 0 { supply, matched := m.pickBestSupplyFor(r) if matched { retChan <- supply close(retChan) return } } m.Demands = append(m.Demands, Demand{ Requirement: r, Bid: bid, ReturnChan: retChan, }) m.hasDemands.Signal() }
[ "func", "(", "m", "*", "Market", ")", "AddDemand", "(", "r", "Requirement", ",", "bid", "float64", ",", "retChan", "chan", "Supply", ")", "{", "m", ".", "Lock", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Lock", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "m", ".", "Supplies", ")", ">", "0", "{", "supply", ",", "matched", ":=", "m", ".", "pickBestSupplyFor", "(", "r", ")", "\n", "if", "matched", "{", "retChan", "<-", "supply", "\n", "close", "(", "retChan", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "m", ".", "Demands", "=", "append", "(", "m", ".", "Demands", ",", "Demand", "{", "Requirement", ":", "r", ",", "Bid", ":", "bid", ",", "ReturnChan", ":", "retChan", ",", "}", ")", "\n", "m", ".", "hasDemands", ".", "Signal", "(", ")", "\n", "}" ]
// retChan should be a buffered channel
[ "retChan", "should", "be", "a", "buffered", "channel" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/driver/scheduler/market/cda_market.go#L63-L81
train
chrislusf/gleam
util/printf.go
TsvPrintf
func TsvPrintf(writer io.Writer, reader io.Reader, format string) error { return TakeTsv(reader, -1, func(args []string) error { var objects []interface{} for _, arg := range args { objects = append(objects, arg) } if len(objects) > 0 { _, err := fmt.Fprintf(writer, format, objects...) return err } return nil }) }
go
func TsvPrintf(writer io.Writer, reader io.Reader, format string) error { return TakeTsv(reader, -1, func(args []string) error { var objects []interface{} for _, arg := range args { objects = append(objects, arg) } if len(objects) > 0 { _, err := fmt.Fprintf(writer, format, objects...) return err } return nil }) }
[ "func", "TsvPrintf", "(", "writer", "io", ".", "Writer", ",", "reader", "io", ".", "Reader", ",", "format", "string", ")", "error", "{", "return", "TakeTsv", "(", "reader", ",", "-", "1", ",", "func", "(", "args", "[", "]", "string", ")", "error", "{", "var", "objects", "[", "]", "interface", "{", "}", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "objects", "=", "append", "(", "objects", ",", "arg", ")", "\n", "}", "\n", "if", "len", "(", "objects", ")", ">", "0", "{", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "writer", ",", "format", ",", "objects", "...", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// TsvPrintf reads TSV lines from reader, // and formats according to a format specifier and writes to writer.
[ "TsvPrintf", "reads", "TSV", "lines", "from", "reader", "and", "formats", "according", "to", "a", "format", "specifier", "and", "writes", "to", "writer", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/printf.go#L12-L24
train
chrislusf/gleam
util/printf.go
Fprintf
func Fprintf(writer io.Writer, reader io.Reader, format string) error { return ProcessMessage(reader, func(encodedBytes []byte) error { var decodedObjects []interface{} var row *Row var err error // fmt.Printf("chan input encoded: %s\n", string(encodedBytes)) if row, err = DecodeRow(encodedBytes); err != nil { return fmt.Errorf("Failed to decode byte: %v\n", err) } decodedObjects = append(decodedObjects, row.K...) decodedObjects = append(decodedObjects, row.V...) fmt.Fprintf(writer, format, decodedObjects...) return nil }) }
go
func Fprintf(writer io.Writer, reader io.Reader, format string) error { return ProcessMessage(reader, func(encodedBytes []byte) error { var decodedObjects []interface{} var row *Row var err error // fmt.Printf("chan input encoded: %s\n", string(encodedBytes)) if row, err = DecodeRow(encodedBytes); err != nil { return fmt.Errorf("Failed to decode byte: %v\n", err) } decodedObjects = append(decodedObjects, row.K...) decodedObjects = append(decodedObjects, row.V...) fmt.Fprintf(writer, format, decodedObjects...) return nil }) }
[ "func", "Fprintf", "(", "writer", "io", ".", "Writer", ",", "reader", "io", ".", "Reader", ",", "format", "string", ")", "error", "{", "return", "ProcessMessage", "(", "reader", ",", "func", "(", "encodedBytes", "[", "]", "byte", ")", "error", "{", "var", "decodedObjects", "[", "]", "interface", "{", "}", "\n", "var", "row", "*", "Row", "\n", "var", "err", "error", "\n", "if", "row", ",", "err", "=", "DecodeRow", "(", "encodedBytes", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to decode byte: %v\\n\"", ",", "\\n", ")", "\n", "}", "\n", "err", "\n", "decodedObjects", "=", "append", "(", "decodedObjects", ",", "row", ".", "K", "...", ")", "\n", "decodedObjects", "=", "append", "(", "decodedObjects", ",", "row", ".", "V", "...", ")", "\n", "fmt", ".", "Fprintf", "(", "writer", ",", "format", ",", "decodedObjects", "...", ")", "\n", "}", ")", "\n", "}" ]
// Fprintf reads MessagePack encoded messages from reader, // and formats according to a format specifier and writes to writer.
[ "Fprintf", "reads", "MessagePack", "encoded", "messages", "from", "reader", "and", "formats", "according", "to", "a", "format", "specifier", "and", "writes", "to", "writer", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/printf.go#L28-L45
train
chrislusf/gleam
util/printf.go
PrintDelimited
func PrintDelimited(stat *pb.InstructionStat, reader io.Reader, writer io.Writer, delimiter string, lineSperator string) error { return ProcessMessage(reader, func(encodedBytes []byte) error { var row *Row var err error // fmt.Printf("chan input encoded: %s\n", string(encodedBytes)) if row, err = DecodeRow(encodedBytes); err != nil { return fmt.Errorf("Failed to decode byte: %v", err) } stat.InputCounter++ var written = 0 // fmt.Printf("> len=%d row:%s\n", len(decodedObjects), decodedObjects[0]) if written, err = fprintRow(writer, 0, delimiter, row.K...); err != nil { return fmt.Errorf("Failed to write row: %v", err) } if _, err := fprintRow(writer, written, delimiter, row.V...); err != nil { return fmt.Errorf("Failed to write row: %v", err) } if _, err := writer.Write([]byte("\n")); err != nil { return fmt.Errorf("Failed to write line separator: %v", err) } stat.OutputCounter++ return nil }) }
go
func PrintDelimited(stat *pb.InstructionStat, reader io.Reader, writer io.Writer, delimiter string, lineSperator string) error { return ProcessMessage(reader, func(encodedBytes []byte) error { var row *Row var err error // fmt.Printf("chan input encoded: %s\n", string(encodedBytes)) if row, err = DecodeRow(encodedBytes); err != nil { return fmt.Errorf("Failed to decode byte: %v", err) } stat.InputCounter++ var written = 0 // fmt.Printf("> len=%d row:%s\n", len(decodedObjects), decodedObjects[0]) if written, err = fprintRow(writer, 0, delimiter, row.K...); err != nil { return fmt.Errorf("Failed to write row: %v", err) } if _, err := fprintRow(writer, written, delimiter, row.V...); err != nil { return fmt.Errorf("Failed to write row: %v", err) } if _, err := writer.Write([]byte("\n")); err != nil { return fmt.Errorf("Failed to write line separator: %v", err) } stat.OutputCounter++ return nil }) }
[ "func", "PrintDelimited", "(", "stat", "*", "pb", ".", "InstructionStat", ",", "reader", "io", ".", "Reader", ",", "writer", "io", ".", "Writer", ",", "delimiter", "string", ",", "lineSperator", "string", ")", "error", "{", "return", "ProcessMessage", "(", "reader", ",", "func", "(", "encodedBytes", "[", "]", "byte", ")", "error", "{", "var", "row", "*", "Row", "\n", "var", "err", "error", "\n", "if", "row", ",", "err", "=", "DecodeRow", "(", "encodedBytes", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to decode byte: %v\"", ",", "err", ")", "\n", "}", "\n", "stat", ".", "InputCounter", "++", "\n", "var", "written", "=", "0", "\n", "if", "written", ",", "err", "=", "fprintRow", "(", "writer", ",", "0", ",", "delimiter", ",", "row", ".", "K", "...", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to write row: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "fprintRow", "(", "writer", ",", "written", ",", "delimiter", ",", "row", ".", "V", "...", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to write row: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "writer", ".", "Write", "(", "[", "]", "byte", "(", "\"\\n\"", ")", ")", ";", "\\n", "err", "!=", "nil", "\n", "{", "return", "fmt", ".", "Errorf", "(", "\"Failed to write line separator: %v\"", ",", "err", ")", "\n", "}", "\n", "stat", ".", "OutputCounter", "++", "\n", "}", ")", "\n", "}" ]
// PrintDelimited Reads and formats MessagePack encoded messages // with delimiter and lineSeparator.
[ "PrintDelimited", "Reads", "and", "formats", "MessagePack", "encoded", "messages", "with", "delimiter", "and", "lineSeparator", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/printf.go#L49-L75
train
chrislusf/gleam
sql/plan/match_property.go
matchPropColumn
func matchPropColumn(prop *requiredProperty, matchedIdx int, idxCol *model.IndexColumn) int { if matchedIdx < prop.sortKeyLen { // When walking through the first sorKeyLen column, // we should make sure to match them as the columns order exactly. // So we must check the column in position of matchedIdx. propCol := prop.props[matchedIdx] if idxCol.Name.L == propCol.col.ColName.L { return matchedIdx } } else { // When walking outside the first sorKeyLen column, we can match the columns as any order. for j, propCol := range prop.props { if idxCol.Name.L == propCol.col.ColName.L { return j } } } return -1 }
go
func matchPropColumn(prop *requiredProperty, matchedIdx int, idxCol *model.IndexColumn) int { if matchedIdx < prop.sortKeyLen { // When walking through the first sorKeyLen column, // we should make sure to match them as the columns order exactly. // So we must check the column in position of matchedIdx. propCol := prop.props[matchedIdx] if idxCol.Name.L == propCol.col.ColName.L { return matchedIdx } } else { // When walking outside the first sorKeyLen column, we can match the columns as any order. for j, propCol := range prop.props { if idxCol.Name.L == propCol.col.ColName.L { return j } } } return -1 }
[ "func", "matchPropColumn", "(", "prop", "*", "requiredProperty", ",", "matchedIdx", "int", ",", "idxCol", "*", "model", ".", "IndexColumn", ")", "int", "{", "if", "matchedIdx", "<", "prop", ".", "sortKeyLen", "{", "propCol", ":=", "prop", ".", "props", "[", "matchedIdx", "]", "\n", "if", "idxCol", ".", "Name", ".", "L", "==", "propCol", ".", "col", ".", "ColName", ".", "L", "{", "return", "matchedIdx", "\n", "}", "\n", "}", "else", "{", "for", "j", ",", "propCol", ":=", "range", "prop", ".", "props", "{", "if", "idxCol", ".", "Name", ".", "L", "==", "propCol", ".", "col", ".", "ColName", ".", "L", "{", "return", "j", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// matchPropColumn checks if the idxCol match one of columns in required property and return the matched index. // If no column is matched, return -1.
[ "matchPropColumn", "checks", "if", "the", "idxCol", "match", "one", "of", "columns", "in", "required", "property", "and", "return", "the", "matched", "index", ".", "If", "no", "column", "is", "matched", "return", "-", "1", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/match_property.go#L79-L97
train
chrislusf/gleam
sql/util/types/datum.go
SetRow
func (d *Datum) SetRow(ds []Datum) { d.k = KindRow d.x = ds }
go
func (d *Datum) SetRow(ds []Datum) { d.k = KindRow d.x = ds }
[ "func", "(", "d", "*", "Datum", ")", "SetRow", "(", "ds", "[", "]", "Datum", ")", "{", "d", ".", "k", "=", "KindRow", "\n", "d", ".", "x", "=", "ds", "\n", "}" ]
// SetRow sets row value.
[ "SetRow", "sets", "row", "value", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L198-L201
train
chrislusf/gleam
sql/util/types/datum.go
GetMysqlBit
func (d *Datum) GetMysqlBit() Bit { width := int(d.length) value := uint64(d.i) return Bit{Value: value, Width: width} }
go
func (d *Datum) GetMysqlBit() Bit { width := int(d.length) value := uint64(d.i) return Bit{Value: value, Width: width} }
[ "func", "(", "d", "*", "Datum", ")", "GetMysqlBit", "(", ")", "Bit", "{", "width", ":=", "int", "(", "d", ".", "length", ")", "\n", "value", ":=", "uint64", "(", "d", ".", "i", ")", "\n", "return", "Bit", "{", "Value", ":", "value", ",", "Width", ":", "width", "}", "\n", "}" ]
// GetMysqlBit gets Bit value
[ "GetMysqlBit", "gets", "Bit", "value" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L210-L214
train
chrislusf/gleam
sql/util/types/datum.go
SetMysqlBit
func (d *Datum) SetMysqlBit(b Bit) { d.k = KindMysqlBit d.length = uint32(b.Width) d.i = int64(b.Value) }
go
func (d *Datum) SetMysqlBit(b Bit) { d.k = KindMysqlBit d.length = uint32(b.Width) d.i = int64(b.Value) }
[ "func", "(", "d", "*", "Datum", ")", "SetMysqlBit", "(", "b", "Bit", ")", "{", "d", ".", "k", "=", "KindMysqlBit", "\n", "d", ".", "length", "=", "uint32", "(", "b", ".", "Width", ")", "\n", "d", ".", "i", "=", "int64", "(", "b", ".", "Value", ")", "\n", "}" ]
// SetMysqlBit sets Bit value
[ "SetMysqlBit", "sets", "Bit", "value" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L217-L221
train
chrislusf/gleam
sql/util/types/datum.go
GetMysqlEnum
func (d *Datum) GetMysqlEnum() Enum { return Enum{Value: uint64(d.i), Name: hack.String(d.b)} }
go
func (d *Datum) GetMysqlEnum() Enum { return Enum{Value: uint64(d.i), Name: hack.String(d.b)} }
[ "func", "(", "d", "*", "Datum", ")", "GetMysqlEnum", "(", ")", "Enum", "{", "return", "Enum", "{", "Value", ":", "uint64", "(", "d", ".", "i", ")", ",", "Name", ":", "hack", ".", "String", "(", "d", ".", "b", ")", "}", "\n", "}" ]
// GetMysqlEnum gets Enum value
[ "GetMysqlEnum", "gets", "Enum", "value" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L247-L249
train
chrislusf/gleam
sql/util/types/datum.go
SetMysqlHex
func (d *Datum) SetMysqlHex(b Hex) { d.k = KindMysqlHex d.i = b.Value }
go
func (d *Datum) SetMysqlHex(b Hex) { d.k = KindMysqlHex d.i = b.Value }
[ "func", "(", "d", "*", "Datum", ")", "SetMysqlHex", "(", "b", "Hex", ")", "{", "d", ".", "k", "=", "KindMysqlHex", "\n", "d", ".", "i", "=", "b", ".", "Value", "\n", "}" ]
// SetMysqlHex sets Hex value
[ "SetMysqlHex", "sets", "Hex", "value" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L265-L268
train
chrislusf/gleam
sql/util/types/datum.go
Cast
func (d *Datum) Cast(sc *variable.StatementContext, target *FieldType) (ad Datum, err error) { if !isCastType(target.Tp) { return ad, errors.Errorf("unknown cast type - %v", target) } return d.ConvertTo(sc, target) }
go
func (d *Datum) Cast(sc *variable.StatementContext, target *FieldType) (ad Datum, err error) { if !isCastType(target.Tp) { return ad, errors.Errorf("unknown cast type - %v", target) } return d.ConvertTo(sc, target) }
[ "func", "(", "d", "*", "Datum", ")", "Cast", "(", "sc", "*", "variable", ".", "StatementContext", ",", "target", "*", "FieldType", ")", "(", "ad", "Datum", ",", "err", "error", ")", "{", "if", "!", "isCastType", "(", "target", ".", "Tp", ")", "{", "return", "ad", ",", "errors", ".", "Errorf", "(", "\"unknown cast type - %v\"", ",", "target", ")", "\n", "}", "\n", "return", "d", ".", "ConvertTo", "(", "sc", ",", "target", ")", "\n", "}" ]
// Cast casts datum to certain types.
[ "Cast", "casts", "datum", "to", "certain", "types", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L636-L641
train
chrislusf/gleam
sql/util/types/datum.go
ToString
func (d *Datum) ToString() (string, error) { switch d.Kind() { case KindInt64: return strconv.FormatInt(d.GetInt64(), 10), nil case KindUint64: return strconv.FormatUint(d.GetUint64(), 10), nil case KindFloat32: return strconv.FormatFloat(float64(d.GetFloat32()), 'f', -1, 32), nil case KindFloat64: return strconv.FormatFloat(float64(d.GetFloat64()), 'f', -1, 64), nil case KindString: return d.GetString(), nil case KindBytes: return d.GetString(), nil case KindMysqlTime: return d.GetMysqlTime().String(), nil case KindMysqlDuration: return d.GetMysqlDuration().String(), nil case KindMysqlDecimal: return d.GetMysqlDecimal().String(), nil case KindMysqlHex: return d.GetMysqlHex().ToString(), nil case KindMysqlBit: return d.GetMysqlBit().ToString(), nil case KindMysqlEnum: return d.GetMysqlEnum().String(), nil case KindMysqlSet: return d.GetMysqlSet().String(), nil default: return "", errors.Errorf("cannot convert %v(type %T) to string", d.GetValue(), d.GetValue()) } }
go
func (d *Datum) ToString() (string, error) { switch d.Kind() { case KindInt64: return strconv.FormatInt(d.GetInt64(), 10), nil case KindUint64: return strconv.FormatUint(d.GetUint64(), 10), nil case KindFloat32: return strconv.FormatFloat(float64(d.GetFloat32()), 'f', -1, 32), nil case KindFloat64: return strconv.FormatFloat(float64(d.GetFloat64()), 'f', -1, 64), nil case KindString: return d.GetString(), nil case KindBytes: return d.GetString(), nil case KindMysqlTime: return d.GetMysqlTime().String(), nil case KindMysqlDuration: return d.GetMysqlDuration().String(), nil case KindMysqlDecimal: return d.GetMysqlDecimal().String(), nil case KindMysqlHex: return d.GetMysqlHex().ToString(), nil case KindMysqlBit: return d.GetMysqlBit().ToString(), nil case KindMysqlEnum: return d.GetMysqlEnum().String(), nil case KindMysqlSet: return d.GetMysqlSet().String(), nil default: return "", errors.Errorf("cannot convert %v(type %T) to string", d.GetValue(), d.GetValue()) } }
[ "func", "(", "d", "*", "Datum", ")", "ToString", "(", ")", "(", "string", ",", "error", ")", "{", "switch", "d", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "return", "strconv", ".", "FormatInt", "(", "d", ".", "GetInt64", "(", ")", ",", "10", ")", ",", "nil", "\n", "case", "KindUint64", ":", "return", "strconv", ".", "FormatUint", "(", "d", ".", "GetUint64", "(", ")", ",", "10", ")", ",", "nil", "\n", "case", "KindFloat32", ":", "return", "strconv", ".", "FormatFloat", "(", "float64", "(", "d", ".", "GetFloat32", "(", ")", ")", ",", "'f'", ",", "-", "1", ",", "32", ")", ",", "nil", "\n", "case", "KindFloat64", ":", "return", "strconv", ".", "FormatFloat", "(", "float64", "(", "d", ".", "GetFloat64", "(", ")", ")", ",", "'f'", ",", "-", "1", ",", "64", ")", ",", "nil", "\n", "case", "KindString", ":", "return", "d", ".", "GetString", "(", ")", ",", "nil", "\n", "case", "KindBytes", ":", "return", "d", ".", "GetString", "(", ")", ",", "nil", "\n", "case", "KindMysqlTime", ":", "return", "d", ".", "GetMysqlTime", "(", ")", ".", "String", "(", ")", ",", "nil", "\n", "case", "KindMysqlDuration", ":", "return", "d", ".", "GetMysqlDuration", "(", ")", ".", "String", "(", ")", ",", "nil", "\n", "case", "KindMysqlDecimal", ":", "return", "d", ".", "GetMysqlDecimal", "(", ")", ".", "String", "(", ")", ",", "nil", "\n", "case", "KindMysqlHex", ":", "return", "d", ".", "GetMysqlHex", "(", ")", ".", "ToString", "(", ")", ",", "nil", "\n", "case", "KindMysqlBit", ":", "return", "d", ".", "GetMysqlBit", "(", ")", ".", "ToString", "(", ")", ",", "nil", "\n", "case", "KindMysqlEnum", ":", "return", "d", ".", "GetMysqlEnum", "(", ")", ".", "String", "(", ")", ",", "nil", "\n", "case", "KindMysqlSet", ":", "return", "d", ".", "GetMysqlSet", "(", ")", ".", "String", "(", ")", ",", "nil", "\n", "default", ":", "return", "\"\"", ",", "errors", ".", "Errorf", "(", "\"cannot convert %v(type %T) to string\"", ",", "d", ".", "GetValue", "(", ")", ",", "d", ".", "GetValue", "(", ")", ")", "\n", "}", "\n", "}" ]
// ToString gets the string representation of the datum.
[ "ToString", "gets", "the", "string", "representation", "of", "the", "datum", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L1299-L1330
train
chrislusf/gleam
sql/util/types/datum.go
CoerceDatum
func CoerceDatum(sc *variable.StatementContext, a, b Datum) (x, y Datum, err error) { if a.IsNull() || b.IsNull() { return x, y, nil } var ( hasUint bool hasDecimal bool hasFloat bool ) x = a.convergeType(&hasUint, &hasDecimal, &hasFloat) y = b.convergeType(&hasUint, &hasDecimal, &hasFloat) if hasFloat { switch x.Kind() { case KindInt64: x.SetFloat64(float64(x.GetInt64())) case KindUint64: x.SetFloat64(float64(x.GetUint64())) case KindMysqlHex: x.SetFloat64(x.GetMysqlHex().ToNumber()) case KindMysqlBit: x.SetFloat64(x.GetMysqlBit().ToNumber()) case KindMysqlEnum: x.SetFloat64(x.GetMysqlEnum().ToNumber()) case KindMysqlSet: x.SetFloat64(x.GetMysqlSet().ToNumber()) case KindMysqlDecimal: fval, err := x.ToFloat64(sc) if err != nil { return x, y, errors.Trace(err) } x.SetFloat64(fval) } switch y.Kind() { case KindInt64: y.SetFloat64(float64(y.GetInt64())) case KindUint64: y.SetFloat64(float64(y.GetUint64())) case KindMysqlHex: y.SetFloat64(y.GetMysqlHex().ToNumber()) case KindMysqlBit: y.SetFloat64(y.GetMysqlBit().ToNumber()) case KindMysqlEnum: y.SetFloat64(y.GetMysqlEnum().ToNumber()) case KindMysqlSet: y.SetFloat64(y.GetMysqlSet().ToNumber()) case KindMysqlDecimal: fval, err := y.ToFloat64(sc) if err != nil { return x, y, errors.Trace(err) } y.SetFloat64(fval) } } else if hasDecimal { var dec *MyDecimal dec, err = ConvertDatumToDecimal(sc, x) if err != nil { return x, y, errors.Trace(err) } x.SetMysqlDecimal(dec) dec, err = ConvertDatumToDecimal(sc, y) if err != nil { return x, y, errors.Trace(err) } y.SetMysqlDecimal(dec) } return }
go
func CoerceDatum(sc *variable.StatementContext, a, b Datum) (x, y Datum, err error) { if a.IsNull() || b.IsNull() { return x, y, nil } var ( hasUint bool hasDecimal bool hasFloat bool ) x = a.convergeType(&hasUint, &hasDecimal, &hasFloat) y = b.convergeType(&hasUint, &hasDecimal, &hasFloat) if hasFloat { switch x.Kind() { case KindInt64: x.SetFloat64(float64(x.GetInt64())) case KindUint64: x.SetFloat64(float64(x.GetUint64())) case KindMysqlHex: x.SetFloat64(x.GetMysqlHex().ToNumber()) case KindMysqlBit: x.SetFloat64(x.GetMysqlBit().ToNumber()) case KindMysqlEnum: x.SetFloat64(x.GetMysqlEnum().ToNumber()) case KindMysqlSet: x.SetFloat64(x.GetMysqlSet().ToNumber()) case KindMysqlDecimal: fval, err := x.ToFloat64(sc) if err != nil { return x, y, errors.Trace(err) } x.SetFloat64(fval) } switch y.Kind() { case KindInt64: y.SetFloat64(float64(y.GetInt64())) case KindUint64: y.SetFloat64(float64(y.GetUint64())) case KindMysqlHex: y.SetFloat64(y.GetMysqlHex().ToNumber()) case KindMysqlBit: y.SetFloat64(y.GetMysqlBit().ToNumber()) case KindMysqlEnum: y.SetFloat64(y.GetMysqlEnum().ToNumber()) case KindMysqlSet: y.SetFloat64(y.GetMysqlSet().ToNumber()) case KindMysqlDecimal: fval, err := y.ToFloat64(sc) if err != nil { return x, y, errors.Trace(err) } y.SetFloat64(fval) } } else if hasDecimal { var dec *MyDecimal dec, err = ConvertDatumToDecimal(sc, x) if err != nil { return x, y, errors.Trace(err) } x.SetMysqlDecimal(dec) dec, err = ConvertDatumToDecimal(sc, y) if err != nil { return x, y, errors.Trace(err) } y.SetMysqlDecimal(dec) } return }
[ "func", "CoerceDatum", "(", "sc", "*", "variable", ".", "StatementContext", ",", "a", ",", "b", "Datum", ")", "(", "x", ",", "y", "Datum", ",", "err", "error", ")", "{", "if", "a", ".", "IsNull", "(", ")", "||", "b", ".", "IsNull", "(", ")", "{", "return", "x", ",", "y", ",", "nil", "\n", "}", "\n", "var", "(", "hasUint", "bool", "\n", "hasDecimal", "bool", "\n", "hasFloat", "bool", "\n", ")", "\n", "x", "=", "a", ".", "convergeType", "(", "&", "hasUint", ",", "&", "hasDecimal", ",", "&", "hasFloat", ")", "\n", "y", "=", "b", ".", "convergeType", "(", "&", "hasUint", ",", "&", "hasDecimal", ",", "&", "hasFloat", ")", "\n", "if", "hasFloat", "{", "switch", "x", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "x", ".", "SetFloat64", "(", "float64", "(", "x", ".", "GetInt64", "(", ")", ")", ")", "\n", "case", "KindUint64", ":", "x", ".", "SetFloat64", "(", "float64", "(", "x", ".", "GetUint64", "(", ")", ")", ")", "\n", "case", "KindMysqlHex", ":", "x", ".", "SetFloat64", "(", "x", ".", "GetMysqlHex", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlBit", ":", "x", ".", "SetFloat64", "(", "x", ".", "GetMysqlBit", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlEnum", ":", "x", ".", "SetFloat64", "(", "x", ".", "GetMysqlEnum", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlSet", ":", "x", ".", "SetFloat64", "(", "x", ".", "GetMysqlSet", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlDecimal", ":", "fval", ",", "err", ":=", "x", ".", "ToFloat64", "(", "sc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "x", ",", "y", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "x", ".", "SetFloat64", "(", "fval", ")", "\n", "}", "\n", "switch", "y", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "y", ".", "SetFloat64", "(", "float64", "(", "y", ".", "GetInt64", "(", ")", ")", ")", "\n", "case", "KindUint64", ":", "y", ".", "SetFloat64", "(", "float64", "(", "y", ".", "GetUint64", "(", ")", ")", ")", "\n", "case", "KindMysqlHex", ":", "y", ".", "SetFloat64", "(", "y", ".", "GetMysqlHex", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlBit", ":", "y", ".", "SetFloat64", "(", "y", ".", "GetMysqlBit", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlEnum", ":", "y", ".", "SetFloat64", "(", "y", ".", "GetMysqlEnum", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlSet", ":", "y", ".", "SetFloat64", "(", "y", ".", "GetMysqlSet", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "case", "KindMysqlDecimal", ":", "fval", ",", "err", ":=", "y", ".", "ToFloat64", "(", "sc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "x", ",", "y", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "y", ".", "SetFloat64", "(", "fval", ")", "\n", "}", "\n", "}", "else", "if", "hasDecimal", "{", "var", "dec", "*", "MyDecimal", "\n", "dec", ",", "err", "=", "ConvertDatumToDecimal", "(", "sc", ",", "x", ")", "\n", "if", "err", "!=", "nil", "{", "return", "x", ",", "y", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "x", ".", "SetMysqlDecimal", "(", "dec", ")", "\n", "dec", ",", "err", "=", "ConvertDatumToDecimal", "(", "sc", ",", "y", ")", "\n", "if", "err", "!=", "nil", "{", "return", "x", ",", "y", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "y", ".", "SetMysqlDecimal", "(", "dec", ")", "\n", "}", "\n", "return", "\n", "}" ]
// 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.
[ "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", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L1357-L1423
train
chrislusf/gleam
sql/util/types/datum.go
DatumsToInterfaces
func DatumsToInterfaces(datums []Datum) []interface{} { ins := make([]interface{}, len(datums)) for i, v := range datums { ins[i] = v.GetValue() } return ins }
go
func DatumsToInterfaces(datums []Datum) []interface{} { ins := make([]interface{}, len(datums)) for i, v := range datums { ins[i] = v.GetValue() } return ins }
[ "func", "DatumsToInterfaces", "(", "datums", "[", "]", "Datum", ")", "[", "]", "interface", "{", "}", "{", "ins", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "datums", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "datums", "{", "ins", "[", "i", "]", "=", "v", ".", "GetValue", "(", ")", "\n", "}", "\n", "return", "ins", "\n", "}" ]
// DatumsToInterfaces converts a datum slice to interface slice.
[ "DatumsToInterfaces", "converts", "a", "datum", "slice", "to", "interface", "slice", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L1494-L1500
train
chrislusf/gleam
sql/util/types/datum.go
SortDatums
func SortDatums(sc *variable.StatementContext, datums []Datum) error { sorter := datumsSorter{datums: datums, sc: sc} sort.Sort(&sorter) return sorter.err }
go
func SortDatums(sc *variable.StatementContext, datums []Datum) error { sorter := datumsSorter{datums: datums, sc: sc} sort.Sort(&sorter) return sorter.err }
[ "func", "SortDatums", "(", "sc", "*", "variable", ".", "StatementContext", ",", "datums", "[", "]", "Datum", ")", "error", "{", "sorter", ":=", "datumsSorter", "{", "datums", ":", "datums", ",", "sc", ":", "sc", "}", "\n", "sort", ".", "Sort", "(", "&", "sorter", ")", "\n", "return", "sorter", ".", "err", "\n", "}" ]
// SortDatums sorts a slice of datum.
[ "SortDatums", "sorts", "a", "slice", "of", "datum", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum.go#L1536-L1540
train
chrislusf/gleam
sql/expression/builtin_time.go
errorOrWarning
func errorOrWarning(err error, ctx context.Context) error { sc := ctx.GetSessionVars().StmtCtx // TODO: Use better name, such as sc.IsInsert instead of sc.IgnoreTruncate. if ctx.GetSessionVars().StrictSQLMode && !sc.IgnoreTruncate { return errors.Trace(types.ErrInvalidTimeFormat) } sc.AppendWarning(err) return nil }
go
func errorOrWarning(err error, ctx context.Context) error { sc := ctx.GetSessionVars().StmtCtx // TODO: Use better name, such as sc.IsInsert instead of sc.IgnoreTruncate. if ctx.GetSessionVars().StrictSQLMode && !sc.IgnoreTruncate { return errors.Trace(types.ErrInvalidTimeFormat) } sc.AppendWarning(err) return nil }
[ "func", "errorOrWarning", "(", "err", "error", ",", "ctx", "context", ".", "Context", ")", "error", "{", "sc", ":=", "ctx", ".", "GetSessionVars", "(", ")", ".", "StmtCtx", "\n", "if", "ctx", ".", "GetSessionVars", "(", ")", ".", "StrictSQLMode", "&&", "!", "sc", ".", "IgnoreTruncate", "{", "return", "errors", ".", "Trace", "(", "types", ".", "ErrInvalidTimeFormat", ")", "\n", "}", "\n", "sc", ".", "AppendWarning", "(", "err", ")", "\n", "return", "nil", "\n", "}" ]
// errorOrWarning reports error or warning depend on the context.
[ "errorOrWarning", "reports", "error", "or", "warning", "depend", "on", "the", "context", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/builtin_time.go#L1516-L1524
train
chrislusf/gleam
sql/expression/builtin_other.go
BuiltinValuesFactory
func BuiltinValuesFactory(offset int) BuiltinFunc { return func(_ []types.Datum, ctx context.Context) (d types.Datum, err error) { values := ctx.GetSessionVars().CurrInsertValues if values == nil { err = errors.New("Session current insert values is nil") return } row := values.([]types.Datum) if len(row) > offset { return row[offset], nil } err = errors.Errorf("Session current insert values len %d and column's offset %v don't match", len(row), offset) return } }
go
func BuiltinValuesFactory(offset int) BuiltinFunc { return func(_ []types.Datum, ctx context.Context) (d types.Datum, err error) { values := ctx.GetSessionVars().CurrInsertValues if values == nil { err = errors.New("Session current insert values is nil") return } row := values.([]types.Datum) if len(row) > offset { return row[offset], nil } err = errors.Errorf("Session current insert values len %d and column's offset %v don't match", len(row), offset) return } }
[ "func", "BuiltinValuesFactory", "(", "offset", "int", ")", "BuiltinFunc", "{", "return", "func", "(", "_", "[", "]", "types", ".", "Datum", ",", "ctx", "context", ".", "Context", ")", "(", "d", "types", ".", "Datum", ",", "err", "error", ")", "{", "values", ":=", "ctx", ".", "GetSessionVars", "(", ")", ".", "CurrInsertValues", "\n", "if", "values", "==", "nil", "{", "err", "=", "errors", ".", "New", "(", "\"Session current insert values is nil\"", ")", "\n", "return", "\n", "}", "\n", "row", ":=", "values", ".", "(", "[", "]", "types", ".", "Datum", ")", "\n", "if", "len", "(", "row", ")", ">", "offset", "{", "return", "row", "[", "offset", "]", ",", "nil", "\n", "}", "\n", "err", "=", "errors", ".", "Errorf", "(", "\"Session current insert values len %d and column's offset %v don't match\"", ",", "len", "(", "row", ")", ",", "offset", ")", "\n", "return", "\n", "}", "\n", "}" ]
// BuiltinValuesFactory generates values builtin function.
[ "BuiltinValuesFactory", "generates", "values", "builtin", "function", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/builtin_other.go#L391-L405
train
chrislusf/gleam
instruction/utils.go
newChannelOfValuesWithSameKey
func newChannelOfValuesWithSameKey(name string, sortedChan io.Reader, indexes []int) chan util.Row { writer := make(chan util.Row, 1024) go func() { defer close(writer) firstRow, err := util.ReadRow(sortedChan) if err != nil { if err != io.EOF { fmt.Fprintf(os.Stderr, "%s join read first row error: %v\n", name, err) } return } // fmt.Printf("%s join read len=%d, row: %s\n", name, len(row), row[0]) firstRow.UseKeys(indexes) row := util.Row{ T: firstRow.T, K: firstRow.K, V: []interface{}{firstRow.V}, } for { newRow, err := util.ReadRow(sortedChan) if err != nil { if err != io.EOF { fmt.Fprintf(os.Stderr, "join read row error: %v", err) } break } newRow.UseKeys(indexes) x := util.Compare(row.K, newRow.K) if x == 0 { row.V = append(row.V, newRow.V) } else { writer <- row row.K = newRow.K row.V = []interface{}{newRow.V} } row.T = max(row.T, newRow.T) } writer <- row }() return writer }
go
func newChannelOfValuesWithSameKey(name string, sortedChan io.Reader, indexes []int) chan util.Row { writer := make(chan util.Row, 1024) go func() { defer close(writer) firstRow, err := util.ReadRow(sortedChan) if err != nil { if err != io.EOF { fmt.Fprintf(os.Stderr, "%s join read first row error: %v\n", name, err) } return } // fmt.Printf("%s join read len=%d, row: %s\n", name, len(row), row[0]) firstRow.UseKeys(indexes) row := util.Row{ T: firstRow.T, K: firstRow.K, V: []interface{}{firstRow.V}, } for { newRow, err := util.ReadRow(sortedChan) if err != nil { if err != io.EOF { fmt.Fprintf(os.Stderr, "join read row error: %v", err) } break } newRow.UseKeys(indexes) x := util.Compare(row.K, newRow.K) if x == 0 { row.V = append(row.V, newRow.V) } else { writer <- row row.K = newRow.K row.V = []interface{}{newRow.V} } row.T = max(row.T, newRow.T) } writer <- row }() return writer }
[ "func", "newChannelOfValuesWithSameKey", "(", "name", "string", ",", "sortedChan", "io", ".", "Reader", ",", "indexes", "[", "]", "int", ")", "chan", "util", ".", "Row", "{", "writer", ":=", "make", "(", "chan", "util", ".", "Row", ",", "1024", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "writer", ")", "\n", "firstRow", ",", "err", ":=", "util", ".", "ReadRow", "(", "sortedChan", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"%s join read first row error: %v\\n\"", ",", "\\n", ",", "name", ")", "\n", "}", "\n", "err", "\n", "}", "\n", "return", "\n", "firstRow", ".", "UseKeys", "(", "indexes", ")", "\n", "row", ":=", "util", ".", "Row", "{", "T", ":", "firstRow", ".", "T", ",", "K", ":", "firstRow", ".", "K", ",", "V", ":", "[", "]", "interface", "{", "}", "{", "firstRow", ".", "V", "}", ",", "}", "\n", "for", "{", "newRow", ",", "err", ":=", "util", ".", "ReadRow", "(", "sortedChan", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"join read row error: %v\"", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "newRow", ".", "UseKeys", "(", "indexes", ")", "\n", "x", ":=", "util", ".", "Compare", "(", "row", ".", "K", ",", "newRow", ".", "K", ")", "\n", "if", "x", "==", "0", "{", "row", ".", "V", "=", "append", "(", "row", ".", "V", ",", "newRow", ".", "V", ")", "\n", "}", "else", "{", "writer", "<-", "row", "\n", "row", ".", "K", "=", "newRow", ".", "K", "\n", "row", ".", "V", "=", "[", "]", "interface", "{", "}", "{", "newRow", ".", "V", "}", "\n", "}", "\n", "row", ".", "T", "=", "max", "(", "row", ".", "T", ",", "newRow", ".", "T", ")", "\n", "}", "\n", "}", "writer", "<-", "row", "\n", "(", ")", "\n", "}" ]
// create a channel to aggregate values of the same key // automatically close original sorted channel
[ "create", "a", "channel", "to", "aggregate", "values", "of", "the", "same", "key", "automatically", "close", "original", "sorted", "channel" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/instruction/utils.go#L32-L78
train
chrislusf/gleam
sql/util/printer/printer.go
GetPrintResult
func GetPrintResult(cols []string, datas [][]string) (string, bool) { if !checkValidity(cols, datas) { return "", false } var value []byte maxColLen := getMaxColLen(cols, datas) value = append(value, getPrintDivLine(maxColLen)...) value = append(value, getPrintCol(cols, maxColLen)...) value = append(value, getPrintDivLine(maxColLen)...) value = append(value, getPrintRows(datas, maxColLen)...) value = append(value, getPrintDivLine(maxColLen)...) return string(value), true }
go
func GetPrintResult(cols []string, datas [][]string) (string, bool) { if !checkValidity(cols, datas) { return "", false } var value []byte maxColLen := getMaxColLen(cols, datas) value = append(value, getPrintDivLine(maxColLen)...) value = append(value, getPrintCol(cols, maxColLen)...) value = append(value, getPrintDivLine(maxColLen)...) value = append(value, getPrintRows(datas, maxColLen)...) value = append(value, getPrintDivLine(maxColLen)...) return string(value), true }
[ "func", "GetPrintResult", "(", "cols", "[", "]", "string", ",", "datas", "[", "]", "[", "]", "string", ")", "(", "string", ",", "bool", ")", "{", "if", "!", "checkValidity", "(", "cols", ",", "datas", ")", "{", "return", "\"\"", ",", "false", "\n", "}", "\n", "var", "value", "[", "]", "byte", "\n", "maxColLen", ":=", "getMaxColLen", "(", "cols", ",", "datas", ")", "\n", "value", "=", "append", "(", "value", ",", "getPrintDivLine", "(", "maxColLen", ")", "...", ")", "\n", "value", "=", "append", "(", "value", ",", "getPrintCol", "(", "cols", ",", "maxColLen", ")", "...", ")", "\n", "value", "=", "append", "(", "value", ",", "getPrintDivLine", "(", "maxColLen", ")", "...", ")", "\n", "value", "=", "append", "(", "value", ",", "getPrintRows", "(", "datas", ",", "maxColLen", ")", "...", ")", "\n", "value", "=", "append", "(", "value", ",", "getPrintDivLine", "(", "maxColLen", ")", "...", ")", "\n", "return", "string", "(", "value", ")", ",", "true", "\n", "}" ]
// GetPrintResult gets a result with a formatted string.
[ "GetPrintResult", "gets", "a", "result", "with", "a", "formatted", "string", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/printer/printer.go#L122-L136
train
chrislusf/gleam
sql/expression/helper.go
IsCurrentTimeExpr
func IsCurrentTimeExpr(e ast.ExprNode) bool { x, ok := e.(*ast.FuncCallExpr) if !ok { return false } return x.FnName.L == currentTimestampL }
go
func IsCurrentTimeExpr(e ast.ExprNode) bool { x, ok := e.(*ast.FuncCallExpr) if !ok { return false } return x.FnName.L == currentTimestampL }
[ "func", "IsCurrentTimeExpr", "(", "e", "ast", ".", "ExprNode", ")", "bool", "{", "x", ",", "ok", ":=", "e", ".", "(", "*", "ast", ".", "FuncCallExpr", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "return", "x", ".", "FnName", ".", "L", "==", "currentTimestampL", "\n", "}" ]
// IsCurrentTimeExpr returns whether e is CurrentTimeExpr.
[ "IsCurrentTimeExpr", "returns", "whether", "e", "is", "CurrentTimeExpr", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/helper.go#L129-L135
train
chrislusf/gleam
distributed/plan/plan_physical.go
translateToTaskGroups
func translateToTaskGroups(stepId2StepGroup []*StepGroup) (ret []*TaskGroup) { for _, stepGroup := range stepId2StepGroup { assertSameNumberOfTasks(stepGroup.Steps) count := len(stepGroup.Steps[0].Tasks) // println("dealing with", stepGroup.Steps[0].Name, "tasks:", len(stepGroup.Steps[0].Tasks)) for i := 0; i < count; i++ { tg := NewTaskGroup() for _, step := range stepGroup.Steps { tg.AddTask(step.Tasks[i]) } // depends on the previous step group // MAYBE IMPROVEMENT: depends on a subset of previus shards tg.ParentStepGroup = stepGroup stepGroup.TaskGroups = append(stepGroup.TaskGroups, tg) tg.Id = len(ret) ret = append(ret, tg) } } return }
go
func translateToTaskGroups(stepId2StepGroup []*StepGroup) (ret []*TaskGroup) { for _, stepGroup := range stepId2StepGroup { assertSameNumberOfTasks(stepGroup.Steps) count := len(stepGroup.Steps[0].Tasks) // println("dealing with", stepGroup.Steps[0].Name, "tasks:", len(stepGroup.Steps[0].Tasks)) for i := 0; i < count; i++ { tg := NewTaskGroup() for _, step := range stepGroup.Steps { tg.AddTask(step.Tasks[i]) } // depends on the previous step group // MAYBE IMPROVEMENT: depends on a subset of previus shards tg.ParentStepGroup = stepGroup stepGroup.TaskGroups = append(stepGroup.TaskGroups, tg) tg.Id = len(ret) ret = append(ret, tg) } } return }
[ "func", "translateToTaskGroups", "(", "stepId2StepGroup", "[", "]", "*", "StepGroup", ")", "(", "ret", "[", "]", "*", "TaskGroup", ")", "{", "for", "_", ",", "stepGroup", ":=", "range", "stepId2StepGroup", "{", "assertSameNumberOfTasks", "(", "stepGroup", ".", "Steps", ")", "\n", "count", ":=", "len", "(", "stepGroup", ".", "Steps", "[", "0", "]", ".", "Tasks", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "tg", ":=", "NewTaskGroup", "(", ")", "\n", "for", "_", ",", "step", ":=", "range", "stepGroup", ".", "Steps", "{", "tg", ".", "AddTask", "(", "step", ".", "Tasks", "[", "i", "]", ")", "\n", "}", "\n", "tg", ".", "ParentStepGroup", "=", "stepGroup", "\n", "stepGroup", ".", "TaskGroups", "=", "append", "(", "stepGroup", ".", "TaskGroups", ",", "tg", ")", "\n", "tg", ".", "Id", "=", "len", "(", "ret", ")", "\n", "ret", "=", "append", "(", "ret", ",", "tg", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// group local tasks into one task group
[ "group", "local", "tasks", "into", "one", "task", "group" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/plan/plan_physical.go#L10-L29
train
chrislusf/gleam
sql/plan/planbuilder.go
splitWhere
func splitWhere(where ast.ExprNode) []ast.ExprNode { var conditions []ast.ExprNode switch x := where.(type) { case nil: case *ast.BinaryOperationExpr: if x.Op == opcode.AndAnd { conditions = append(conditions, splitWhere(x.L)...) conditions = append(conditions, splitWhere(x.R)...) } else { conditions = append(conditions, x) } case *ast.ParenthesesExpr: conditions = append(conditions, splitWhere(x.Expr)...) default: conditions = append(conditions, where) } return conditions }
go
func splitWhere(where ast.ExprNode) []ast.ExprNode { var conditions []ast.ExprNode switch x := where.(type) { case nil: case *ast.BinaryOperationExpr: if x.Op == opcode.AndAnd { conditions = append(conditions, splitWhere(x.L)...) conditions = append(conditions, splitWhere(x.R)...) } else { conditions = append(conditions, x) } case *ast.ParenthesesExpr: conditions = append(conditions, splitWhere(x.Expr)...) default: conditions = append(conditions, where) } return conditions }
[ "func", "splitWhere", "(", "where", "ast", ".", "ExprNode", ")", "[", "]", "ast", ".", "ExprNode", "{", "var", "conditions", "[", "]", "ast", ".", "ExprNode", "\n", "switch", "x", ":=", "where", ".", "(", "type", ")", "{", "case", "nil", ":", "case", "*", "ast", ".", "BinaryOperationExpr", ":", "if", "x", ".", "Op", "==", "opcode", ".", "AndAnd", "{", "conditions", "=", "append", "(", "conditions", ",", "splitWhere", "(", "x", ".", "L", ")", "...", ")", "\n", "conditions", "=", "append", "(", "conditions", ",", "splitWhere", "(", "x", ".", "R", ")", "...", ")", "\n", "}", "else", "{", "conditions", "=", "append", "(", "conditions", ",", "x", ")", "\n", "}", "\n", "case", "*", "ast", ".", "ParenthesesExpr", ":", "conditions", "=", "append", "(", "conditions", ",", "splitWhere", "(", "x", ".", "Expr", ")", "...", ")", "\n", "default", ":", "conditions", "=", "append", "(", "conditions", ",", "where", ")", "\n", "}", "\n", "return", "conditions", "\n", "}" ]
// splitWhere split a where expression to a list of AND conditions.
[ "splitWhere", "split", "a", "where", "expression", "to", "a", "list", "of", "AND", "conditions", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/planbuilder.go#L250-L267
train
chrislusf/gleam
sql/util/types/datum_eval.go
CoerceArithmetic
func CoerceArithmetic(sc *variable.StatementContext, a Datum) (d Datum, err error) { switch a.Kind() { case KindString, KindBytes: // MySQL will convert string to float for arithmetic operation f, err := StrToFloat(sc, a.GetString()) if err != nil { return d, errors.Trace(err) } d.SetFloat64(f) return d, errors.Trace(err) case KindMysqlTime: // if time has no precision, return int64 t := a.GetMysqlTime() de := t.ToNumber() if t.Fsp == 0 { iVal, _ := de.ToInt() d.SetInt64(iVal) return d, nil } d.SetMysqlDecimal(de) return d, nil case KindMysqlDuration: // if duration has no precision, return int64 du := a.GetMysqlDuration() de := du.ToNumber() if du.Fsp == 0 { iVal, _ := de.ToInt() d.SetInt64(iVal) return d, nil } d.SetMysqlDecimal(de) return d, nil case KindMysqlHex: d.SetFloat64(a.GetMysqlHex().ToNumber()) return d, nil case KindMysqlBit: d.SetFloat64(a.GetMysqlBit().ToNumber()) return d, nil case KindMysqlEnum: d.SetFloat64(a.GetMysqlEnum().ToNumber()) return d, nil case KindMysqlSet: d.SetFloat64(a.GetMysqlSet().ToNumber()) return d, nil default: return a, nil } }
go
func CoerceArithmetic(sc *variable.StatementContext, a Datum) (d Datum, err error) { switch a.Kind() { case KindString, KindBytes: // MySQL will convert string to float for arithmetic operation f, err := StrToFloat(sc, a.GetString()) if err != nil { return d, errors.Trace(err) } d.SetFloat64(f) return d, errors.Trace(err) case KindMysqlTime: // if time has no precision, return int64 t := a.GetMysqlTime() de := t.ToNumber() if t.Fsp == 0 { iVal, _ := de.ToInt() d.SetInt64(iVal) return d, nil } d.SetMysqlDecimal(de) return d, nil case KindMysqlDuration: // if duration has no precision, return int64 du := a.GetMysqlDuration() de := du.ToNumber() if du.Fsp == 0 { iVal, _ := de.ToInt() d.SetInt64(iVal) return d, nil } d.SetMysqlDecimal(de) return d, nil case KindMysqlHex: d.SetFloat64(a.GetMysqlHex().ToNumber()) return d, nil case KindMysqlBit: d.SetFloat64(a.GetMysqlBit().ToNumber()) return d, nil case KindMysqlEnum: d.SetFloat64(a.GetMysqlEnum().ToNumber()) return d, nil case KindMysqlSet: d.SetFloat64(a.GetMysqlSet().ToNumber()) return d, nil default: return a, nil } }
[ "func", "CoerceArithmetic", "(", "sc", "*", "variable", ".", "StatementContext", ",", "a", "Datum", ")", "(", "d", "Datum", ",", "err", "error", ")", "{", "switch", "a", ".", "Kind", "(", ")", "{", "case", "KindString", ",", "KindBytes", ":", "f", ",", "err", ":=", "StrToFloat", "(", "sc", ",", "a", ".", "GetString", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "d", ".", "SetFloat64", "(", "f", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "case", "KindMysqlTime", ":", "t", ":=", "a", ".", "GetMysqlTime", "(", ")", "\n", "de", ":=", "t", ".", "ToNumber", "(", ")", "\n", "if", "t", ".", "Fsp", "==", "0", "{", "iVal", ",", "_", ":=", "de", ".", "ToInt", "(", ")", "\n", "d", ".", "SetInt64", "(", "iVal", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "d", ".", "SetMysqlDecimal", "(", "de", ")", "\n", "return", "d", ",", "nil", "\n", "case", "KindMysqlDuration", ":", "du", ":=", "a", ".", "GetMysqlDuration", "(", ")", "\n", "de", ":=", "du", ".", "ToNumber", "(", ")", "\n", "if", "du", ".", "Fsp", "==", "0", "{", "iVal", ",", "_", ":=", "de", ".", "ToInt", "(", ")", "\n", "d", ".", "SetInt64", "(", "iVal", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "d", ".", "SetMysqlDecimal", "(", "de", ")", "\n", "return", "d", ",", "nil", "\n", "case", "KindMysqlHex", ":", "d", ".", "SetFloat64", "(", "a", ".", "GetMysqlHex", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "return", "d", ",", "nil", "\n", "case", "KindMysqlBit", ":", "d", ".", "SetFloat64", "(", "a", ".", "GetMysqlBit", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "return", "d", ",", "nil", "\n", "case", "KindMysqlEnum", ":", "d", ".", "SetFloat64", "(", "a", ".", "GetMysqlEnum", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "return", "d", ",", "nil", "\n", "case", "KindMysqlSet", ":", "d", ".", "SetFloat64", "(", "a", ".", "GetMysqlSet", "(", ")", ".", "ToNumber", "(", ")", ")", "\n", "return", "d", ",", "nil", "\n", "default", ":", "return", "a", ",", "nil", "\n", "}", "\n", "}" ]
// CoerceArithmetic converts datum to appropriate datum for arithmetic computing.
[ "CoerceArithmetic", "converts", "datum", "to", "appropriate", "datum", "for", "arithmetic", "computing", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L25-L72
train
chrislusf/gleam
sql/util/types/datum_eval.go
ComputePlus
func ComputePlus(a, b Datum) (d Datum, err error) { switch a.Kind() { case KindInt64: switch b.Kind() { case KindInt64: r, err1 := AddInt64(a.GetInt64(), b.GetInt64()) d.SetInt64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := AddInteger(b.GetUint64(), a.GetInt64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindUint64: switch b.Kind() { case KindInt64: r, err1 := AddInteger(a.GetUint64(), b.GetInt64()) d.SetUint64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := AddUint64(a.GetUint64(), b.GetUint64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindFloat64: switch b.Kind() { case KindFloat64: r := a.GetFloat64() + b.GetFloat64() d.SetFloat64(r) return d, nil } case KindMysqlDecimal: switch b.Kind() { case KindMysqlDecimal: r := new(MyDecimal) err = DecimalAdd(a.GetMysqlDecimal(), b.GetMysqlDecimal(), r) d.SetMysqlDecimal(r) return d, err } } _, err = InvOp2(a.GetValue(), b.GetValue(), opcode.Plus) return d, err }
go
func ComputePlus(a, b Datum) (d Datum, err error) { switch a.Kind() { case KindInt64: switch b.Kind() { case KindInt64: r, err1 := AddInt64(a.GetInt64(), b.GetInt64()) d.SetInt64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := AddInteger(b.GetUint64(), a.GetInt64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindUint64: switch b.Kind() { case KindInt64: r, err1 := AddInteger(a.GetUint64(), b.GetInt64()) d.SetUint64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := AddUint64(a.GetUint64(), b.GetUint64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindFloat64: switch b.Kind() { case KindFloat64: r := a.GetFloat64() + b.GetFloat64() d.SetFloat64(r) return d, nil } case KindMysqlDecimal: switch b.Kind() { case KindMysqlDecimal: r := new(MyDecimal) err = DecimalAdd(a.GetMysqlDecimal(), b.GetMysqlDecimal(), r) d.SetMysqlDecimal(r) return d, err } } _, err = InvOp2(a.GetValue(), b.GetValue(), opcode.Plus) return d, err }
[ "func", "ComputePlus", "(", "a", ",", "b", "Datum", ")", "(", "d", "Datum", ",", "err", "error", ")", "{", "switch", "a", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "r", ",", "err1", ":=", "AddInt64", "(", "a", ".", "GetInt64", "(", ")", ",", "b", ".", "GetInt64", "(", ")", ")", "\n", "d", ".", "SetInt64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "case", "KindUint64", ":", "r", ",", "err1", ":=", "AddInteger", "(", "b", ".", "GetUint64", "(", ")", ",", "a", ".", "GetInt64", "(", ")", ")", "\n", "d", ".", "SetUint64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "}", "\n", "case", "KindUint64", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "r", ",", "err1", ":=", "AddInteger", "(", "a", ".", "GetUint64", "(", ")", ",", "b", ".", "GetInt64", "(", ")", ")", "\n", "d", ".", "SetUint64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "case", "KindUint64", ":", "r", ",", "err1", ":=", "AddUint64", "(", "a", ".", "GetUint64", "(", ")", ",", "b", ".", "GetUint64", "(", ")", ")", "\n", "d", ".", "SetUint64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "}", "\n", "case", "KindFloat64", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindFloat64", ":", "r", ":=", "a", ".", "GetFloat64", "(", ")", "+", "b", ".", "GetFloat64", "(", ")", "\n", "d", ".", "SetFloat64", "(", "r", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "case", "KindMysqlDecimal", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindMysqlDecimal", ":", "r", ":=", "new", "(", "MyDecimal", ")", "\n", "err", "=", "DecimalAdd", "(", "a", ".", "GetMysqlDecimal", "(", ")", ",", "b", ".", "GetMysqlDecimal", "(", ")", ",", "r", ")", "\n", "d", ".", "SetMysqlDecimal", "(", "r", ")", "\n", "return", "d", ",", "err", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "InvOp2", "(", "a", ".", "GetValue", "(", ")", ",", "b", ".", "GetValue", "(", ")", ",", "opcode", ".", "Plus", ")", "\n", "return", "d", ",", "err", "\n", "}" ]
// ComputePlus computes the result of a+b.
[ "ComputePlus", "computes", "the", "result", "of", "a", "+", "b", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L75-L117
train
chrislusf/gleam
sql/util/types/datum_eval.go
ComputeMinus
func ComputeMinus(a, b Datum) (d Datum, err error) { switch a.Kind() { case KindInt64: switch b.Kind() { case KindInt64: r, err1 := SubInt64(a.GetInt64(), b.GetInt64()) d.SetInt64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := SubIntWithUint(a.GetInt64(), b.GetUint64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindUint64: switch b.Kind() { case KindInt64: r, err1 := SubUintWithInt(a.GetUint64(), b.GetInt64()) d.SetUint64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := SubUint64(a.GetUint64(), b.GetUint64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindFloat64: switch b.Kind() { case KindFloat64: r := a.GetFloat64() - b.GetFloat64() d.SetFloat64(r) return d, nil } case KindMysqlDecimal: switch b.Kind() { case KindMysqlDecimal: r := new(MyDecimal) err = DecimalSub(a.GetMysqlDecimal(), b.GetMysqlDecimal(), r) d.SetMysqlDecimal(r) return d, err } } _, err = InvOp2(a.GetValue(), b.GetValue(), opcode.Minus) return d, errors.Trace(err) }
go
func ComputeMinus(a, b Datum) (d Datum, err error) { switch a.Kind() { case KindInt64: switch b.Kind() { case KindInt64: r, err1 := SubInt64(a.GetInt64(), b.GetInt64()) d.SetInt64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := SubIntWithUint(a.GetInt64(), b.GetUint64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindUint64: switch b.Kind() { case KindInt64: r, err1 := SubUintWithInt(a.GetUint64(), b.GetInt64()) d.SetUint64(r) return d, errors.Trace(err1) case KindUint64: r, err1 := SubUint64(a.GetUint64(), b.GetUint64()) d.SetUint64(r) return d, errors.Trace(err1) } case KindFloat64: switch b.Kind() { case KindFloat64: r := a.GetFloat64() - b.GetFloat64() d.SetFloat64(r) return d, nil } case KindMysqlDecimal: switch b.Kind() { case KindMysqlDecimal: r := new(MyDecimal) err = DecimalSub(a.GetMysqlDecimal(), b.GetMysqlDecimal(), r) d.SetMysqlDecimal(r) return d, err } } _, err = InvOp2(a.GetValue(), b.GetValue(), opcode.Minus) return d, errors.Trace(err) }
[ "func", "ComputeMinus", "(", "a", ",", "b", "Datum", ")", "(", "d", "Datum", ",", "err", "error", ")", "{", "switch", "a", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "r", ",", "err1", ":=", "SubInt64", "(", "a", ".", "GetInt64", "(", ")", ",", "b", ".", "GetInt64", "(", ")", ")", "\n", "d", ".", "SetInt64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "case", "KindUint64", ":", "r", ",", "err1", ":=", "SubIntWithUint", "(", "a", ".", "GetInt64", "(", ")", ",", "b", ".", "GetUint64", "(", ")", ")", "\n", "d", ".", "SetUint64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "}", "\n", "case", "KindUint64", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "r", ",", "err1", ":=", "SubUintWithInt", "(", "a", ".", "GetUint64", "(", ")", ",", "b", ".", "GetInt64", "(", ")", ")", "\n", "d", ".", "SetUint64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "case", "KindUint64", ":", "r", ",", "err1", ":=", "SubUint64", "(", "a", ".", "GetUint64", "(", ")", ",", "b", ".", "GetUint64", "(", ")", ")", "\n", "d", ".", "SetUint64", "(", "r", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err1", ")", "\n", "}", "\n", "case", "KindFloat64", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindFloat64", ":", "r", ":=", "a", ".", "GetFloat64", "(", ")", "-", "b", ".", "GetFloat64", "(", ")", "\n", "d", ".", "SetFloat64", "(", "r", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "case", "KindMysqlDecimal", ":", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindMysqlDecimal", ":", "r", ":=", "new", "(", "MyDecimal", ")", "\n", "err", "=", "DecimalSub", "(", "a", ".", "GetMysqlDecimal", "(", ")", ",", "b", ".", "GetMysqlDecimal", "(", ")", ",", "r", ")", "\n", "d", ".", "SetMysqlDecimal", "(", "r", ")", "\n", "return", "d", ",", "err", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "InvOp2", "(", "a", ".", "GetValue", "(", ")", ",", "b", ".", "GetValue", "(", ")", ",", "opcode", ".", "Minus", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// ComputeMinus computes the result of a-b.
[ "ComputeMinus", "computes", "the", "result", "of", "a", "-", "b", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L120-L162
train
chrislusf/gleam
sql/util/types/datum_eval.go
ComputeMod
func ComputeMod(sc *variable.StatementContext, a, b Datum) (d Datum, err error) { switch a.Kind() { case KindInt64: x := a.GetInt64() switch b.Kind() { case KindInt64: y := b.GetInt64() if y == 0 { return d, nil } d.SetInt64(x % y) return d, nil case KindUint64: y := b.GetUint64() if y == 0 { return d, nil } else if x < 0 { d.SetInt64(-int64(uint64(-x) % y)) // first is int64, return int64. return d, nil } d.SetInt64(int64(uint64(x) % y)) return d, nil } case KindUint64: x := a.GetUint64() switch b.Kind() { case KindInt64: y := b.GetInt64() if y == 0 { return d, nil } else if y < 0 { // first is uint64, return uint64. d.SetUint64(uint64(x % uint64(-y))) return d, nil } d.SetUint64(x % uint64(y)) return d, nil case KindUint64: y := b.GetUint64() if y == 0 { return d, nil } d.SetUint64(x % y) return d, nil } case KindFloat64: x := a.GetFloat64() switch b.Kind() { case KindFloat64: y := b.GetFloat64() if y == 0 { return d, nil } d.SetFloat64(math.Mod(x, y)) return d, nil } case KindMysqlDecimal: x := a.GetMysqlDecimal() switch b.Kind() { case KindMysqlDecimal: y := b.GetMysqlDecimal() to := new(MyDecimal) err = DecimalMod(x, y, to) if err != ErrDivByZero { d.SetMysqlDecimal(to) } else { // div by zero returns nil without error. err = nil } return d, err } } _, err = InvOp2(a.GetValue(), b.GetValue(), opcode.Mod) return d, errors.Trace(err) }
go
func ComputeMod(sc *variable.StatementContext, a, b Datum) (d Datum, err error) { switch a.Kind() { case KindInt64: x := a.GetInt64() switch b.Kind() { case KindInt64: y := b.GetInt64() if y == 0 { return d, nil } d.SetInt64(x % y) return d, nil case KindUint64: y := b.GetUint64() if y == 0 { return d, nil } else if x < 0 { d.SetInt64(-int64(uint64(-x) % y)) // first is int64, return int64. return d, nil } d.SetInt64(int64(uint64(x) % y)) return d, nil } case KindUint64: x := a.GetUint64() switch b.Kind() { case KindInt64: y := b.GetInt64() if y == 0 { return d, nil } else if y < 0 { // first is uint64, return uint64. d.SetUint64(uint64(x % uint64(-y))) return d, nil } d.SetUint64(x % uint64(y)) return d, nil case KindUint64: y := b.GetUint64() if y == 0 { return d, nil } d.SetUint64(x % y) return d, nil } case KindFloat64: x := a.GetFloat64() switch b.Kind() { case KindFloat64: y := b.GetFloat64() if y == 0 { return d, nil } d.SetFloat64(math.Mod(x, y)) return d, nil } case KindMysqlDecimal: x := a.GetMysqlDecimal() switch b.Kind() { case KindMysqlDecimal: y := b.GetMysqlDecimal() to := new(MyDecimal) err = DecimalMod(x, y, to) if err != ErrDivByZero { d.SetMysqlDecimal(to) } else { // div by zero returns nil without error. err = nil } return d, err } } _, err = InvOp2(a.GetValue(), b.GetValue(), opcode.Mod) return d, errors.Trace(err) }
[ "func", "ComputeMod", "(", "sc", "*", "variable", ".", "StatementContext", ",", "a", ",", "b", "Datum", ")", "(", "d", "Datum", ",", "err", "error", ")", "{", "switch", "a", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "x", ":=", "a", ".", "GetInt64", "(", ")", "\n", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "y", ":=", "b", ".", "GetInt64", "(", ")", "\n", "if", "y", "==", "0", "{", "return", "d", ",", "nil", "\n", "}", "\n", "d", ".", "SetInt64", "(", "x", "%", "y", ")", "\n", "return", "d", ",", "nil", "\n", "case", "KindUint64", ":", "y", ":=", "b", ".", "GetUint64", "(", ")", "\n", "if", "y", "==", "0", "{", "return", "d", ",", "nil", "\n", "}", "else", "if", "x", "<", "0", "{", "d", ".", "SetInt64", "(", "-", "int64", "(", "uint64", "(", "-", "x", ")", "%", "y", ")", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "d", ".", "SetInt64", "(", "int64", "(", "uint64", "(", "x", ")", "%", "y", ")", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "case", "KindUint64", ":", "x", ":=", "a", ".", "GetUint64", "(", ")", "\n", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindInt64", ":", "y", ":=", "b", ".", "GetInt64", "(", ")", "\n", "if", "y", "==", "0", "{", "return", "d", ",", "nil", "\n", "}", "else", "if", "y", "<", "0", "{", "d", ".", "SetUint64", "(", "uint64", "(", "x", "%", "uint64", "(", "-", "y", ")", ")", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "d", ".", "SetUint64", "(", "x", "%", "uint64", "(", "y", ")", ")", "\n", "return", "d", ",", "nil", "\n", "case", "KindUint64", ":", "y", ":=", "b", ".", "GetUint64", "(", ")", "\n", "if", "y", "==", "0", "{", "return", "d", ",", "nil", "\n", "}", "\n", "d", ".", "SetUint64", "(", "x", "%", "y", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "case", "KindFloat64", ":", "x", ":=", "a", ".", "GetFloat64", "(", ")", "\n", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindFloat64", ":", "y", ":=", "b", ".", "GetFloat64", "(", ")", "\n", "if", "y", "==", "0", "{", "return", "d", ",", "nil", "\n", "}", "\n", "d", ".", "SetFloat64", "(", "math", ".", "Mod", "(", "x", ",", "y", ")", ")", "\n", "return", "d", ",", "nil", "\n", "}", "\n", "case", "KindMysqlDecimal", ":", "x", ":=", "a", ".", "GetMysqlDecimal", "(", ")", "\n", "switch", "b", ".", "Kind", "(", ")", "{", "case", "KindMysqlDecimal", ":", "y", ":=", "b", ".", "GetMysqlDecimal", "(", ")", "\n", "to", ":=", "new", "(", "MyDecimal", ")", "\n", "err", "=", "DecimalMod", "(", "x", ",", "y", ",", "to", ")", "\n", "if", "err", "!=", "ErrDivByZero", "{", "d", ".", "SetMysqlDecimal", "(", "to", ")", "\n", "}", "else", "{", "err", "=", "nil", "\n", "}", "\n", "return", "d", ",", "err", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "InvOp2", "(", "a", ".", "GetValue", "(", ")", ",", "b", ".", "GetValue", "(", ")", ",", "opcode", ".", "Mod", ")", "\n", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// ComputeMod computes the result of a mod b.
[ "ComputeMod", "computes", "the", "result", "of", "a", "mod", "b", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L255-L330
train
chrislusf/gleam
sql/util/types/datum_eval.go
decimal2RoundUint
func decimal2RoundUint(x *MyDecimal) (uint64, error) { roundX := new(MyDecimal) x.Round(roundX, 0) var ( uintX uint64 err error ) if roundX.IsNegative() { intX, err := roundX.ToInt() if err != nil && err != ErrTruncated { return 0, errors.Trace(err) } uintX = uint64(intX) } else { uintX, err = roundX.ToUint() if err != nil && err != ErrTruncated { return 0, errors.Trace(err) } } return uintX, nil }
go
func decimal2RoundUint(x *MyDecimal) (uint64, error) { roundX := new(MyDecimal) x.Round(roundX, 0) var ( uintX uint64 err error ) if roundX.IsNegative() { intX, err := roundX.ToInt() if err != nil && err != ErrTruncated { return 0, errors.Trace(err) } uintX = uint64(intX) } else { uintX, err = roundX.ToUint() if err != nil && err != ErrTruncated { return 0, errors.Trace(err) } } return uintX, nil }
[ "func", "decimal2RoundUint", "(", "x", "*", "MyDecimal", ")", "(", "uint64", ",", "error", ")", "{", "roundX", ":=", "new", "(", "MyDecimal", ")", "\n", "x", ".", "Round", "(", "roundX", ",", "0", ")", "\n", "var", "(", "uintX", "uint64", "\n", "err", "error", "\n", ")", "\n", "if", "roundX", ".", "IsNegative", "(", ")", "{", "intX", ",", "err", ":=", "roundX", ".", "ToInt", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ErrTruncated", "{", "return", "0", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "uintX", "=", "uint64", "(", "intX", ")", "\n", "}", "else", "{", "uintX", ",", "err", "=", "roundX", ".", "ToUint", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ErrTruncated", "{", "return", "0", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "uintX", ",", "nil", "\n", "}" ]
// decimal2RoundUint converts a MyDecimal to an uint64 after rounding.
[ "decimal2RoundUint", "converts", "a", "MyDecimal", "to", "an", "uint64", "after", "rounding", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L400-L421
train
chrislusf/gleam
sql/util/types/datum_eval.go
ComputeBitNeg
func ComputeBitNeg(sc *variable.StatementContext, a Datum) (d Datum, err error) { aKind := a.Kind() if aKind == KindInt64 || aKind == KindUint64 { d.SetUint64(^a.GetUint64()) return } // If either is not integer, we round the operands and then use uint64 to calculate. x, err := convertNonInt2RoundUint64(sc, a) if err != nil { return d, errors.Trace(err) } d.SetUint64(^x) return d, nil }
go
func ComputeBitNeg(sc *variable.StatementContext, a Datum) (d Datum, err error) { aKind := a.Kind() if aKind == KindInt64 || aKind == KindUint64 { d.SetUint64(^a.GetUint64()) return } // If either is not integer, we round the operands and then use uint64 to calculate. x, err := convertNonInt2RoundUint64(sc, a) if err != nil { return d, errors.Trace(err) } d.SetUint64(^x) return d, nil }
[ "func", "ComputeBitNeg", "(", "sc", "*", "variable", ".", "StatementContext", ",", "a", "Datum", ")", "(", "d", "Datum", ",", "err", "error", ")", "{", "aKind", ":=", "a", ".", "Kind", "(", ")", "\n", "if", "aKind", "==", "KindInt64", "||", "aKind", "==", "KindUint64", "{", "d", ".", "SetUint64", "(", "^", "a", ".", "GetUint64", "(", ")", ")", "\n", "return", "\n", "}", "\n", "x", ",", "err", ":=", "convertNonInt2RoundUint64", "(", "sc", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "d", ".", "SetUint64", "(", "^", "x", ")", "\n", "return", "d", ",", "nil", "\n", "}" ]
// ComputeBitNeg computes the result of ~a.
[ "ComputeBitNeg", "computes", "the", "result", "of", "~a", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L468-L482
train
chrislusf/gleam
sql/util/types/datum_eval.go
ComputeBitXor
func ComputeBitXor(sc *variable.StatementContext, a, b Datum) (d Datum, err error) { aKind, bKind := a.Kind(), b.Kind() if (aKind == KindInt64 || aKind == KindUint64) && (bKind == KindInt64 || bKind == KindUint64) { d.SetUint64(a.GetUint64() ^ b.GetUint64()) return } // If either is not integer, we round the operands and then use uint64 to calculate. x, err := convertNonInt2RoundUint64(sc, a) if err != nil { return d, errors.Trace(err) } y, err := convertNonInt2RoundUint64(sc, b) if err != nil { return d, errors.Trace(err) } d.SetUint64(x ^ y) return d, nil }
go
func ComputeBitXor(sc *variable.StatementContext, a, b Datum) (d Datum, err error) { aKind, bKind := a.Kind(), b.Kind() if (aKind == KindInt64 || aKind == KindUint64) && (bKind == KindInt64 || bKind == KindUint64) { d.SetUint64(a.GetUint64() ^ b.GetUint64()) return } // If either is not integer, we round the operands and then use uint64 to calculate. x, err := convertNonInt2RoundUint64(sc, a) if err != nil { return d, errors.Trace(err) } y, err := convertNonInt2RoundUint64(sc, b) if err != nil { return d, errors.Trace(err) } d.SetUint64(x ^ y) return d, nil }
[ "func", "ComputeBitXor", "(", "sc", "*", "variable", ".", "StatementContext", ",", "a", ",", "b", "Datum", ")", "(", "d", "Datum", ",", "err", "error", ")", "{", "aKind", ",", "bKind", ":=", "a", ".", "Kind", "(", ")", ",", "b", ".", "Kind", "(", ")", "\n", "if", "(", "aKind", "==", "KindInt64", "||", "aKind", "==", "KindUint64", ")", "&&", "(", "bKind", "==", "KindInt64", "||", "bKind", "==", "KindUint64", ")", "{", "d", ".", "SetUint64", "(", "a", ".", "GetUint64", "(", ")", "^", "b", ".", "GetUint64", "(", ")", ")", "\n", "return", "\n", "}", "\n", "x", ",", "err", ":=", "convertNonInt2RoundUint64", "(", "sc", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "y", ",", "err", ":=", "convertNonInt2RoundUint64", "(", "sc", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "d", ".", "SetUint64", "(", "x", "^", "y", ")", "\n", "return", "d", ",", "nil", "\n", "}" ]
// ComputeBitXor computes the result of a ^ b.
[ "ComputeBitXor", "computes", "the", "result", "of", "a", "^", "b", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L485-L504
train
chrislusf/gleam
sql/util/types/datum_eval.go
convertNonInt2RoundUint64
func convertNonInt2RoundUint64(sc *variable.StatementContext, x Datum) (d uint64, err error) { decimalX, err := x.ToDecimal(sc) if err != nil { return d, errors.Trace(err) } d, err = decimal2RoundUint(decimalX) if err != nil { return d, errors.Trace(err) } return }
go
func convertNonInt2RoundUint64(sc *variable.StatementContext, x Datum) (d uint64, err error) { decimalX, err := x.ToDecimal(sc) if err != nil { return d, errors.Trace(err) } d, err = decimal2RoundUint(decimalX) if err != nil { return d, errors.Trace(err) } return }
[ "func", "convertNonInt2RoundUint64", "(", "sc", "*", "variable", ".", "StatementContext", ",", "x", "Datum", ")", "(", "d", "uint64", ",", "err", "error", ")", "{", "decimalX", ",", "err", ":=", "x", ".", "ToDecimal", "(", "sc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "d", ",", "err", "=", "decimal2RoundUint", "(", "decimalX", ")", "\n", "if", "err", "!=", "nil", "{", "return", "d", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// covertNonIntegerToUint64 coverts a non-integer to an uint64
[ "covertNonIntegerToUint64", "coverts", "a", "non", "-", "integer", "to", "an", "uint64" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/datum_eval.go#L551-L561
train
chrislusf/gleam
sql/expression/util.go
calculateSum
func calculateSum(sc *variable.StatementContext, sum, v types.Datum) (data types.Datum, err error) { // for avg and sum calculation // avg and sum use decimal for integer and decimal type, use float for others // see https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html switch v.Kind() { case types.KindNull: case types.KindInt64, types.KindUint64: var d *types.MyDecimal d, err = v.ToDecimal(sc) if err == nil { data = types.NewDecimalDatum(d) } case types.KindMysqlDecimal: data = v default: var f float64 f, err = v.ToFloat64(sc) if err == nil { data = types.NewFloat64Datum(f) } } if err != nil { return data, errors.Trace(err) } if data.IsNull() { return sum, nil } switch sum.Kind() { case types.KindNull: return data, nil case types.KindFloat64, types.KindMysqlDecimal: return types.ComputePlus(sum, data) default: return data, errors.Errorf("invalid value %v for aggregate", sum.Kind()) } }
go
func calculateSum(sc *variable.StatementContext, sum, v types.Datum) (data types.Datum, err error) { // for avg and sum calculation // avg and sum use decimal for integer and decimal type, use float for others // see https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html switch v.Kind() { case types.KindNull: case types.KindInt64, types.KindUint64: var d *types.MyDecimal d, err = v.ToDecimal(sc) if err == nil { data = types.NewDecimalDatum(d) } case types.KindMysqlDecimal: data = v default: var f float64 f, err = v.ToFloat64(sc) if err == nil { data = types.NewFloat64Datum(f) } } if err != nil { return data, errors.Trace(err) } if data.IsNull() { return sum, nil } switch sum.Kind() { case types.KindNull: return data, nil case types.KindFloat64, types.KindMysqlDecimal: return types.ComputePlus(sum, data) default: return data, errors.Errorf("invalid value %v for aggregate", sum.Kind()) } }
[ "func", "calculateSum", "(", "sc", "*", "variable", ".", "StatementContext", ",", "sum", ",", "v", "types", ".", "Datum", ")", "(", "data", "types", ".", "Datum", ",", "err", "error", ")", "{", "switch", "v", ".", "Kind", "(", ")", "{", "case", "types", ".", "KindNull", ":", "case", "types", ".", "KindInt64", ",", "types", ".", "KindUint64", ":", "var", "d", "*", "types", ".", "MyDecimal", "\n", "d", ",", "err", "=", "v", ".", "ToDecimal", "(", "sc", ")", "\n", "if", "err", "==", "nil", "{", "data", "=", "types", ".", "NewDecimalDatum", "(", "d", ")", "\n", "}", "\n", "case", "types", ".", "KindMysqlDecimal", ":", "data", "=", "v", "\n", "default", ":", "var", "f", "float64", "\n", "f", ",", "err", "=", "v", ".", "ToFloat64", "(", "sc", ")", "\n", "if", "err", "==", "nil", "{", "data", "=", "types", ".", "NewFloat64Datum", "(", "f", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "data", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "data", ".", "IsNull", "(", ")", "{", "return", "sum", ",", "nil", "\n", "}", "\n", "switch", "sum", ".", "Kind", "(", ")", "{", "case", "types", ".", "KindNull", ":", "return", "data", ",", "nil", "\n", "case", "types", ".", "KindFloat64", ",", "types", ".", "KindMysqlDecimal", ":", "return", "types", ".", "ComputePlus", "(", "sum", ",", "data", ")", "\n", "default", ":", "return", "data", ",", "errors", ".", "Errorf", "(", "\"invalid value %v for aggregate\"", ",", "sum", ".", "Kind", "(", ")", ")", "\n", "}", "\n", "}" ]
// calculateSum adds v to sum.
[ "calculateSum", "adds", "v", "to", "sum", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/util.go#L73-L110
train
chrislusf/gleam
util/channel_util.go
CopyMultipleReaders
func CopyMultipleReaders(readers []io.Reader, writer io.Writer) (inCounter int64, outCounter int64, e error) { writerChan := make(chan []byte, 16*len(readers)) errChan := make(chan error, len(readers)) defer close(errChan) var wg sync.WaitGroup for _, reader := range readers { wg.Add(1) go func(reader io.Reader) { defer wg.Done() err := ProcessMessage(reader, func(data []byte) error { writerChan <- data atomic.AddInt64(&inCounter, 1) return nil }) errChan <- err }(reader) } wg.Add(1) go func() { defer wg.Done() for data := range writerChan { if err := WriteMessage(writer, data); err != nil { errChan <- fmt.Errorf("WriteMessage Error: %v", err) break } atomic.AddInt64(&outCounter, 1) } }() for range readers { err := <-errChan if err != nil && err != io.EOF { return inCounter, outCounter, err } } close(writerChan) wg.Wait() return inCounter, outCounter, nil }
go
func CopyMultipleReaders(readers []io.Reader, writer io.Writer) (inCounter int64, outCounter int64, e error) { writerChan := make(chan []byte, 16*len(readers)) errChan := make(chan error, len(readers)) defer close(errChan) var wg sync.WaitGroup for _, reader := range readers { wg.Add(1) go func(reader io.Reader) { defer wg.Done() err := ProcessMessage(reader, func(data []byte) error { writerChan <- data atomic.AddInt64(&inCounter, 1) return nil }) errChan <- err }(reader) } wg.Add(1) go func() { defer wg.Done() for data := range writerChan { if err := WriteMessage(writer, data); err != nil { errChan <- fmt.Errorf("WriteMessage Error: %v", err) break } atomic.AddInt64(&outCounter, 1) } }() for range readers { err := <-errChan if err != nil && err != io.EOF { return inCounter, outCounter, err } } close(writerChan) wg.Wait() return inCounter, outCounter, nil }
[ "func", "CopyMultipleReaders", "(", "readers", "[", "]", "io", ".", "Reader", ",", "writer", "io", ".", "Writer", ")", "(", "inCounter", "int64", ",", "outCounter", "int64", ",", "e", "error", ")", "{", "writerChan", ":=", "make", "(", "chan", "[", "]", "byte", ",", "16", "*", "len", "(", "readers", ")", ")", "\n", "errChan", ":=", "make", "(", "chan", "error", ",", "len", "(", "readers", ")", ")", "\n", "defer", "close", "(", "errChan", ")", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "for", "_", ",", "reader", ":=", "range", "readers", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "reader", "io", ".", "Reader", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "err", ":=", "ProcessMessage", "(", "reader", ",", "func", "(", "data", "[", "]", "byte", ")", "error", "{", "writerChan", "<-", "data", "\n", "atomic", ".", "AddInt64", "(", "&", "inCounter", ",", "1", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "errChan", "<-", "err", "\n", "}", "(", "reader", ")", "\n", "}", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "for", "data", ":=", "range", "writerChan", "{", "if", "err", ":=", "WriteMessage", "(", "writer", ",", "data", ")", ";", "err", "!=", "nil", "{", "errChan", "<-", "fmt", ".", "Errorf", "(", "\"WriteMessage Error: %v\"", ",", "err", ")", "\n", "break", "\n", "}", "\n", "atomic", ".", "AddInt64", "(", "&", "outCounter", ",", "1", ")", "\n", "}", "\n", "}", "(", ")", "\n", "for", "range", "readers", "{", "err", ":=", "<-", "errChan", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "inCounter", ",", "outCounter", ",", "err", "\n", "}", "\n", "}", "\n", "close", "(", "writerChan", ")", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "inCounter", ",", "outCounter", ",", "nil", "\n", "}" ]
// setup asynchronously to merge multiple channels into one channel
[ "setup", "asynchronously", "to", "merge", "multiple", "channels", "into", "one", "channel" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/channel_util.go#L58-L101
train
chrislusf/gleam
flow/dataset_pipe.go
Pipe
func (d *Dataset) Pipe(name, code string) *Dataset { ret, step := add1ShardTo1Step(d) step.Name = name step.Description = code step.IsPipe = true step.Command = script.NewShellScript().Pipe(code).GetCommand() return ret }
go
func (d *Dataset) Pipe(name, code string) *Dataset { ret, step := add1ShardTo1Step(d) step.Name = name step.Description = code step.IsPipe = true step.Command = script.NewShellScript().Pipe(code).GetCommand() return ret }
[ "func", "(", "d", "*", "Dataset", ")", "Pipe", "(", "name", ",", "code", "string", ")", "*", "Dataset", "{", "ret", ",", "step", ":=", "add1ShardTo1Step", "(", "d", ")", "\n", "step", ".", "Name", "=", "name", "\n", "step", ".", "Description", "=", "code", "\n", "step", ".", "IsPipe", "=", "true", "\n", "step", ".", "Command", "=", "script", ".", "NewShellScript", "(", ")", ".", "Pipe", "(", "code", ")", ".", "GetCommand", "(", ")", "\n", "return", "ret", "\n", "}" ]
// Pipe runs the code as an external program, which processes the // tab-separated input from the program's stdin, and outout to // stdout also in tab-separated lines.
[ "Pipe", "runs", "the", "code", "as", "an", "external", "program", "which", "processes", "the", "tab", "-", "separated", "input", "from", "the", "program", "s", "stdin", "and", "outout", "to", "stdout", "also", "in", "tab", "-", "separated", "lines", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_pipe.go#L11-L18
train
chrislusf/gleam
instruction/local_top.go
DoLocalTop
func DoLocalTop(reader io.Reader, writer io.Writer, n int, orderBys []OrderBy, stats *pb.InstructionStat) error { pq := newMinQueueOfPairs(orderBys) err := util.ProcessRow(reader, nil, func(row *util.Row) error { stats.InputCounter++ if pq.Len() >= n { if lessThan(orderBys, pq.Top().(*util.Row), row) { pq.Dequeue() pq.Enqueue(row, 0) } } else { pq.Enqueue(row, 0) } return nil }) if err != nil { fmt.Printf("Top>Failed to process input data:%v\n", err) return err } // read data out of the priority queue length := pq.Len() itemsToReverse := make([]*util.Row, length) for i := 0; i < length; i++ { entry, _ := pq.Dequeue() itemsToReverse[i] = entry.(*util.Row) } for i := length - 1; i >= 0; i-- { itemsToReverse[i].WriteTo(writer) stats.OutputCounter++ } return nil }
go
func DoLocalTop(reader io.Reader, writer io.Writer, n int, orderBys []OrderBy, stats *pb.InstructionStat) error { pq := newMinQueueOfPairs(orderBys) err := util.ProcessRow(reader, nil, func(row *util.Row) error { stats.InputCounter++ if pq.Len() >= n { if lessThan(orderBys, pq.Top().(*util.Row), row) { pq.Dequeue() pq.Enqueue(row, 0) } } else { pq.Enqueue(row, 0) } return nil }) if err != nil { fmt.Printf("Top>Failed to process input data:%v\n", err) return err } // read data out of the priority queue length := pq.Len() itemsToReverse := make([]*util.Row, length) for i := 0; i < length; i++ { entry, _ := pq.Dequeue() itemsToReverse[i] = entry.(*util.Row) } for i := length - 1; i >= 0; i-- { itemsToReverse[i].WriteTo(writer) stats.OutputCounter++ } return nil }
[ "func", "DoLocalTop", "(", "reader", "io", ".", "Reader", ",", "writer", "io", ".", "Writer", ",", "n", "int", ",", "orderBys", "[", "]", "OrderBy", ",", "stats", "*", "pb", ".", "InstructionStat", ")", "error", "{", "pq", ":=", "newMinQueueOfPairs", "(", "orderBys", ")", "\n", "err", ":=", "util", ".", "ProcessRow", "(", "reader", ",", "nil", ",", "func", "(", "row", "*", "util", ".", "Row", ")", "error", "{", "stats", ".", "InputCounter", "++", "\n", "if", "pq", ".", "Len", "(", ")", ">=", "n", "{", "if", "lessThan", "(", "orderBys", ",", "pq", ".", "Top", "(", ")", ".", "(", "*", "util", ".", "Row", ")", ",", "row", ")", "{", "pq", ".", "Dequeue", "(", ")", "\n", "pq", ".", "Enqueue", "(", "row", ",", "0", ")", "\n", "}", "\n", "}", "else", "{", "pq", ".", "Enqueue", "(", "row", ",", "0", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"Top>Failed to process input data:%v\\n\"", ",", "\\n", ")", "\n", "err", "\n", "}", "\n", "return", "err", "\n", "length", ":=", "pq", ".", "Len", "(", ")", "\n", "itemsToReverse", ":=", "make", "(", "[", "]", "*", "util", ".", "Row", ",", "length", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "length", ";", "i", "++", "{", "entry", ",", "_", ":=", "pq", ".", "Dequeue", "(", ")", "\n", "itemsToReverse", "[", "i", "]", "=", "entry", ".", "(", "*", "util", ".", "Row", ")", "\n", "}", "\n", "for", "i", ":=", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "itemsToReverse", "[", "i", "]", ".", "WriteTo", "(", "writer", ")", "\n", "stats", ".", "OutputCounter", "++", "\n", "}", "\n", "}" ]
// DoLocalTop streamingly compare and get the top n items
[ "DoLocalTop", "streamingly", "compare", "and", "get", "the", "top", "n", "items" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/instruction/local_top.go#L56-L92
train
chrislusf/gleam
sql/ast/expressions.go
NewValueExpr
func NewValueExpr(value interface{}) *ValueExpr { if ve, ok := value.(*ValueExpr); ok { return ve } ve := &ValueExpr{} ve.SetValue(value) types.DefaultTypeForValue(value, &ve.Type) return ve }
go
func NewValueExpr(value interface{}) *ValueExpr { if ve, ok := value.(*ValueExpr); ok { return ve } ve := &ValueExpr{} ve.SetValue(value) types.DefaultTypeForValue(value, &ve.Type) return ve }
[ "func", "NewValueExpr", "(", "value", "interface", "{", "}", ")", "*", "ValueExpr", "{", "if", "ve", ",", "ok", ":=", "value", ".", "(", "*", "ValueExpr", ")", ";", "ok", "{", "return", "ve", "\n", "}", "\n", "ve", ":=", "&", "ValueExpr", "{", "}", "\n", "ve", ".", "SetValue", "(", "value", ")", "\n", "types", ".", "DefaultTypeForValue", "(", "value", ",", "&", "ve", ".", "Type", ")", "\n", "return", "ve", "\n", "}" ]
// NewValueExpr creates a ValueExpr with value, and sets default field type.
[ "NewValueExpr", "creates", "a", "ValueExpr", "with", "value", "and", "sets", "default", "field", "type", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/ast/expressions.go#L58-L66
train
chrislusf/gleam
distributed/option.go
SetProfiling
func (o *DistributedOption) SetProfiling(isProfiling bool) *DistributedOption { o.IsProfiling = isProfiling return o }
go
func (o *DistributedOption) SetProfiling(isProfiling bool) *DistributedOption { o.IsProfiling = isProfiling return o }
[ "func", "(", "o", "*", "DistributedOption", ")", "SetProfiling", "(", "isProfiling", "bool", ")", "*", "DistributedOption", "{", "o", ".", "IsProfiling", "=", "isProfiling", "\n", "return", "o", "\n", "}" ]
// SetProfiling profiling will generate cpu and memory profile files when the executors are completed.
[ "SetProfiling", "profiling", "will", "generate", "cpu", "and", "memory", "profile", "files", "when", "the", "executors", "are", "completed", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/option.go#L55-L58
train
chrislusf/gleam
distributed/option.go
WithFile
func (o *DistributedOption) WithFile(relatedFile, toFolder string) *DistributedOption { relativePath, err := filepath.Rel(".", relatedFile) if err != nil { relativePath = relatedFile } o.RequiredFiles = append(o.RequiredFiles, resource.FileResource{relativePath, toFolder}) return o }
go
func (o *DistributedOption) WithFile(relatedFile, toFolder string) *DistributedOption { relativePath, err := filepath.Rel(".", relatedFile) if err != nil { relativePath = relatedFile } o.RequiredFiles = append(o.RequiredFiles, resource.FileResource{relativePath, toFolder}) return o }
[ "func", "(", "o", "*", "DistributedOption", ")", "WithFile", "(", "relatedFile", ",", "toFolder", "string", ")", "*", "DistributedOption", "{", "relativePath", ",", "err", ":=", "filepath", ".", "Rel", "(", "\".\"", ",", "relatedFile", ")", "\n", "if", "err", "!=", "nil", "{", "relativePath", "=", "relatedFile", "\n", "}", "\n", "o", ".", "RequiredFiles", "=", "append", "(", "o", ".", "RequiredFiles", ",", "resource", ".", "FileResource", "{", "relativePath", ",", "toFolder", "}", ")", "\n", "return", "o", "\n", "}" ]
// WithFile sends any related file over to gleam agents // so the task can still access these files on gleam agents. // The files are placed on the executed task's current working directory.
[ "WithFile", "sends", "any", "related", "file", "over", "to", "gleam", "agents", "so", "the", "task", "can", "still", "access", "these", "files", "on", "gleam", "agents", ".", "The", "files", "are", "placed", "on", "the", "executed", "task", "s", "current", "working", "directory", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/option.go#L63-L70
train
chrislusf/gleam
util/row_read_write.go
WriteTo
func (row Row) WriteTo(writer io.Writer) (err error) { encoded, err := encodeRow(row) if err != nil { return fmt.Errorf("WriteTo encoding error: %v", err) } return WriteMessage(writer, encoded) }
go
func (row Row) WriteTo(writer io.Writer) (err error) { encoded, err := encodeRow(row) if err != nil { return fmt.Errorf("WriteTo encoding error: %v", err) } return WriteMessage(writer, encoded) }
[ "func", "(", "row", "Row", ")", "WriteTo", "(", "writer", "io", ".", "Writer", ")", "(", "err", "error", ")", "{", "encoded", ",", "err", ":=", "encodeRow", "(", "row", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"WriteTo encoding error: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "WriteMessage", "(", "writer", ",", "encoded", ")", "\n", "}" ]
// WriteTo encode and write a row of data to the writer
[ "WriteTo", "encode", "and", "write", "a", "row", "of", "data", "to", "the", "writer" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/row_read_write.go#L12-L18
train
chrislusf/gleam
util/row_read_write.go
ReadRow
func ReadRow(reader io.Reader) (row *Row, err error) { encodedBytes, hasErr := ReadMessage(reader) if hasErr != nil { if hasErr != io.EOF { return row, fmt.Errorf("ReadRow ReadMessage: %v", hasErr) } return row, io.EOF } if row, err = DecodeRow(encodedBytes); err != nil { return row, fmt.Errorf("ReadRow failed to decode byte: %v", err) } return row, err }
go
func ReadRow(reader io.Reader) (row *Row, err error) { encodedBytes, hasErr := ReadMessage(reader) if hasErr != nil { if hasErr != io.EOF { return row, fmt.Errorf("ReadRow ReadMessage: %v", hasErr) } return row, io.EOF } if row, err = DecodeRow(encodedBytes); err != nil { return row, fmt.Errorf("ReadRow failed to decode byte: %v", err) } return row, err }
[ "func", "ReadRow", "(", "reader", "io", ".", "Reader", ")", "(", "row", "*", "Row", ",", "err", "error", ")", "{", "encodedBytes", ",", "hasErr", ":=", "ReadMessage", "(", "reader", ")", "\n", "if", "hasErr", "!=", "nil", "{", "if", "hasErr", "!=", "io", ".", "EOF", "{", "return", "row", ",", "fmt", ".", "Errorf", "(", "\"ReadRow ReadMessage: %v\"", ",", "hasErr", ")", "\n", "}", "\n", "return", "row", ",", "io", ".", "EOF", "\n", "}", "\n", "if", "row", ",", "err", "=", "DecodeRow", "(", "encodedBytes", ")", ";", "err", "!=", "nil", "{", "return", "row", ",", "fmt", ".", "Errorf", "(", "\"ReadRow failed to decode byte: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "row", ",", "err", "\n", "}" ]
// ReadRow read and decode one row of data
[ "ReadRow", "read", "and", "decode", "one", "row", "of", "data" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/row_read_write.go#L21-L33
train
chrislusf/gleam
util/row_read_write.go
EncodeKeys
func EncodeKeys(anyObject ...interface{}) ([]byte, error) { var buf bytes.Buffer en := msgp.NewWriter(&buf) for _, obj := range anyObject { if err := en.WriteIntf(obj); err != nil { return nil, fmt.Errorf("Failed to encode key: %v", err) } } return buf.Bytes(), nil }
go
func EncodeKeys(anyObject ...interface{}) ([]byte, error) { var buf bytes.Buffer en := msgp.NewWriter(&buf) for _, obj := range anyObject { if err := en.WriteIntf(obj); err != nil { return nil, fmt.Errorf("Failed to encode key: %v", err) } } return buf.Bytes(), nil }
[ "func", "EncodeKeys", "(", "anyObject", "...", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "en", ":=", "msgp", ".", "NewWriter", "(", "&", "buf", ")", "\n", "for", "_", ",", "obj", ":=", "range", "anyObject", "{", "if", "err", ":=", "en", ".", "WriteIntf", "(", "obj", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Failed to encode key: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// EncodeKeys encode keys to a blob, for comparing or sorting
[ "EncodeKeys", "encode", "keys", "to", "a", "blob", "for", "comparing", "or", "sorting" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/row_read_write.go#L41-L50
train
chrislusf/gleam
util/row_read_write.go
DecodeRow
func DecodeRow(encodedBytes []byte) (*Row, error) { row := &Row{} _, err := row.UnmarshalMsg(encodedBytes) if err != nil { err = fmt.Errorf("decode row error %v: %s\n", err, string(encodedBytes)) } return row, err }
go
func DecodeRow(encodedBytes []byte) (*Row, error) { row := &Row{} _, err := row.UnmarshalMsg(encodedBytes) if err != nil { err = fmt.Errorf("decode row error %v: %s\n", err, string(encodedBytes)) } return row, err }
[ "func", "DecodeRow", "(", "encodedBytes", "[", "]", "byte", ")", "(", "*", "Row", ",", "error", ")", "{", "row", ":=", "&", "Row", "{", "}", "\n", "_", ",", "err", ":=", "row", ".", "UnmarshalMsg", "(", "encodedBytes", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"decode row error %v: %s\\n\"", ",", "\\n", ",", "err", ")", "\n", "}", "\n", "string", "(", "encodedBytes", ")", "\n", "}" ]
// DecodeRow decodes one row of data from a blob
[ "DecodeRow", "decodes", "one", "row", "of", "data", "from", "a", "blob" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/row_read_write.go#L53-L60
train
chrislusf/gleam
util/row_read_write.go
ProcessRow
func ProcessRow(reader io.Reader, indexes []int, f func(*Row) error) (err error) { return ProcessMessage(reader, func(input []byte) error { // read the row row, err := DecodeRow(input) if err != nil { return fmt.Errorf("DoLocalDistinct error %v: %+v", err, input) } row.UseKeys(indexes) return f(row) }) }
go
func ProcessRow(reader io.Reader, indexes []int, f func(*Row) error) (err error) { return ProcessMessage(reader, func(input []byte) error { // read the row row, err := DecodeRow(input) if err != nil { return fmt.Errorf("DoLocalDistinct error %v: %+v", err, input) } row.UseKeys(indexes) return f(row) }) }
[ "func", "ProcessRow", "(", "reader", "io", ".", "Reader", ",", "indexes", "[", "]", "int", ",", "f", "func", "(", "*", "Row", ")", "error", ")", "(", "err", "error", ")", "{", "return", "ProcessMessage", "(", "reader", ",", "func", "(", "input", "[", "]", "byte", ")", "error", "{", "row", ",", "err", ":=", "DecodeRow", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"DoLocalDistinct error %v: %+v\"", ",", "err", ",", "input", ")", "\n", "}", "\n", "row", ".", "UseKeys", "(", "indexes", ")", "\n", "return", "f", "(", "row", ")", "\n", "}", ")", "\n", "}" ]
// ProcessRow Reads and processes rows until EOF
[ "ProcessRow", "Reads", "and", "processes", "rows", "until", "EOF" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/row_read_write.go#L63-L73
train
chrislusf/gleam
pb/resource_proto_helper.go
Distance
func (a *Location) Distance(b *Location) float64 { if a.DataCenter != b.DataCenter { return 1000 } if a.Rack != b.Rack { return 100 } if a.Server != b.Server { return 10 } return 1 }
go
func (a *Location) Distance(b *Location) float64 { if a.DataCenter != b.DataCenter { return 1000 } if a.Rack != b.Rack { return 100 } if a.Server != b.Server { return 10 } return 1 }
[ "func", "(", "a", "*", "Location", ")", "Distance", "(", "b", "*", "Location", ")", "float64", "{", "if", "a", ".", "DataCenter", "!=", "b", ".", "DataCenter", "{", "return", "1000", "\n", "}", "\n", "if", "a", ".", "Rack", "!=", "b", ".", "Rack", "{", "return", "100", "\n", "}", "\n", "if", "a", ".", "Server", "!=", "b", ".", "Server", "{", "return", "10", "\n", "}", "\n", "return", "1", "\n", "}" ]
// the distance is a relative value, similar to network lantency
[ "the", "distance", "is", "a", "relative", "value", "similar", "to", "network", "lantency" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/pb/resource_proto_helper.go#L12-L23
train
chrislusf/gleam
sql/resolver/resolver.go
ResolveName
func ResolveName(node ast.Node, info infoschema.InfoSchema, ctx context.Context) error { defaultSchema := ctx.GetSessionVars().CurrentDB resolver := nameResolver{Info: info, Ctx: ctx, DefaultSchema: model.NewCIStr(defaultSchema)} node.Accept(&resolver) return errors.Trace(resolver.Err) }
go
func ResolveName(node ast.Node, info infoschema.InfoSchema, ctx context.Context) error { defaultSchema := ctx.GetSessionVars().CurrentDB resolver := nameResolver{Info: info, Ctx: ctx, DefaultSchema: model.NewCIStr(defaultSchema)} node.Accept(&resolver) return errors.Trace(resolver.Err) }
[ "func", "ResolveName", "(", "node", "ast", ".", "Node", ",", "info", "infoschema", ".", "InfoSchema", ",", "ctx", "context", ".", "Context", ")", "error", "{", "defaultSchema", ":=", "ctx", ".", "GetSessionVars", "(", ")", ".", "CurrentDB", "\n", "resolver", ":=", "nameResolver", "{", "Info", ":", "info", ",", "Ctx", ":", "ctx", ",", "DefaultSchema", ":", "model", ".", "NewCIStr", "(", "defaultSchema", ")", "}", "\n", "node", ".", "Accept", "(", "&", "resolver", ")", "\n", "return", "errors", ".", "Trace", "(", "resolver", ".", "Err", ")", "\n", "}" ]
// ResolveName resolves table name and column name. // It generates ResultFields for ResultSetNode and resolves ColumnNameExpr to a ResultField.
[ "ResolveName", "resolves", "table", "name", "and", "column", "name", ".", "It", "generates", "ResultFields", "for", "ResultSetNode", "and", "resolves", "ColumnNameExpr", "to", "a", "ResultField", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L30-L35
train
chrislusf/gleam
sql/resolver/resolver.go
currentContext
func (nr *nameResolver) currentContext() *resolverContext { stackLen := len(nr.contextStack) if stackLen == 0 { return nil } return nr.contextStack[stackLen-1] }
go
func (nr *nameResolver) currentContext() *resolverContext { stackLen := len(nr.contextStack) if stackLen == 0 { return nil } return nr.contextStack[stackLen-1] }
[ "func", "(", "nr", "*", "nameResolver", ")", "currentContext", "(", ")", "*", "resolverContext", "{", "stackLen", ":=", "len", "(", "nr", ".", "contextStack", ")", "\n", "if", "stackLen", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "nr", ".", "contextStack", "[", "stackLen", "-", "1", "]", "\n", "}" ]
// currentContext gets the current resolverContext.
[ "currentContext", "gets", "the", "current", "resolverContext", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L104-L110
train
chrislusf/gleam
sql/resolver/resolver.go
pushContext
func (nr *nameResolver) pushContext() { nr.contextStack = append(nr.contextStack, &resolverContext{ tableMap: map[string]int{}, derivedTableMap: map[string]int{}, }) }
go
func (nr *nameResolver) pushContext() { nr.contextStack = append(nr.contextStack, &resolverContext{ tableMap: map[string]int{}, derivedTableMap: map[string]int{}, }) }
[ "func", "(", "nr", "*", "nameResolver", ")", "pushContext", "(", ")", "{", "nr", ".", "contextStack", "=", "append", "(", "nr", ".", "contextStack", ",", "&", "resolverContext", "{", "tableMap", ":", "map", "[", "string", "]", "int", "{", "}", ",", "derivedTableMap", ":", "map", "[", "string", "]", "int", "{", "}", ",", "}", ")", "\n", "}" ]
// pushContext is called when we enter a statement.
[ "pushContext", "is", "called", "when", "we", "enter", "a", "statement", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L113-L118
train
chrislusf/gleam
sql/resolver/resolver.go
popContext
func (nr *nameResolver) popContext() { nr.contextStack = nr.contextStack[:len(nr.contextStack)-1] }
go
func (nr *nameResolver) popContext() { nr.contextStack = nr.contextStack[:len(nr.contextStack)-1] }
[ "func", "(", "nr", "*", "nameResolver", ")", "popContext", "(", ")", "{", "nr", ".", "contextStack", "=", "nr", ".", "contextStack", "[", ":", "len", "(", "nr", ".", "contextStack", ")", "-", "1", "]", "\n", "}" ]
// popContext is called when we leave a statement.
[ "popContext", "is", "called", "when", "we", "leave", "a", "statement", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L121-L123
train
chrislusf/gleam
sql/resolver/resolver.go
pushJoin
func (nr *nameResolver) pushJoin(j *ast.Join) { ctx := nr.currentContext() ctx.joinNodeStack = append(ctx.joinNodeStack, j) }
go
func (nr *nameResolver) pushJoin(j *ast.Join) { ctx := nr.currentContext() ctx.joinNodeStack = append(ctx.joinNodeStack, j) }
[ "func", "(", "nr", "*", "nameResolver", ")", "pushJoin", "(", "j", "*", "ast", ".", "Join", ")", "{", "ctx", ":=", "nr", ".", "currentContext", "(", ")", "\n", "ctx", ".", "joinNodeStack", "=", "append", "(", "ctx", ".", "joinNodeStack", ",", "j", ")", "\n", "}" ]
// pushJoin is called when we enter a join node.
[ "pushJoin", "is", "called", "when", "we", "enter", "a", "join", "node", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L126-L129
train
chrislusf/gleam
sql/resolver/resolver.go
popJoin
func (nr *nameResolver) popJoin() { ctx := nr.currentContext() ctx.joinNodeStack = ctx.joinNodeStack[:len(ctx.joinNodeStack)-1] }
go
func (nr *nameResolver) popJoin() { ctx := nr.currentContext() ctx.joinNodeStack = ctx.joinNodeStack[:len(ctx.joinNodeStack)-1] }
[ "func", "(", "nr", "*", "nameResolver", ")", "popJoin", "(", ")", "{", "ctx", ":=", "nr", ".", "currentContext", "(", ")", "\n", "ctx", ".", "joinNodeStack", "=", "ctx", ".", "joinNodeStack", "[", ":", "len", "(", "ctx", ".", "joinNodeStack", ")", "-", "1", "]", "\n", "}" ]
// popJoin is called when we leave a join node.
[ "popJoin", "is", "called", "when", "we", "leave", "a", "join", "node", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L132-L135
train
chrislusf/gleam
sql/resolver/resolver.go
handleTableName
func (nr *nameResolver) handleTableName(tn *ast.TableName) { if tn.Schema.L == "" { tn.Schema = nr.DefaultSchema } ctx := nr.currentContext() if ctx.inCreateOrDropTable { // The table may not exist in create table or drop table statement. // Skip resolving the table to avoid error. return } if ctx.inDeleteTableList { idx, ok := ctx.tableMap[nr.tableUniqueName(tn.Schema, tn.Name)] if !ok { nr.Err = errors.Errorf("Unknown table %s", tn.Name.O) return } ts := ctx.tables[idx] tableName := ts.Source.(*ast.TableName) tn.DBInfo = tableName.DBInfo tn.TableInfo = tableName.TableInfo tn.SetResultFields(tableName.GetResultFields()) return } table, err := nr.Info.TableByName(tn.Schema, tn.Name) if err != nil { nr.Err = errors.Trace(err) return } tn.TableInfo = table.Meta() dbInfo, _ := nr.Info.SchemaByName(tn.Schema) tn.DBInfo = dbInfo rfs := make([]*ast.ResultField, 0, len(tn.TableInfo.Columns)) tmp := make([]struct { ast.ValueExpr ast.ResultField }, len(tn.TableInfo.Columns)) for i, v := range tn.TableInfo.Columns { expr := &tmp[i].ValueExpr rf := &tmp[i].ResultField expr.SetType(&v.FieldType) *rf = ast.ResultField{ Column: v, Table: tn.TableInfo, DBName: tn.Schema, Expr: expr, TableName: tn, } rfs = append(rfs, rf) } tn.SetResultFields(rfs) return }
go
func (nr *nameResolver) handleTableName(tn *ast.TableName) { if tn.Schema.L == "" { tn.Schema = nr.DefaultSchema } ctx := nr.currentContext() if ctx.inCreateOrDropTable { // The table may not exist in create table or drop table statement. // Skip resolving the table to avoid error. return } if ctx.inDeleteTableList { idx, ok := ctx.tableMap[nr.tableUniqueName(tn.Schema, tn.Name)] if !ok { nr.Err = errors.Errorf("Unknown table %s", tn.Name.O) return } ts := ctx.tables[idx] tableName := ts.Source.(*ast.TableName) tn.DBInfo = tableName.DBInfo tn.TableInfo = tableName.TableInfo tn.SetResultFields(tableName.GetResultFields()) return } table, err := nr.Info.TableByName(tn.Schema, tn.Name) if err != nil { nr.Err = errors.Trace(err) return } tn.TableInfo = table.Meta() dbInfo, _ := nr.Info.SchemaByName(tn.Schema) tn.DBInfo = dbInfo rfs := make([]*ast.ResultField, 0, len(tn.TableInfo.Columns)) tmp := make([]struct { ast.ValueExpr ast.ResultField }, len(tn.TableInfo.Columns)) for i, v := range tn.TableInfo.Columns { expr := &tmp[i].ValueExpr rf := &tmp[i].ResultField expr.SetType(&v.FieldType) *rf = ast.ResultField{ Column: v, Table: tn.TableInfo, DBName: tn.Schema, Expr: expr, TableName: tn, } rfs = append(rfs, rf) } tn.SetResultFields(rfs) return }
[ "func", "(", "nr", "*", "nameResolver", ")", "handleTableName", "(", "tn", "*", "ast", ".", "TableName", ")", "{", "if", "tn", ".", "Schema", ".", "L", "==", "\"\"", "{", "tn", ".", "Schema", "=", "nr", ".", "DefaultSchema", "\n", "}", "\n", "ctx", ":=", "nr", ".", "currentContext", "(", ")", "\n", "if", "ctx", ".", "inCreateOrDropTable", "{", "return", "\n", "}", "\n", "if", "ctx", ".", "inDeleteTableList", "{", "idx", ",", "ok", ":=", "ctx", ".", "tableMap", "[", "nr", ".", "tableUniqueName", "(", "tn", ".", "Schema", ",", "tn", ".", "Name", ")", "]", "\n", "if", "!", "ok", "{", "nr", ".", "Err", "=", "errors", ".", "Errorf", "(", "\"Unknown table %s\"", ",", "tn", ".", "Name", ".", "O", ")", "\n", "return", "\n", "}", "\n", "ts", ":=", "ctx", ".", "tables", "[", "idx", "]", "\n", "tableName", ":=", "ts", ".", "Source", ".", "(", "*", "ast", ".", "TableName", ")", "\n", "tn", ".", "DBInfo", "=", "tableName", ".", "DBInfo", "\n", "tn", ".", "TableInfo", "=", "tableName", ".", "TableInfo", "\n", "tn", ".", "SetResultFields", "(", "tableName", ".", "GetResultFields", "(", ")", ")", "\n", "return", "\n", "}", "\n", "table", ",", "err", ":=", "nr", ".", "Info", ".", "TableByName", "(", "tn", ".", "Schema", ",", "tn", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "nr", ".", "Err", "=", "errors", ".", "Trace", "(", "err", ")", "\n", "return", "\n", "}", "\n", "tn", ".", "TableInfo", "=", "table", ".", "Meta", "(", ")", "\n", "dbInfo", ",", "_", ":=", "nr", ".", "Info", ".", "SchemaByName", "(", "tn", ".", "Schema", ")", "\n", "tn", ".", "DBInfo", "=", "dbInfo", "\n", "rfs", ":=", "make", "(", "[", "]", "*", "ast", ".", "ResultField", ",", "0", ",", "len", "(", "tn", ".", "TableInfo", ".", "Columns", ")", ")", "\n", "tmp", ":=", "make", "(", "[", "]", "struct", "{", "ast", ".", "ValueExpr", "\n", "ast", ".", "ResultField", "\n", "}", ",", "len", "(", "tn", ".", "TableInfo", ".", "Columns", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "tn", ".", "TableInfo", ".", "Columns", "{", "expr", ":=", "&", "tmp", "[", "i", "]", ".", "ValueExpr", "\n", "rf", ":=", "&", "tmp", "[", "i", "]", ".", "ResultField", "\n", "expr", ".", "SetType", "(", "&", "v", ".", "FieldType", ")", "\n", "*", "rf", "=", "ast", ".", "ResultField", "{", "Column", ":", "v", ",", "Table", ":", "tn", ".", "TableInfo", ",", "DBName", ":", "tn", ".", "Schema", ",", "Expr", ":", "expr", ",", "TableName", ":", "tn", ",", "}", "\n", "rfs", "=", "append", "(", "rfs", ",", "rf", ")", "\n", "}", "\n", "tn", ".", "SetResultFields", "(", "rfs", ")", "\n", "return", "\n", "}" ]
// handleTableName looks up and sets the schema information and result fields for table name.
[ "handleTableName", "looks", "up", "and", "sets", "the", "schema", "information", "and", "result", "fields", "for", "table", "name", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L334-L386
train
chrislusf/gleam
sql/resolver/resolver.go
handleJoin
func (nr *nameResolver) handleJoin(j *ast.Join) { if j.Right == nil { j.SetResultFields(j.Left.GetResultFields()) return } leftLen := len(j.Left.GetResultFields()) rightLen := len(j.Right.GetResultFields()) rfs := make([]*ast.ResultField, leftLen+rightLen) copy(rfs, j.Left.GetResultFields()) copy(rfs[leftLen:], j.Right.GetResultFields()) j.SetResultFields(rfs) }
go
func (nr *nameResolver) handleJoin(j *ast.Join) { if j.Right == nil { j.SetResultFields(j.Left.GetResultFields()) return } leftLen := len(j.Left.GetResultFields()) rightLen := len(j.Right.GetResultFields()) rfs := make([]*ast.ResultField, leftLen+rightLen) copy(rfs, j.Left.GetResultFields()) copy(rfs[leftLen:], j.Right.GetResultFields()) j.SetResultFields(rfs) }
[ "func", "(", "nr", "*", "nameResolver", ")", "handleJoin", "(", "j", "*", "ast", ".", "Join", ")", "{", "if", "j", ".", "Right", "==", "nil", "{", "j", ".", "SetResultFields", "(", "j", ".", "Left", ".", "GetResultFields", "(", ")", ")", "\n", "return", "\n", "}", "\n", "leftLen", ":=", "len", "(", "j", ".", "Left", ".", "GetResultFields", "(", ")", ")", "\n", "rightLen", ":=", "len", "(", "j", ".", "Right", ".", "GetResultFields", "(", ")", ")", "\n", "rfs", ":=", "make", "(", "[", "]", "*", "ast", ".", "ResultField", ",", "leftLen", "+", "rightLen", ")", "\n", "copy", "(", "rfs", ",", "j", ".", "Left", ".", "GetResultFields", "(", ")", ")", "\n", "copy", "(", "rfs", "[", "leftLen", ":", "]", ",", "j", ".", "Right", ".", "GetResultFields", "(", ")", ")", "\n", "j", ".", "SetResultFields", "(", "rfs", ")", "\n", "}" ]
// handleJoin sets result fields for join.
[ "handleJoin", "sets", "result", "fields", "for", "join", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L440-L451
train
chrislusf/gleam
sql/resolver/resolver.go
handleColumnName
func (nr *nameResolver) handleColumnName(cn *ast.ColumnNameExpr) { ctx := nr.currentContext() if ctx.inOnCondition { // In on condition, only tables within current join is available. nr.resolveColumnNameInOnCondition(cn) return } // Try to resolve the column name form top to bottom in the context stack. for i := len(nr.contextStack) - 1; i >= 0; i-- { if nr.resolveColumnNameInContext(nr.contextStack[i], cn) { // Column is already resolved or encountered an error. if i < len(nr.contextStack)-1 { // If in subselect, the query use outer query. nr.currentContext().useOuterContext = true } return } } nr.Err = errors.Errorf("unknown column %s", cn.Name.Name.L) }
go
func (nr *nameResolver) handleColumnName(cn *ast.ColumnNameExpr) { ctx := nr.currentContext() if ctx.inOnCondition { // In on condition, only tables within current join is available. nr.resolveColumnNameInOnCondition(cn) return } // Try to resolve the column name form top to bottom in the context stack. for i := len(nr.contextStack) - 1; i >= 0; i-- { if nr.resolveColumnNameInContext(nr.contextStack[i], cn) { // Column is already resolved or encountered an error. if i < len(nr.contextStack)-1 { // If in subselect, the query use outer query. nr.currentContext().useOuterContext = true } return } } nr.Err = errors.Errorf("unknown column %s", cn.Name.Name.L) }
[ "func", "(", "nr", "*", "nameResolver", ")", "handleColumnName", "(", "cn", "*", "ast", ".", "ColumnNameExpr", ")", "{", "ctx", ":=", "nr", ".", "currentContext", "(", ")", "\n", "if", "ctx", ".", "inOnCondition", "{", "nr", ".", "resolveColumnNameInOnCondition", "(", "cn", ")", "\n", "return", "\n", "}", "\n", "for", "i", ":=", "len", "(", "nr", ".", "contextStack", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "nr", ".", "resolveColumnNameInContext", "(", "nr", ".", "contextStack", "[", "i", "]", ",", "cn", ")", "{", "if", "i", "<", "len", "(", "nr", ".", "contextStack", ")", "-", "1", "{", "nr", ".", "currentContext", "(", ")", ".", "useOuterContext", "=", "true", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "nr", ".", "Err", "=", "errors", ".", "Errorf", "(", "\"unknown column %s\"", ",", "cn", ".", "Name", ".", "Name", ".", "L", ")", "\n", "}" ]
// handleColumnName looks up and sets ResultField for // the column name.
[ "handleColumnName", "looks", "up", "and", "sets", "ResultField", "for", "the", "column", "name", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L455-L475
train
chrislusf/gleam
sql/resolver/resolver.go
resolveColumnNameInContext
func (nr *nameResolver) resolveColumnNameInContext(ctx *resolverContext, cn *ast.ColumnNameExpr) bool { if ctx.inTableRefs { // In TableRefsClause, column reference only in join on condition which is handled before. return false } if ctx.inFieldList { // only resolve column using tables. return nr.resolveColumnInTableSources(cn, ctx.tables) } if ctx.inGroupBy { // From tables first, then field list. // If ctx.InByItemExpression is true, the item is not an identifier. // Otherwise it is an identifier. if ctx.inByItemExpression { // From table first, then field list. if nr.resolveColumnInTableSources(cn, ctx.tables) { return true } found := nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) if nr.Err == nil && found { // Check if resolved refer is an aggregate function expr. if _, ok := cn.Refer.Expr.(*ast.AggregateFuncExpr); ok { nr.Err = ErrIllegalReference.Gen("Reference '%s' not supported (reference to group function)", cn.Name.Name.O) } } return found } // Resolve from table first, then from select list. found := nr.resolveColumnInTableSources(cn, ctx.tables) if nr.Err != nil { return found } // We should copy the refer here. // Because if the ByItem is an identifier, we should check if it // is ambiguous even it is already resolved from table source. // If the ByItem is not an identifier, we do not need the second check. r := cn.Refer if nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) { if nr.Err != nil { return true } if r != nil { // It is not ambiguous and already resolved from table source. // We should restore its Refer. cn.Refer = r } if _, ok := cn.Refer.Expr.(*ast.AggregateFuncExpr); ok { nr.Err = ErrIllegalReference.Gen("Reference '%s' not supported (reference to group function)", cn.Name.Name.O) } return true } return found } if ctx.inHaving { // First group by, then field list. if nr.resolveColumnInResultFields(ctx, cn, ctx.groupBy) { return true } if ctx.inHavingAgg { // If cn is in an aggregate function in having clause, check tablesource first. if nr.resolveColumnInTableSources(cn, ctx.tables) { return true } } return nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) } if ctx.inOrderBy { if nr.resolveColumnInResultFields(ctx, cn, ctx.groupBy) { return true } if ctx.inByItemExpression { // From table first, then field list. if nr.resolveColumnInTableSources(cn, ctx.tables) { return true } return nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) } // Field list first, then from table. if nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) { return true } return nr.resolveColumnInTableSources(cn, ctx.tables) } if ctx.inShow { return nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) } // In where clause. return nr.resolveColumnInTableSources(cn, ctx.tables) }
go
func (nr *nameResolver) resolveColumnNameInContext(ctx *resolverContext, cn *ast.ColumnNameExpr) bool { if ctx.inTableRefs { // In TableRefsClause, column reference only in join on condition which is handled before. return false } if ctx.inFieldList { // only resolve column using tables. return nr.resolveColumnInTableSources(cn, ctx.tables) } if ctx.inGroupBy { // From tables first, then field list. // If ctx.InByItemExpression is true, the item is not an identifier. // Otherwise it is an identifier. if ctx.inByItemExpression { // From table first, then field list. if nr.resolveColumnInTableSources(cn, ctx.tables) { return true } found := nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) if nr.Err == nil && found { // Check if resolved refer is an aggregate function expr. if _, ok := cn.Refer.Expr.(*ast.AggregateFuncExpr); ok { nr.Err = ErrIllegalReference.Gen("Reference '%s' not supported (reference to group function)", cn.Name.Name.O) } } return found } // Resolve from table first, then from select list. found := nr.resolveColumnInTableSources(cn, ctx.tables) if nr.Err != nil { return found } // We should copy the refer here. // Because if the ByItem is an identifier, we should check if it // is ambiguous even it is already resolved from table source. // If the ByItem is not an identifier, we do not need the second check. r := cn.Refer if nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) { if nr.Err != nil { return true } if r != nil { // It is not ambiguous and already resolved from table source. // We should restore its Refer. cn.Refer = r } if _, ok := cn.Refer.Expr.(*ast.AggregateFuncExpr); ok { nr.Err = ErrIllegalReference.Gen("Reference '%s' not supported (reference to group function)", cn.Name.Name.O) } return true } return found } if ctx.inHaving { // First group by, then field list. if nr.resolveColumnInResultFields(ctx, cn, ctx.groupBy) { return true } if ctx.inHavingAgg { // If cn is in an aggregate function in having clause, check tablesource first. if nr.resolveColumnInTableSources(cn, ctx.tables) { return true } } return nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) } if ctx.inOrderBy { if nr.resolveColumnInResultFields(ctx, cn, ctx.groupBy) { return true } if ctx.inByItemExpression { // From table first, then field list. if nr.resolveColumnInTableSources(cn, ctx.tables) { return true } return nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) } // Field list first, then from table. if nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) { return true } return nr.resolveColumnInTableSources(cn, ctx.tables) } if ctx.inShow { return nr.resolveColumnInResultFields(ctx, cn, ctx.fieldList) } // In where clause. return nr.resolveColumnInTableSources(cn, ctx.tables) }
[ "func", "(", "nr", "*", "nameResolver", ")", "resolveColumnNameInContext", "(", "ctx", "*", "resolverContext", ",", "cn", "*", "ast", ".", "ColumnNameExpr", ")", "bool", "{", "if", "ctx", ".", "inTableRefs", "{", "return", "false", "\n", "}", "\n", "if", "ctx", ".", "inFieldList", "{", "return", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "ctx", ".", "tables", ")", "\n", "}", "\n", "if", "ctx", ".", "inGroupBy", "{", "if", "ctx", ".", "inByItemExpression", "{", "if", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "ctx", ".", "tables", ")", "{", "return", "true", "\n", "}", "\n", "found", ":=", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "fieldList", ")", "\n", "if", "nr", ".", "Err", "==", "nil", "&&", "found", "{", "if", "_", ",", "ok", ":=", "cn", ".", "Refer", ".", "Expr", ".", "(", "*", "ast", ".", "AggregateFuncExpr", ")", ";", "ok", "{", "nr", ".", "Err", "=", "ErrIllegalReference", ".", "Gen", "(", "\"Reference '%s' not supported (reference to group function)\"", ",", "cn", ".", "Name", ".", "Name", ".", "O", ")", "\n", "}", "\n", "}", "\n", "return", "found", "\n", "}", "\n", "found", ":=", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "ctx", ".", "tables", ")", "\n", "if", "nr", ".", "Err", "!=", "nil", "{", "return", "found", "\n", "}", "\n", "r", ":=", "cn", ".", "Refer", "\n", "if", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "fieldList", ")", "{", "if", "nr", ".", "Err", "!=", "nil", "{", "return", "true", "\n", "}", "\n", "if", "r", "!=", "nil", "{", "cn", ".", "Refer", "=", "r", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "cn", ".", "Refer", ".", "Expr", ".", "(", "*", "ast", ".", "AggregateFuncExpr", ")", ";", "ok", "{", "nr", ".", "Err", "=", "ErrIllegalReference", ".", "Gen", "(", "\"Reference '%s' not supported (reference to group function)\"", ",", "cn", ".", "Name", ".", "Name", ".", "O", ")", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "return", "found", "\n", "}", "\n", "if", "ctx", ".", "inHaving", "{", "if", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "groupBy", ")", "{", "return", "true", "\n", "}", "\n", "if", "ctx", ".", "inHavingAgg", "{", "if", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "ctx", ".", "tables", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "fieldList", ")", "\n", "}", "\n", "if", "ctx", ".", "inOrderBy", "{", "if", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "groupBy", ")", "{", "return", "true", "\n", "}", "\n", "if", "ctx", ".", "inByItemExpression", "{", "if", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "ctx", ".", "tables", ")", "{", "return", "true", "\n", "}", "\n", "return", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "fieldList", ")", "\n", "}", "\n", "if", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "fieldList", ")", "{", "return", "true", "\n", "}", "\n", "return", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "ctx", ".", "tables", ")", "\n", "}", "\n", "if", "ctx", ".", "inShow", "{", "return", "nr", ".", "resolveColumnInResultFields", "(", "ctx", ",", "cn", ",", "ctx", ".", "fieldList", ")", "\n", "}", "\n", "return", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "ctx", ".", "tables", ")", "\n", "}" ]
// resolveColumnNameInContext looks up and sets ResultField for a column with the ctx.
[ "resolveColumnNameInContext", "looks", "up", "and", "sets", "ResultField", "for", "a", "column", "with", "the", "ctx", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L478-L566
train
chrislusf/gleam
sql/resolver/resolver.go
resolveColumnNameInOnCondition
func (nr *nameResolver) resolveColumnNameInOnCondition(cn *ast.ColumnNameExpr) { ctx := nr.currentContext() join := ctx.joinNodeStack[len(ctx.joinNodeStack)-1] tableSources := appendTableSources(nil, join) if !nr.resolveColumnInTableSources(cn, tableSources) { nr.Err = errors.Errorf("unknown column name %s", cn.Name.Name.O) } }
go
func (nr *nameResolver) resolveColumnNameInOnCondition(cn *ast.ColumnNameExpr) { ctx := nr.currentContext() join := ctx.joinNodeStack[len(ctx.joinNodeStack)-1] tableSources := appendTableSources(nil, join) if !nr.resolveColumnInTableSources(cn, tableSources) { nr.Err = errors.Errorf("unknown column name %s", cn.Name.Name.O) } }
[ "func", "(", "nr", "*", "nameResolver", ")", "resolveColumnNameInOnCondition", "(", "cn", "*", "ast", ".", "ColumnNameExpr", ")", "{", "ctx", ":=", "nr", ".", "currentContext", "(", ")", "\n", "join", ":=", "ctx", ".", "joinNodeStack", "[", "len", "(", "ctx", ".", "joinNodeStack", ")", "-", "1", "]", "\n", "tableSources", ":=", "appendTableSources", "(", "nil", ",", "join", ")", "\n", "if", "!", "nr", ".", "resolveColumnInTableSources", "(", "cn", ",", "tableSources", ")", "{", "nr", ".", "Err", "=", "errors", ".", "Errorf", "(", "\"unknown column name %s\"", ",", "cn", ".", "Name", ".", "Name", ".", "O", ")", "\n", "}", "\n", "}" ]
// resolveColumnNameInOnCondition resolves the column name in current join.
[ "resolveColumnNameInOnCondition", "resolves", "the", "column", "name", "in", "current", "join", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L569-L576
train
chrislusf/gleam
sql/resolver/resolver.go
handleFieldList
func (nr *nameResolver) handleFieldList(fieldList *ast.FieldList) { var resultFields []*ast.ResultField for _, v := range fieldList.Fields { resultFields = append(resultFields, nr.createResultFields(v)...) } nr.currentContext().fieldList = resultFields }
go
func (nr *nameResolver) handleFieldList(fieldList *ast.FieldList) { var resultFields []*ast.ResultField for _, v := range fieldList.Fields { resultFields = append(resultFields, nr.createResultFields(v)...) } nr.currentContext().fieldList = resultFields }
[ "func", "(", "nr", "*", "nameResolver", ")", "handleFieldList", "(", "fieldList", "*", "ast", ".", "FieldList", ")", "{", "var", "resultFields", "[", "]", "*", "ast", ".", "ResultField", "\n", "for", "_", ",", "v", ":=", "range", "fieldList", ".", "Fields", "{", "resultFields", "=", "append", "(", "resultFields", ",", "nr", ".", "createResultFields", "(", "v", ")", "...", ")", "\n", "}", "\n", "nr", ".", "currentContext", "(", ")", ".", "fieldList", "=", "resultFields", "\n", "}" ]
// handleFieldList expands wild card field and sets fieldList in current context.
[ "handleFieldList", "expands", "wild", "card", "field", "and", "sets", "fieldList", "in", "current", "context", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/resolver/resolver.go#L685-L691
train
chrislusf/gleam
sql/util/charset/charset.go
GetAllCharsets
func GetAllCharsets() []*Desc { descs := make([]*Desc, 0, len(charsets)) // The charsetInfos is an array, so the iterate order will be stable. for _, ci := range charsetInfos { c, ok := charsets[ci.Name] if !ok { continue } desc := &Desc{ Name: c.Name, DefaultCollation: c.DefaultCollation.Name, Desc: c.Desc, Maxlen: c.Maxlen, } descs = append(descs, desc) } return descs }
go
func GetAllCharsets() []*Desc { descs := make([]*Desc, 0, len(charsets)) // The charsetInfos is an array, so the iterate order will be stable. for _, ci := range charsetInfos { c, ok := charsets[ci.Name] if !ok { continue } desc := &Desc{ Name: c.Name, DefaultCollation: c.DefaultCollation.Name, Desc: c.Desc, Maxlen: c.Maxlen, } descs = append(descs, desc) } return descs }
[ "func", "GetAllCharsets", "(", ")", "[", "]", "*", "Desc", "{", "descs", ":=", "make", "(", "[", "]", "*", "Desc", ",", "0", ",", "len", "(", "charsets", ")", ")", "\n", "for", "_", ",", "ci", ":=", "range", "charsetInfos", "{", "c", ",", "ok", ":=", "charsets", "[", "ci", ".", "Name", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "desc", ":=", "&", "Desc", "{", "Name", ":", "c", ".", "Name", ",", "DefaultCollation", ":", "c", ".", "DefaultCollation", ".", "Name", ",", "Desc", ":", "c", ".", "Desc", ",", "Maxlen", ":", "c", ".", "Maxlen", ",", "}", "\n", "descs", "=", "append", "(", "descs", ",", "desc", ")", "\n", "}", "\n", "return", "descs", "\n", "}" ]
// GetAllCharsets gets all charset descriptions in the local charsets.
[ "GetAllCharsets", "gets", "all", "charset", "descriptions", "in", "the", "local", "charsets", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/charset/charset.go#L77-L94
train
chrislusf/gleam
sql/util/charset/charset.go
ValidCharsetAndCollation
func ValidCharsetAndCollation(cs string, co string) bool { // We will use utf8 as a default charset. if cs == "" { cs = "utf8" } c, ok := charsets[cs] if !ok { return false } if co == "" { return true } _, ok = c.Collations[co] if !ok { return false } return true }
go
func ValidCharsetAndCollation(cs string, co string) bool { // We will use utf8 as a default charset. if cs == "" { cs = "utf8" } c, ok := charsets[cs] if !ok { return false } if co == "" { return true } _, ok = c.Collations[co] if !ok { return false } return true }
[ "func", "ValidCharsetAndCollation", "(", "cs", "string", ",", "co", "string", ")", "bool", "{", "if", "cs", "==", "\"\"", "{", "cs", "=", "\"utf8\"", "\n", "}", "\n", "c", ",", "ok", ":=", "charsets", "[", "cs", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "if", "co", "==", "\"\"", "{", "return", "true", "\n", "}", "\n", "_", ",", "ok", "=", "c", ".", "Collations", "[", "co", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ValidCharsetAndCollation checks the charset and the collation validity // and returns a boolean.
[ "ValidCharsetAndCollation", "checks", "the", "charset", "and", "the", "collation", "validity", "and", "returns", "a", "boolean", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/charset/charset.go#L98-L118
train
chrislusf/gleam
sql/util/charset/charset.go
GetDefaultCollation
func GetDefaultCollation(charset string) (string, error) { charset = strings.ToLower(charset) if charset == CharsetBin { return CollationBin, nil } c, ok := charsets[charset] if !ok { return "", errors.Errorf("Unknown charset %s", charset) } return c.DefaultCollation.Name, nil }
go
func GetDefaultCollation(charset string) (string, error) { charset = strings.ToLower(charset) if charset == CharsetBin { return CollationBin, nil } c, ok := charsets[charset] if !ok { return "", errors.Errorf("Unknown charset %s", charset) } return c.DefaultCollation.Name, nil }
[ "func", "GetDefaultCollation", "(", "charset", "string", ")", "(", "string", ",", "error", ")", "{", "charset", "=", "strings", ".", "ToLower", "(", "charset", ")", "\n", "if", "charset", "==", "CharsetBin", "{", "return", "CollationBin", ",", "nil", "\n", "}", "\n", "c", ",", "ok", ":=", "charsets", "[", "charset", "]", "\n", "if", "!", "ok", "{", "return", "\"\"", ",", "errors", ".", "Errorf", "(", "\"Unknown charset %s\"", ",", "charset", ")", "\n", "}", "\n", "return", "c", ".", "DefaultCollation", ".", "Name", ",", "nil", "\n", "}" ]
// GetDefaultCollation returns the default collation for charset.
[ "GetDefaultCollation", "returns", "the", "default", "collation", "for", "charset", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/charset/charset.go#L121-L131
train
chrislusf/gleam
sql/util/charset/charset.go
GetCharsetInfo
func GetCharsetInfo(cs string) (string, string, error) { c, ok := charsets[strings.ToLower(cs)] if !ok { return "", "", errors.Errorf("Unknown charset %s", cs) } return c.Name, c.DefaultCollation.Name, nil }
go
func GetCharsetInfo(cs string) (string, string, error) { c, ok := charsets[strings.ToLower(cs)] if !ok { return "", "", errors.Errorf("Unknown charset %s", cs) } return c.Name, c.DefaultCollation.Name, nil }
[ "func", "GetCharsetInfo", "(", "cs", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "c", ",", "ok", ":=", "charsets", "[", "strings", ".", "ToLower", "(", "cs", ")", "]", "\n", "if", "!", "ok", "{", "return", "\"\"", ",", "\"\"", ",", "errors", ".", "Errorf", "(", "\"Unknown charset %s\"", ",", "cs", ")", "\n", "}", "\n", "return", "c", ".", "Name", ",", "c", ".", "DefaultCollation", ".", "Name", ",", "nil", "\n", "}" ]
// GetCharsetInfo returns charset and collation for cs as name.
[ "GetCharsetInfo", "returns", "charset", "and", "collation", "for", "cs", "as", "name", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/charset/charset.go#L134-L140
train
chrislusf/gleam
sql/plan/aggregation_push_down.go
tryToPushDownAgg
func (a *aggPushDownSolver) tryToPushDownAgg(aggFuncs []expression.AggregationFunction, gbyCols []*expression.Column, join *Join, childIdx int) LogicalPlan { child := join.GetChildByIndex(childIdx).(LogicalPlan) if a.allFirstRow(aggFuncs) { return child } agg := a.makeNewAgg(aggFuncs, gbyCols) child.SetParents(agg) agg.SetChildren(child) // If agg has no group-by item, it will return a default value, which may cause some bugs. // So here we add a group-by item forcely. if len(agg.GroupByItems) == 0 { agg.GroupByItems = []expression.Expression{&expression.Constant{ Value: types.NewDatum(0), RetType: types.NewFieldType(mysql.TypeLong)}} } if (childIdx == 0 && join.JoinType == RightOuterJoin) || (childIdx == 1 && join.JoinType == LeftOuterJoin) { var existsDefaultValues bool join.DefaultValues, existsDefaultValues = a.getDefaultValues(agg) if !existsDefaultValues { return child } } return agg }
go
func (a *aggPushDownSolver) tryToPushDownAgg(aggFuncs []expression.AggregationFunction, gbyCols []*expression.Column, join *Join, childIdx int) LogicalPlan { child := join.GetChildByIndex(childIdx).(LogicalPlan) if a.allFirstRow(aggFuncs) { return child } agg := a.makeNewAgg(aggFuncs, gbyCols) child.SetParents(agg) agg.SetChildren(child) // If agg has no group-by item, it will return a default value, which may cause some bugs. // So here we add a group-by item forcely. if len(agg.GroupByItems) == 0 { agg.GroupByItems = []expression.Expression{&expression.Constant{ Value: types.NewDatum(0), RetType: types.NewFieldType(mysql.TypeLong)}} } if (childIdx == 0 && join.JoinType == RightOuterJoin) || (childIdx == 1 && join.JoinType == LeftOuterJoin) { var existsDefaultValues bool join.DefaultValues, existsDefaultValues = a.getDefaultValues(agg) if !existsDefaultValues { return child } } return agg }
[ "func", "(", "a", "*", "aggPushDownSolver", ")", "tryToPushDownAgg", "(", "aggFuncs", "[", "]", "expression", ".", "AggregationFunction", ",", "gbyCols", "[", "]", "*", "expression", ".", "Column", ",", "join", "*", "Join", ",", "childIdx", "int", ")", "LogicalPlan", "{", "child", ":=", "join", ".", "GetChildByIndex", "(", "childIdx", ")", ".", "(", "LogicalPlan", ")", "\n", "if", "a", ".", "allFirstRow", "(", "aggFuncs", ")", "{", "return", "child", "\n", "}", "\n", "agg", ":=", "a", ".", "makeNewAgg", "(", "aggFuncs", ",", "gbyCols", ")", "\n", "child", ".", "SetParents", "(", "agg", ")", "\n", "agg", ".", "SetChildren", "(", "child", ")", "\n", "if", "len", "(", "agg", ".", "GroupByItems", ")", "==", "0", "{", "agg", ".", "GroupByItems", "=", "[", "]", "expression", ".", "Expression", "{", "&", "expression", ".", "Constant", "{", "Value", ":", "types", ".", "NewDatum", "(", "0", ")", ",", "RetType", ":", "types", ".", "NewFieldType", "(", "mysql", ".", "TypeLong", ")", "}", "}", "\n", "}", "\n", "if", "(", "childIdx", "==", "0", "&&", "join", ".", "JoinType", "==", "RightOuterJoin", ")", "||", "(", "childIdx", "==", "1", "&&", "join", ".", "JoinType", "==", "LeftOuterJoin", ")", "{", "var", "existsDefaultValues", "bool", "\n", "join", ".", "DefaultValues", ",", "existsDefaultValues", "=", "a", ".", "getDefaultValues", "(", "agg", ")", "\n", "if", "!", "existsDefaultValues", "{", "return", "child", "\n", "}", "\n", "}", "\n", "return", "agg", "\n", "}" ]
// tryToPushDownAgg tries to push down an aggregate function into a join path. If all aggFuncs are first row, we won't // process it temporarily. If not, We will add additional group by columns and first row functions. We make a new aggregation // operator.
[ "tryToPushDownAgg", "tries", "to", "push", "down", "an", "aggregate", "function", "into", "a", "join", "path", ".", "If", "all", "aggFuncs", "are", "first", "row", "we", "won", "t", "process", "it", "temporarily", ".", "If", "not", "We", "will", "add", "additional", "group", "by", "columns", "and", "first", "row", "functions", ".", "We", "make", "a", "new", "aggregation", "operator", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/aggregation_push_down.go#L202-L225
train
chrislusf/gleam
distributed/master/ui/svg_writer_layout.go
toStepGroupLayers
func toStepGroupLayers(status *pb.FlowExecutionStatus) (layers [][]int) { // how many step groups depenend on this step group dependencyCount := make([]int, len(status.StepGroups)) isUsed := make([]bool, len(status.StepGroups)) for _, stepGroup := range status.StepGroups { for _, parentId := range stepGroup.GetParentIds() { dependencyCount[parentId]++ } } noDependencyStepGroupIds := checkAllDepencies(dependencyCount, isUsed) for len(noDependencyStepGroupIds) > 0 { layers = append(layers, noDependencyStepGroupIds) // maintain dependencyCount after one layer for _, stepGroupId := range noDependencyStepGroupIds { for _, parentId := range status.StepGroups[stepGroupId].GetParentIds() { dependencyCount[parentId]-- } } noDependencyStepGroupIds = checkAllDepencies(dependencyCount, isUsed) } return }
go
func toStepGroupLayers(status *pb.FlowExecutionStatus) (layers [][]int) { // how many step groups depenend on this step group dependencyCount := make([]int, len(status.StepGroups)) isUsed := make([]bool, len(status.StepGroups)) for _, stepGroup := range status.StepGroups { for _, parentId := range stepGroup.GetParentIds() { dependencyCount[parentId]++ } } noDependencyStepGroupIds := checkAllDepencies(dependencyCount, isUsed) for len(noDependencyStepGroupIds) > 0 { layers = append(layers, noDependencyStepGroupIds) // maintain dependencyCount after one layer for _, stepGroupId := range noDependencyStepGroupIds { for _, parentId := range status.StepGroups[stepGroupId].GetParentIds() { dependencyCount[parentId]-- } } noDependencyStepGroupIds = checkAllDepencies(dependencyCount, isUsed) } return }
[ "func", "toStepGroupLayers", "(", "status", "*", "pb", ".", "FlowExecutionStatus", ")", "(", "layers", "[", "]", "[", "]", "int", ")", "{", "dependencyCount", ":=", "make", "(", "[", "]", "int", ",", "len", "(", "status", ".", "StepGroups", ")", ")", "\n", "isUsed", ":=", "make", "(", "[", "]", "bool", ",", "len", "(", "status", ".", "StepGroups", ")", ")", "\n", "for", "_", ",", "stepGroup", ":=", "range", "status", ".", "StepGroups", "{", "for", "_", ",", "parentId", ":=", "range", "stepGroup", ".", "GetParentIds", "(", ")", "{", "dependencyCount", "[", "parentId", "]", "++", "\n", "}", "\n", "}", "\n", "noDependencyStepGroupIds", ":=", "checkAllDepencies", "(", "dependencyCount", ",", "isUsed", ")", "\n", "for", "len", "(", "noDependencyStepGroupIds", ")", ">", "0", "{", "layers", "=", "append", "(", "layers", ",", "noDependencyStepGroupIds", ")", "\n", "for", "_", ",", "stepGroupId", ":=", "range", "noDependencyStepGroupIds", "{", "for", "_", ",", "parentId", ":=", "range", "status", ".", "StepGroups", "[", "stepGroupId", "]", ".", "GetParentIds", "(", ")", "{", "dependencyCount", "[", "parentId", "]", "--", "\n", "}", "\n", "}", "\n", "noDependencyStepGroupIds", "=", "checkAllDepencies", "(", "dependencyCount", ",", "isUsed", ")", "\n", "}", "\n", "return", "\n", "}" ]
// separate step groups into layers of step group ids via depencency analysis
[ "separate", "step", "groups", "into", "layers", "of", "step", "group", "ids", "via", "depencency", "analysis" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/master/ui/svg_writer_layout.go#L8-L35
train
chrislusf/gleam
sql/expression/builtin_string.go
argsToSpecifiedType
func argsToSpecifiedType(args []types.Datum, allString bool, allNumber bool, ctx context.Context) (newArgs []types.Datum, err error) { if allNumber { // If all arguments are numbers, they can be compared directly without type converting. return args, nil } sc := ctx.GetSessionVars().StmtCtx newArgs = make([]types.Datum, len(args)) for i, arg := range args { if allString { str, err := arg.ToString() if err != nil { return newArgs, errors.Trace(err) } newArgs[i] = types.NewStringDatum(str) } else { // If error occurred when convert arg to float64, ignore it and set f as 0. f, _ := arg.ToFloat64(sc) newArgs[i] = types.NewFloat64Datum(f) } } return }
go
func argsToSpecifiedType(args []types.Datum, allString bool, allNumber bool, ctx context.Context) (newArgs []types.Datum, err error) { if allNumber { // If all arguments are numbers, they can be compared directly without type converting. return args, nil } sc := ctx.GetSessionVars().StmtCtx newArgs = make([]types.Datum, len(args)) for i, arg := range args { if allString { str, err := arg.ToString() if err != nil { return newArgs, errors.Trace(err) } newArgs[i] = types.NewStringDatum(str) } else { // If error occurred when convert arg to float64, ignore it and set f as 0. f, _ := arg.ToFloat64(sc) newArgs[i] = types.NewFloat64Datum(f) } } return }
[ "func", "argsToSpecifiedType", "(", "args", "[", "]", "types", ".", "Datum", ",", "allString", "bool", ",", "allNumber", "bool", ",", "ctx", "context", ".", "Context", ")", "(", "newArgs", "[", "]", "types", ".", "Datum", ",", "err", "error", ")", "{", "if", "allNumber", "{", "return", "args", ",", "nil", "\n", "}", "\n", "sc", ":=", "ctx", ".", "GetSessionVars", "(", ")", ".", "StmtCtx", "\n", "newArgs", "=", "make", "(", "[", "]", "types", ".", "Datum", ",", "len", "(", "args", ")", ")", "\n", "for", "i", ",", "arg", ":=", "range", "args", "{", "if", "allString", "{", "str", ",", "err", ":=", "arg", ".", "ToString", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "newArgs", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "newArgs", "[", "i", "]", "=", "types", ".", "NewStringDatum", "(", "str", ")", "\n", "}", "else", "{", "f", ",", "_", ":=", "arg", ".", "ToFloat64", "(", "sc", ")", "\n", "newArgs", "[", "i", "]", "=", "types", ".", "NewFloat64Datum", "(", "f", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// argsToSpecifiedType converts the type of all arguments in args into string type or double type.
[ "argsToSpecifiedType", "converts", "the", "type", "of", "all", "arguments", "in", "args", "into", "string", "type", "or", "double", "type", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/builtin_string.go#L1437-L1457
train
chrislusf/gleam
distributed/executor/executor_grpc_server.go
CollectExecutionStatistics
func (exe *Executor) CollectExecutionStatistics(stream pb.GleamExecutor_CollectExecutionStatisticsServer) error { for { stats, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } for _, stat := range stats.Stats { for i, current := range exe.stats { if current.StepId == stat.StepId && current.TaskId == stat.TaskId { exe.stats[i] = stat // fmt.Printf("executor received stat: %+v\n", stat) break } } } } }
go
func (exe *Executor) CollectExecutionStatistics(stream pb.GleamExecutor_CollectExecutionStatisticsServer) error { for { stats, err := stream.Recv() if err == io.EOF { return nil } if err != nil { return err } for _, stat := range stats.Stats { for i, current := range exe.stats { if current.StepId == stat.StepId && current.TaskId == stat.TaskId { exe.stats[i] = stat // fmt.Printf("executor received stat: %+v\n", stat) break } } } } }
[ "func", "(", "exe", "*", "Executor", ")", "CollectExecutionStatistics", "(", "stream", "pb", ".", "GleamExecutor_CollectExecutionStatisticsServer", ")", "error", "{", "for", "{", "stats", ",", "err", ":=", "stream", ".", "Recv", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "stat", ":=", "range", "stats", ".", "Stats", "{", "for", "i", ",", "current", ":=", "range", "exe", ".", "stats", "{", "if", "current", ".", "StepId", "==", "stat", ".", "StepId", "&&", "current", ".", "TaskId", "==", "stat", ".", "TaskId", "{", "exe", ".", "stats", "[", "i", "]", "=", "stat", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Collect stat from "gleam execute" started mapper reducer process
[ "Collect", "stat", "from", "gleam", "execute", "started", "mapper", "reducer", "process" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/executor/executor_grpc_server.go#L19-L41
train
chrislusf/gleam
sql/util/charset/encoding_table.go
Lookup
func Lookup(label string) (e encoding.Encoding, name string) { label = strings.ToLower(strings.Trim(label, "\t\n\r\f ")) enc := encodings[label] return enc.e, enc.name }
go
func Lookup(label string) (e encoding.Encoding, name string) { label = strings.ToLower(strings.Trim(label, "\t\n\r\f ")) enc := encodings[label] return enc.e, enc.name }
[ "func", "Lookup", "(", "label", "string", ")", "(", "e", "encoding", ".", "Encoding", ",", "name", "string", ")", "{", "label", "=", "strings", ".", "ToLower", "(", "strings", ".", "Trim", "(", "label", ",", "\"\\t\\n\\r\\f \"", ")", ")", "\n", "\\t", "\n", "\\n", "\n", "}" ]
// Lookup returns the encoding with the specified label, and its canonical // name. It returns nil and the empty string if label is not one of the // standard encodings for HTML. Matching is case-insensitive and ignores // leading and trailing whitespace.
[ "Lookup", "returns", "the", "encoding", "with", "the", "specified", "label", "and", "its", "canonical", "name", ".", "It", "returns", "nil", "and", "the", "empty", "string", "if", "label", "is", "not", "one", "of", "the", "standard", "encodings", "for", "HTML", ".", "Matching", "is", "case", "-", "insensitive", "and", "ignores", "leading", "and", "trailing", "whitespace", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/charset/encoding_table.go#L32-L36
train
chrislusf/gleam
plugins/file/file_source.go
SetHasHeader
func (q *FileSource) SetHasHeader(hasHeader bool) *FileSource { q.HasHeader = hasHeader return q }
go
func (q *FileSource) SetHasHeader(hasHeader bool) *FileSource { q.HasHeader = hasHeader return q }
[ "func", "(", "q", "*", "FileSource", ")", "SetHasHeader", "(", "hasHeader", "bool", ")", "*", "FileSource", "{", "q", ".", "HasHeader", "=", "hasHeader", "\n", "return", "q", "\n", "}" ]
// SetHasHeader sets whether the data contains header
[ "SetHasHeader", "sets", "whether", "the", "data", "contains", "header" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/plugins/file/file_source.go#L38-L41
train
chrislusf/gleam
sql/util/codec/decimal.go
EncodeDecimal
func EncodeDecimal(b []byte, d types.Datum) []byte { dec := d.GetMysqlDecimal() precision := d.Length() frac := d.Frac() if precision == 0 { precision, frac = dec.PrecisionAndFrac() } b = append(b, byte(precision), byte(frac)) bin, err := dec.ToBin(precision, frac) if err != nil { log.Printf("should not happen, precision %d, frac %d %v", precision, frac, err) return b } b = append(b, bin...) return b }
go
func EncodeDecimal(b []byte, d types.Datum) []byte { dec := d.GetMysqlDecimal() precision := d.Length() frac := d.Frac() if precision == 0 { precision, frac = dec.PrecisionAndFrac() } b = append(b, byte(precision), byte(frac)) bin, err := dec.ToBin(precision, frac) if err != nil { log.Printf("should not happen, precision %d, frac %d %v", precision, frac, err) return b } b = append(b, bin...) return b }
[ "func", "EncodeDecimal", "(", "b", "[", "]", "byte", ",", "d", "types", ".", "Datum", ")", "[", "]", "byte", "{", "dec", ":=", "d", ".", "GetMysqlDecimal", "(", ")", "\n", "precision", ":=", "d", ".", "Length", "(", ")", "\n", "frac", ":=", "d", ".", "Frac", "(", ")", "\n", "if", "precision", "==", "0", "{", "precision", ",", "frac", "=", "dec", ".", "PrecisionAndFrac", "(", ")", "\n", "}", "\n", "b", "=", "append", "(", "b", ",", "byte", "(", "precision", ")", ",", "byte", "(", "frac", ")", ")", "\n", "bin", ",", "err", ":=", "dec", ".", "ToBin", "(", "precision", ",", "frac", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"should not happen, precision %d, frac %d %v\"", ",", "precision", ",", "frac", ",", "err", ")", "\n", "return", "b", "\n", "}", "\n", "b", "=", "append", "(", "b", ",", "bin", "...", ")", "\n", "return", "b", "\n", "}" ]
// EncodeDecimal encodes a decimal d into a byte slice which can be sorted lexicographically later.
[ "EncodeDecimal", "encodes", "a", "decimal", "d", "into", "a", "byte", "slice", "which", "can", "be", "sorted", "lexicographically", "later", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/codec/decimal.go#L24-L39
train
chrislusf/gleam
sql/plan/logical_plan_builder.go
buildInnerApply
func (b *planBuilder) buildInnerApply(outerPlan, innerPlan LogicalPlan) LogicalPlan { join := &Join{ JoinType: InnerJoin, baseLogicalPlan: newBaseLogicalPlan(Jn, b.allocator), } ap := &Apply{Join: *join} ap.initIDAndContext(b.ctx) ap.self = ap addChild(ap, outerPlan) addChild(ap, innerPlan) ap.SetSchema(expression.MergeSchema(outerPlan.GetSchema(), innerPlan.GetSchema())) for i := outerPlan.GetSchema().Len(); i < ap.GetSchema().Len(); i++ { ap.schema.Columns[i].IsAggOrSubq = true } ap.SetCorrelated() return ap }
go
func (b *planBuilder) buildInnerApply(outerPlan, innerPlan LogicalPlan) LogicalPlan { join := &Join{ JoinType: InnerJoin, baseLogicalPlan: newBaseLogicalPlan(Jn, b.allocator), } ap := &Apply{Join: *join} ap.initIDAndContext(b.ctx) ap.self = ap addChild(ap, outerPlan) addChild(ap, innerPlan) ap.SetSchema(expression.MergeSchema(outerPlan.GetSchema(), innerPlan.GetSchema())) for i := outerPlan.GetSchema().Len(); i < ap.GetSchema().Len(); i++ { ap.schema.Columns[i].IsAggOrSubq = true } ap.SetCorrelated() return ap }
[ "func", "(", "b", "*", "planBuilder", ")", "buildInnerApply", "(", "outerPlan", ",", "innerPlan", "LogicalPlan", ")", "LogicalPlan", "{", "join", ":=", "&", "Join", "{", "JoinType", ":", "InnerJoin", ",", "baseLogicalPlan", ":", "newBaseLogicalPlan", "(", "Jn", ",", "b", ".", "allocator", ")", ",", "}", "\n", "ap", ":=", "&", "Apply", "{", "Join", ":", "*", "join", "}", "\n", "ap", ".", "initIDAndContext", "(", "b", ".", "ctx", ")", "\n", "ap", ".", "self", "=", "ap", "\n", "addChild", "(", "ap", ",", "outerPlan", ")", "\n", "addChild", "(", "ap", ",", "innerPlan", ")", "\n", "ap", ".", "SetSchema", "(", "expression", ".", "MergeSchema", "(", "outerPlan", ".", "GetSchema", "(", ")", ",", "innerPlan", ".", "GetSchema", "(", ")", ")", ")", "\n", "for", "i", ":=", "outerPlan", ".", "GetSchema", "(", ")", ".", "Len", "(", ")", ";", "i", "<", "ap", ".", "GetSchema", "(", ")", ".", "Len", "(", ")", ";", "i", "++", "{", "ap", ".", "schema", ".", "Columns", "[", "i", "]", ".", "IsAggOrSubq", "=", "true", "\n", "}", "\n", "ap", ".", "SetCorrelated", "(", ")", "\n", "return", "ap", "\n", "}" ]
// buildInnerApply builds apply plan with outerPlan and innerPlan, which apply inner-join for every row from outerPlan and the whole innerPlan.
[ "buildInnerApply", "builds", "apply", "plan", "with", "outerPlan", "and", "innerPlan", "which", "apply", "inner", "-", "join", "for", "every", "row", "from", "outerPlan", "and", "the", "whole", "innerPlan", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/logical_plan_builder.go#L959-L975
train
chrislusf/gleam
sql/plan/refiner.go
detachTableScanConditions
func detachTableScanConditions(conditions []expression.Expression, table *model.TableInfo) ([]expression.Expression, []expression.Expression) { var pkName model.CIStr for _, colInfo := range table.Columns { if mysql.HasPriKeyFlag(colInfo.Flag) { pkName = colInfo.Name break } } if pkName.L == "" { return nil, conditions } var accessConditions, filterConditions []expression.Expression checker := conditionChecker{ tableName: table.Name, pkName: pkName} for _, cond := range conditions { cond = pushDownNot(cond, false, nil) if !checker.check(cond) { filterConditions = append(filterConditions, cond) continue } accessConditions = append(accessConditions, cond) // TODO: it will lead to repeated computation cost. if checker.shouldReserve { filterConditions = append(filterConditions, cond) checker.shouldReserve = false } } return accessConditions, filterConditions }
go
func detachTableScanConditions(conditions []expression.Expression, table *model.TableInfo) ([]expression.Expression, []expression.Expression) { var pkName model.CIStr for _, colInfo := range table.Columns { if mysql.HasPriKeyFlag(colInfo.Flag) { pkName = colInfo.Name break } } if pkName.L == "" { return nil, conditions } var accessConditions, filterConditions []expression.Expression checker := conditionChecker{ tableName: table.Name, pkName: pkName} for _, cond := range conditions { cond = pushDownNot(cond, false, nil) if !checker.check(cond) { filterConditions = append(filterConditions, cond) continue } accessConditions = append(accessConditions, cond) // TODO: it will lead to repeated computation cost. if checker.shouldReserve { filterConditions = append(filterConditions, cond) checker.shouldReserve = false } } return accessConditions, filterConditions }
[ "func", "detachTableScanConditions", "(", "conditions", "[", "]", "expression", ".", "Expression", ",", "table", "*", "model", ".", "TableInfo", ")", "(", "[", "]", "expression", ".", "Expression", ",", "[", "]", "expression", ".", "Expression", ")", "{", "var", "pkName", "model", ".", "CIStr", "\n", "for", "_", ",", "colInfo", ":=", "range", "table", ".", "Columns", "{", "if", "mysql", ".", "HasPriKeyFlag", "(", "colInfo", ".", "Flag", ")", "{", "pkName", "=", "colInfo", ".", "Name", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "pkName", ".", "L", "==", "\"\"", "{", "return", "nil", ",", "conditions", "\n", "}", "\n", "var", "accessConditions", ",", "filterConditions", "[", "]", "expression", ".", "Expression", "\n", "checker", ":=", "conditionChecker", "{", "tableName", ":", "table", ".", "Name", ",", "pkName", ":", "pkName", "}", "\n", "for", "_", ",", "cond", ":=", "range", "conditions", "{", "cond", "=", "pushDownNot", "(", "cond", ",", "false", ",", "nil", ")", "\n", "if", "!", "checker", ".", "check", "(", "cond", ")", "{", "filterConditions", "=", "append", "(", "filterConditions", ",", "cond", ")", "\n", "continue", "\n", "}", "\n", "accessConditions", "=", "append", "(", "accessConditions", ",", "cond", ")", "\n", "if", "checker", ".", "shouldReserve", "{", "filterConditions", "=", "append", "(", "filterConditions", ",", "cond", ")", "\n", "checker", ".", "shouldReserve", "=", "false", "\n", "}", "\n", "}", "\n", "return", "accessConditions", ",", "filterConditions", "\n", "}" ]
// detachTableScanConditions distinguishes between access conditions and filter conditions from conditions.
[ "detachTableScanConditions", "distinguishes", "between", "access", "conditions", "and", "filter", "conditions", "from", "conditions", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/refiner.go#L70-L101
train
chrislusf/gleam
sql/util/types/bit.go
ToString
func (b Bit) ToString() string { byteSize := (b.Width + 7) / 8 buf := make([]byte, byteSize) for i := byteSize - 1; i >= 0; i-- { buf[byteSize-i-1] = byte(b.Value >> uint(i*8)) } return string(buf) }
go
func (b Bit) ToString() string { byteSize := (b.Width + 7) / 8 buf := make([]byte, byteSize) for i := byteSize - 1; i >= 0; i-- { buf[byteSize-i-1] = byte(b.Value >> uint(i*8)) } return string(buf) }
[ "func", "(", "b", "Bit", ")", "ToString", "(", ")", "string", "{", "byteSize", ":=", "(", "b", ".", "Width", "+", "7", ")", "/", "8", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "byteSize", ")", "\n", "for", "i", ":=", "byteSize", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "buf", "[", "byteSize", "-", "i", "-", "1", "]", "=", "byte", "(", "b", ".", "Value", ">>", "uint", "(", "i", "*", "8", ")", ")", "\n", "}", "\n", "return", "string", "(", "buf", ")", "\n", "}" ]
// ToString returns the binary string for bit type.
[ "ToString", "returns", "the", "binary", "string", "for", "bit", "type", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/bit.go#L47-L54
train
chrislusf/gleam
sql/terror/terror.go
Equal
func (e *Error) Equal(err error) bool { originErr := errors.Cause(err) if originErr == nil { return false } inErr, ok := originErr.(*Error) return ok && e.class == inErr.class && e.code == inErr.code }
go
func (e *Error) Equal(err error) bool { originErr := errors.Cause(err) if originErr == nil { return false } inErr, ok := originErr.(*Error) return ok && e.class == inErr.class && e.code == inErr.code }
[ "func", "(", "e", "*", "Error", ")", "Equal", "(", "err", "error", ")", "bool", "{", "originErr", ":=", "errors", ".", "Cause", "(", "err", ")", "\n", "if", "originErr", "==", "nil", "{", "return", "false", "\n", "}", "\n", "inErr", ",", "ok", ":=", "originErr", ".", "(", "*", "Error", ")", "\n", "return", "ok", "&&", "e", ".", "class", "==", "inErr", ".", "class", "&&", "e", ".", "code", "==", "inErr", ".", "code", "\n", "}" ]
// Equal checks if err is equal to e.
[ "Equal", "checks", "if", "err", "is", "equal", "to", "e", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/terror/terror.go#L249-L256
train
chrislusf/gleam
sql/terror/terror.go
ToSQLError
func (e *Error) ToSQLError() *mysql.SQLError { code := e.getMySQLErrorCode() return mysql.NewErrf(code, e.getMsg()) }
go
func (e *Error) ToSQLError() *mysql.SQLError { code := e.getMySQLErrorCode() return mysql.NewErrf(code, e.getMsg()) }
[ "func", "(", "e", "*", "Error", ")", "ToSQLError", "(", ")", "*", "mysql", ".", "SQLError", "{", "code", ":=", "e", ".", "getMySQLErrorCode", "(", ")", "\n", "return", "mysql", ".", "NewErrf", "(", "code", ",", "e", ".", "getMsg", "(", ")", ")", "\n", "}" ]
// ToSQLError convert Error to mysql.SQLError.
[ "ToSQLError", "convert", "Error", "to", "mysql", ".", "SQLError", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/terror/terror.go#L264-L267
train