repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
topfreegames/pitaya
group.go
GroupContainsMember
func GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { if uid == "" { return false, constants.ErrEmptyUID } return groupServiceInstance.GroupContainsMember(ctx, groupName, uid) }
go
func GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { if uid == "" { return false, constants.ErrEmptyUID } return groupServiceInstance.GroupContainsMember(ctx, groupName, uid) }
[ "func", "GroupContainsMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "uid", "==", "\"", "\"", "{", "return", "false", ",", "constants", ".", "ErrEmptyUID", "\n", "}", "\n", "return", "groupServiceInstance", ".", "GroupContainsMember", "(", "ctx", ",", "groupName", ",", "uid", ")", "\n", "}" ]
// GroupContainsMember checks whether an UID is contained in group or not
[ "GroupContainsMember", "checks", "whether", "an", "UID", "is", "contained", "in", "group", "or", "not" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L84-L89
train
topfreegames/pitaya
group.go
GroupRemoveAll
func GroupRemoveAll(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRemoveAll(ctx, groupName) }
go
func GroupRemoveAll(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRemoveAll(ctx, groupName) }
[ "func", "GroupRemoveAll", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupRemoveAll", "(", "ctx", ",", "groupName", ")", "\n", "}" ]
// GroupRemoveAll clears all UIDs
[ "GroupRemoveAll", "clears", "all", "UIDs" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L107-L109
train
topfreegames/pitaya
group.go
GroupRenewTTL
func GroupRenewTTL(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRenewTTL(ctx, groupName) }
go
func GroupRenewTTL(ctx context.Context, groupName string) error { return groupServiceInstance.GroupRenewTTL(ctx, groupName) }
[ "func", "GroupRenewTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupRenewTTL", "(", "ctx", ",", "groupName", ")", "\n", "}" ]
// GroupRenewTTL renews group with the initial TTL
[ "GroupRenewTTL", "renews", "group", "with", "the", "initial", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L117-L119
train
topfreegames/pitaya
group.go
GroupDelete
func GroupDelete(ctx context.Context, groupName string) error { return groupServiceInstance.GroupDelete(ctx, groupName) }
go
func GroupDelete(ctx context.Context, groupName string) error { return groupServiceInstance.GroupDelete(ctx, groupName) }
[ "func", "GroupDelete", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "groupServiceInstance", ".", "GroupDelete", "(", "ctx", ",", "groupName", ")", "\n", "}" ]
// GroupDelete deletes whole group, including UIDs and base group
[ "GroupDelete", "deletes", "whole", "group", "including", "UIDs", "and", "base", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/group.go#L122-L124
train
topfreegames/pitaya
push.go
SendPushToUsers
func SendPushToUsers(route string, v interface{}, uids []string, frontendType string) ([]string, error) { data, err := util.SerializeOrRaw(app.serializer, v) if err != nil { return uids, err } if !app.server.Frontend && frontendType == "" { return uids, constants.ErrFrontendTypeNotSpecified } var notPushedUids []string logger.Log.Debugf("Type=PushToUsers Route=%s, Data=%+v, SvType=%s, #Users=%d", route, v, frontendType, len(uids)) for _, uid := range uids { if s := session.GetSessionByUID(uid); s != nil && app.server.Type == frontendType { if err := s.Push(route, data); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("Session push message error, ID=%d, UID=%d, Error=%s", s.ID(), s.UID(), err.Error()) } } else if app.rpcClient != nil { push := &protos.Push{ Route: route, Uid: uid, Data: data, } if err = app.rpcClient.SendPush(uid, &cluster.Server{Type: frontendType}, push); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("RPCClient send message error, UID=%s, SvType=%s, Error=%s", uid, frontendType, err.Error()) } } else { notPushedUids = append(notPushedUids, uid) } } if len(notPushedUids) != 0 { return notPushedUids, constants.ErrPushingToUsers } return nil, nil }
go
func SendPushToUsers(route string, v interface{}, uids []string, frontendType string) ([]string, error) { data, err := util.SerializeOrRaw(app.serializer, v) if err != nil { return uids, err } if !app.server.Frontend && frontendType == "" { return uids, constants.ErrFrontendTypeNotSpecified } var notPushedUids []string logger.Log.Debugf("Type=PushToUsers Route=%s, Data=%+v, SvType=%s, #Users=%d", route, v, frontendType, len(uids)) for _, uid := range uids { if s := session.GetSessionByUID(uid); s != nil && app.server.Type == frontendType { if err := s.Push(route, data); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("Session push message error, ID=%d, UID=%d, Error=%s", s.ID(), s.UID(), err.Error()) } } else if app.rpcClient != nil { push := &protos.Push{ Route: route, Uid: uid, Data: data, } if err = app.rpcClient.SendPush(uid, &cluster.Server{Type: frontendType}, push); err != nil { notPushedUids = append(notPushedUids, uid) logger.Log.Errorf("RPCClient send message error, UID=%s, SvType=%s, Error=%s", uid, frontendType, err.Error()) } } else { notPushedUids = append(notPushedUids, uid) } } if len(notPushedUids) != 0 { return notPushedUids, constants.ErrPushingToUsers } return nil, nil }
[ "func", "SendPushToUsers", "(", "route", "string", ",", "v", "interface", "{", "}", ",", "uids", "[", "]", "string", ",", "frontendType", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "data", ",", "err", ":=", "util", ".", "SerializeOrRaw", "(", "app", ".", "serializer", ",", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "uids", ",", "err", "\n", "}", "\n\n", "if", "!", "app", ".", "server", ".", "Frontend", "&&", "frontendType", "==", "\"", "\"", "{", "return", "uids", ",", "constants", ".", "ErrFrontendTypeNotSpecified", "\n", "}", "\n\n", "var", "notPushedUids", "[", "]", "string", "\n\n", "logger", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "route", ",", "v", ",", "frontendType", ",", "len", "(", "uids", ")", ")", "\n\n", "for", "_", ",", "uid", ":=", "range", "uids", "{", "if", "s", ":=", "session", ".", "GetSessionByUID", "(", "uid", ")", ";", "s", "!=", "nil", "&&", "app", ".", "server", ".", "Type", "==", "frontendType", "{", "if", "err", ":=", "s", ".", "Push", "(", "route", ",", "data", ")", ";", "err", "!=", "nil", "{", "notPushedUids", "=", "append", "(", "notPushedUids", ",", "uid", ")", "\n", "logger", ".", "Log", ".", "Errorf", "(", "\"", "\"", ",", "s", ".", "ID", "(", ")", ",", "s", ".", "UID", "(", ")", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "if", "app", ".", "rpcClient", "!=", "nil", "{", "push", ":=", "&", "protos", ".", "Push", "{", "Route", ":", "route", ",", "Uid", ":", "uid", ",", "Data", ":", "data", ",", "}", "\n", "if", "err", "=", "app", ".", "rpcClient", ".", "SendPush", "(", "uid", ",", "&", "cluster", ".", "Server", "{", "Type", ":", "frontendType", "}", ",", "push", ")", ";", "err", "!=", "nil", "{", "notPushedUids", "=", "append", "(", "notPushedUids", ",", "uid", ")", "\n", "logger", ".", "Log", ".", "Errorf", "(", "\"", "\"", ",", "uid", ",", "frontendType", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "notPushedUids", "=", "append", "(", "notPushedUids", ",", "uid", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "notPushedUids", ")", "!=", "0", "{", "return", "notPushedUids", ",", "constants", ".", "ErrPushingToUsers", "\n", "}", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// SendPushToUsers sends a message to the given list of users
[ "SendPushToUsers", "sends", "a", "message", "to", "the", "given", "list", "of", "users" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/push.go#L33-L74
train
topfreegames/pitaya
cluster/grpc_rpc_server.go
Init
func (gs *GRPCServer) Init() error { port := gs.config.GetInt("pitaya.cluster.rpc.server.grpc.port") lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { return err } gs.grpcSv = grpc.NewServer() protos.RegisterPitayaServer(gs.grpcSv, gs.pitayaServer) go gs.grpcSv.Serve(lis) return nil }
go
func (gs *GRPCServer) Init() error { port := gs.config.GetInt("pitaya.cluster.rpc.server.grpc.port") lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { return err } gs.grpcSv = grpc.NewServer() protos.RegisterPitayaServer(gs.grpcSv, gs.pitayaServer) go gs.grpcSv.Serve(lis) return nil }
[ "func", "(", "gs", "*", "GRPCServer", ")", "Init", "(", ")", "error", "{", "port", ":=", "gs", ".", "config", ".", "GetInt", "(", "\"", "\"", ")", "\n", "lis", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "port", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "gs", ".", "grpcSv", "=", "grpc", ".", "NewServer", "(", ")", "\n", "protos", ".", "RegisterPitayaServer", "(", "gs", ".", "grpcSv", ",", "gs", ".", "pitayaServer", ")", "\n", "go", "gs", ".", "grpcSv", ".", "Serve", "(", "lis", ")", "\n", "return", "nil", "\n", "}" ]
// Init inits grpc rpc server
[ "Init", "inits", "grpc", "rpc", "server" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/cluster/grpc_rpc_server.go#L54-L64
train
topfreegames/pitaya
metrics/report.go
ReportTimingFromCtx
func ReportTimingFromCtx(ctx context.Context, reporters []Reporter, typ string, err error) { code := errors.CodeFromError(err) status := "ok" if err != nil { status = "failed" } if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) tags := getTags(ctx, map[string]string{ "route": route.(string), "status": status, "type": typ, "code": code, }) for _, r := range reporters { r.ReportSummary(ResponseTime, tags, float64(elapsed.Nanoseconds())) } } }
go
func ReportTimingFromCtx(ctx context.Context, reporters []Reporter, typ string, err error) { code := errors.CodeFromError(err) status := "ok" if err != nil { status = "failed" } if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) tags := getTags(ctx, map[string]string{ "route": route.(string), "status": status, "type": typ, "code": code, }) for _, r := range reporters { r.ReportSummary(ResponseTime, tags, float64(elapsed.Nanoseconds())) } } }
[ "func", "ReportTimingFromCtx", "(", "ctx", "context", ".", "Context", ",", "reporters", "[", "]", "Reporter", ",", "typ", "string", ",", "err", "error", ")", "{", "code", ":=", "errors", ".", "CodeFromError", "(", "err", ")", "\n", "status", ":=", "\"", "\"", "\n", "if", "err", "!=", "nil", "{", "status", "=", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "reporters", ")", ">", "0", "{", "startTime", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "StartTimeKey", ")", "\n", "route", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RouteKey", ")", "\n", "elapsed", ":=", "time", ".", "Since", "(", "time", ".", "Unix", "(", "0", ",", "startTime", ".", "(", "int64", ")", ")", ")", "\n", "tags", ":=", "getTags", "(", "ctx", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "route", ".", "(", "string", ")", ",", "\"", "\"", ":", "status", ",", "\"", "\"", ":", "typ", ",", "\"", "\"", ":", "code", ",", "}", ")", "\n", "for", "_", ",", "r", ":=", "range", "reporters", "{", "r", ".", "ReportSummary", "(", "ResponseTime", ",", "tags", ",", "float64", "(", "elapsed", ".", "Nanoseconds", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ReportTimingFromCtx reports the latency from the context
[ "ReportTimingFromCtx", "reports", "the", "latency", "from", "the", "context" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L35-L55
train
topfreegames/pitaya
metrics/report.go
ReportMessageProcessDelayFromCtx
func ReportMessageProcessDelayFromCtx(ctx context.Context, reporters []Reporter, typ string) { if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) tags := getTags(ctx, map[string]string{ "route": route.(string), "type": typ, }) for _, r := range reporters { r.ReportSummary(ProcessDelay, tags, float64(elapsed.Nanoseconds())) } } }
go
func ReportMessageProcessDelayFromCtx(ctx context.Context, reporters []Reporter, typ string) { if len(reporters) > 0 { startTime := pcontext.GetFromPropagateCtx(ctx, constants.StartTimeKey) elapsed := time.Since(time.Unix(0, startTime.(int64))) route := pcontext.GetFromPropagateCtx(ctx, constants.RouteKey) tags := getTags(ctx, map[string]string{ "route": route.(string), "type": typ, }) for _, r := range reporters { r.ReportSummary(ProcessDelay, tags, float64(elapsed.Nanoseconds())) } } }
[ "func", "ReportMessageProcessDelayFromCtx", "(", "ctx", "context", ".", "Context", ",", "reporters", "[", "]", "Reporter", ",", "typ", "string", ")", "{", "if", "len", "(", "reporters", ")", ">", "0", "{", "startTime", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "StartTimeKey", ")", "\n", "elapsed", ":=", "time", ".", "Since", "(", "time", ".", "Unix", "(", "0", ",", "startTime", ".", "(", "int64", ")", ")", ")", "\n", "route", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RouteKey", ")", "\n", "tags", ":=", "getTags", "(", "ctx", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "route", ".", "(", "string", ")", ",", "\"", "\"", ":", "typ", ",", "}", ")", "\n", "for", "_", ",", "r", ":=", "range", "reporters", "{", "r", ".", "ReportSummary", "(", "ProcessDelay", ",", "tags", ",", "float64", "(", "elapsed", ".", "Nanoseconds", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// ReportMessageProcessDelayFromCtx reports the delay to process the messages
[ "ReportMessageProcessDelayFromCtx", "reports", "the", "delay", "to", "process", "the", "messages" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L58-L71
train
topfreegames/pitaya
metrics/report.go
ReportNumberOfConnectedClients
func ReportNumberOfConnectedClients(reporters []Reporter, number int64) { for _, r := range reporters { r.ReportGauge(ConnectedClients, map[string]string{}, float64(number)) } }
go
func ReportNumberOfConnectedClients(reporters []Reporter, number int64) { for _, r := range reporters { r.ReportGauge(ConnectedClients, map[string]string{}, float64(number)) } }
[ "func", "ReportNumberOfConnectedClients", "(", "reporters", "[", "]", "Reporter", ",", "number", "int64", ")", "{", "for", "_", ",", "r", ":=", "range", "reporters", "{", "r", ".", "ReportGauge", "(", "ConnectedClients", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "number", ")", ")", "\n", "}", "\n", "}" ]
// ReportNumberOfConnectedClients reports the number of connected clients
[ "ReportNumberOfConnectedClients", "reports", "the", "number", "of", "connected", "clients" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L74-L78
train
topfreegames/pitaya
metrics/report.go
ReportSysMetrics
func ReportSysMetrics(reporters []Reporter, period time.Duration) { for { for _, r := range reporters { num := runtime.NumGoroutine() m := &runtime.MemStats{} runtime.ReadMemStats(m) r.ReportGauge(Goroutines, map[string]string{}, float64(num)) r.ReportGauge(HeapSize, map[string]string{}, float64(m.Alloc)) r.ReportGauge(HeapObjects, map[string]string{}, float64(m.HeapObjects)) } time.Sleep(period) } }
go
func ReportSysMetrics(reporters []Reporter, period time.Duration) { for { for _, r := range reporters { num := runtime.NumGoroutine() m := &runtime.MemStats{} runtime.ReadMemStats(m) r.ReportGauge(Goroutines, map[string]string{}, float64(num)) r.ReportGauge(HeapSize, map[string]string{}, float64(m.Alloc)) r.ReportGauge(HeapObjects, map[string]string{}, float64(m.HeapObjects)) } time.Sleep(period) } }
[ "func", "ReportSysMetrics", "(", "reporters", "[", "]", "Reporter", ",", "period", "time", ".", "Duration", ")", "{", "for", "{", "for", "_", ",", "r", ":=", "range", "reporters", "{", "num", ":=", "runtime", ".", "NumGoroutine", "(", ")", "\n", "m", ":=", "&", "runtime", ".", "MemStats", "{", "}", "\n", "runtime", ".", "ReadMemStats", "(", "m", ")", "\n\n", "r", ".", "ReportGauge", "(", "Goroutines", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "num", ")", ")", "\n", "r", ".", "ReportGauge", "(", "HeapSize", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "m", ".", "Alloc", ")", ")", "\n", "r", ".", "ReportGauge", "(", "HeapObjects", ",", "map", "[", "string", "]", "string", "{", "}", ",", "float64", "(", "m", ".", "HeapObjects", ")", ")", "\n", "}", "\n\n", "time", ".", "Sleep", "(", "period", ")", "\n", "}", "\n", "}" ]
// ReportSysMetrics reports sys metrics
[ "ReportSysMetrics", "reports", "sys", "metrics" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/metrics/report.go#L81-L95
train
topfreegames/pitaya
groups/memory_group_service.go
NewMemoryGroupService
func NewMemoryGroupService(conf *config.Config) *MemoryGroupService { memoryOnce.Do(func() { memoryGroups = make(map[string]*MemoryGroup) go groupTTLCleanup(conf) }) return &MemoryGroupService{} }
go
func NewMemoryGroupService(conf *config.Config) *MemoryGroupService { memoryOnce.Do(func() { memoryGroups = make(map[string]*MemoryGroup) go groupTTLCleanup(conf) }) return &MemoryGroupService{} }
[ "func", "NewMemoryGroupService", "(", "conf", "*", "config", ".", "Config", ")", "*", "MemoryGroupService", "{", "memoryOnce", ".", "Do", "(", "func", "(", ")", "{", "memoryGroups", "=", "make", "(", "map", "[", "string", "]", "*", "MemoryGroup", ")", "\n", "go", "groupTTLCleanup", "(", "conf", ")", "\n", "}", ")", "\n", "return", "&", "MemoryGroupService", "{", "}", "\n", "}" ]
// NewMemoryGroupService returns a new group instance
[ "NewMemoryGroupService", "returns", "a", "new", "group", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L30-L36
train
topfreegames/pitaya
groups/memory_group_service.go
GroupCreate
func (c *MemoryGroupService) GroupCreate(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{} return nil }
go
func (c *MemoryGroupService) GroupCreate(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{} return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupCreate", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", ";", "ok", "{", "return", "constants", ".", "ErrGroupAlreadyExists", "\n", "}", "\n\n", "memoryGroups", "[", "groupName", "]", "=", "&", "MemoryGroup", "{", "}", "\n", "return", "nil", "\n", "}" ]
// GroupCreate creates a group without TTL
[ "GroupCreate", "creates", "a", "group", "without", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L51-L61
train
topfreegames/pitaya
groups/memory_group_service.go
GroupCreateWithTTL
func (c *MemoryGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{LastRefresh: time.Now().UnixNano(), TTL: ttlTime.Nanoseconds()} return nil }
go
func (c *MemoryGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() if _, ok := memoryGroups[groupName]; ok { return constants.ErrGroupAlreadyExists } memoryGroups[groupName] = &MemoryGroup{LastRefresh: time.Now().UnixNano(), TTL: ttlTime.Nanoseconds()} return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupCreateWithTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ",", "ttlTime", "time", ".", "Duration", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", ";", "ok", "{", "return", "constants", ".", "ErrGroupAlreadyExists", "\n", "}", "\n\n", "memoryGroups", "[", "groupName", "]", "=", "&", "MemoryGroup", "{", "LastRefresh", ":", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ",", "TTL", ":", "ttlTime", ".", "Nanoseconds", "(", ")", "}", "\n", "return", "nil", "\n", "}" ]
// GroupCreateWithTTL creates a group with TTL, which the go routine will clean later
[ "GroupCreateWithTTL", "creates", "a", "group", "with", "TTL", "which", "the", "go", "routine", "will", "clean", "later" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L64-L74
train
topfreegames/pitaya
groups/memory_group_service.go
GroupMembers
func (c *MemoryGroupService) GroupMembers(ctx context.Context, groupName string) ([]string, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return nil, constants.ErrGroupNotFound } uids := make([]string, len(mg.Uids)) copy(uids, mg.Uids) return uids, nil }
go
func (c *MemoryGroupService) GroupMembers(ctx context.Context, groupName string) ([]string, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return nil, constants.ErrGroupNotFound } uids := make([]string, len(mg.Uids)) copy(uids, mg.Uids) return uids, nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupMembers", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n\n", "uids", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "mg", ".", "Uids", ")", ")", "\n", "copy", "(", "uids", ",", "mg", ".", "Uids", ")", "\n\n", "return", "uids", ",", "nil", "\n", "}" ]
// GroupMembers returns all member's UID in given group
[ "GroupMembers", "returns", "all", "member", "s", "UID", "in", "given", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L77-L90
train
topfreegames/pitaya
groups/memory_group_service.go
GroupContainsMember
func (c *MemoryGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return false, constants.ErrGroupNotFound } _, contains := elementIndex(mg.Uids, uid) return contains, nil }
go
func (c *MemoryGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return false, constants.ErrGroupNotFound } _, contains := elementIndex(mg.Uids, uid) return contains, nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupContainsMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "(", "bool", ",", "error", ")", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "false", ",", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n\n", "_", ",", "contains", ":=", "elementIndex", "(", "mg", ".", "Uids", ",", "uid", ")", "\n", "return", "contains", ",", "nil", "\n", "}" ]
// GroupContainsMember check whether an UID is contained in given group or not
[ "GroupContainsMember", "check", "whether", "an", "UID", "is", "contained", "in", "given", "group", "or", "not" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L93-L104
train
topfreegames/pitaya
groups/memory_group_service.go
GroupRemoveMember
func (c *MemoryGroupService) GroupRemoveMember(ctx context.Context, groupName, uid string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } index, contains := elementIndex(mg.Uids, uid) if contains { mg.Uids[index] = mg.Uids[len(mg.Uids)-1] mg.Uids = mg.Uids[:len(mg.Uids)-1] memoryGroups[groupName] = mg return nil } return constants.ErrMemberNotFound }
go
func (c *MemoryGroupService) GroupRemoveMember(ctx context.Context, groupName, uid string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } index, contains := elementIndex(mg.Uids, uid) if contains { mg.Uids[index] = mg.Uids[len(mg.Uids)-1] mg.Uids = mg.Uids[:len(mg.Uids)-1] memoryGroups[groupName] = mg return nil } return constants.ErrMemberNotFound }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupRemoveMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "index", ",", "contains", ":=", "elementIndex", "(", "mg", ".", "Uids", ",", "uid", ")", "\n", "if", "contains", "{", "mg", ".", "Uids", "[", "index", "]", "=", "mg", ".", "Uids", "[", "len", "(", "mg", ".", "Uids", ")", "-", "1", "]", "\n", "mg", ".", "Uids", "=", "mg", ".", "Uids", "[", ":", "len", "(", "mg", ".", "Uids", ")", "-", "1", "]", "\n", "memoryGroups", "[", "groupName", "]", "=", "mg", "\n", "return", "nil", "\n", "}", "\n\n", "return", "constants", ".", "ErrMemberNotFound", "\n", "}" ]
// GroupRemoveMember removes specific UID from group
[ "GroupRemoveMember", "removes", "specific", "UID", "from", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L127-L144
train
topfreegames/pitaya
groups/memory_group_service.go
GroupRemoveAll
func (c *MemoryGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } mg.Uids = []string{} return nil }
go
func (c *MemoryGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } mg.Uids = []string{} return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupRemoveAll", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n\n", "mg", ".", "Uids", "=", "[", "]", "string", "{", "}", "\n", "return", "nil", "\n", "}" ]
// GroupRemoveAll clears all UIDs from group
[ "GroupRemoveAll", "clears", "all", "UIDs", "from", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L147-L158
train
topfreegames/pitaya
groups/memory_group_service.go
GroupDelete
func (c *MemoryGroupService) GroupDelete(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() _, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } delete(memoryGroups, groupName) return nil }
go
func (c *MemoryGroupService) GroupDelete(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() _, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } delete(memoryGroups, groupName) return nil }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupDelete", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "_", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n\n", "delete", "(", "memoryGroups", ",", "groupName", ")", "\n", "return", "nil", "\n", "}" ]
// GroupDelete deletes the whole group, including members and base group
[ "GroupDelete", "deletes", "the", "whole", "group", "including", "members", "and", "base", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L161-L172
train
topfreegames/pitaya
groups/memory_group_service.go
GroupRenewTTL
func (c *MemoryGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } if mg.TTL != 0 { mg.LastRefresh = time.Now().UnixNano() memoryGroups[groupName] = mg return nil } return constants.ErrMemoryTTLNotFound }
go
func (c *MemoryGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { memoryGroupsMu.Lock() defer memoryGroupsMu.Unlock() mg, ok := memoryGroups[groupName] if !ok { return constants.ErrGroupNotFound } if mg.TTL != 0 { mg.LastRefresh = time.Now().UnixNano() memoryGroups[groupName] = mg return nil } return constants.ErrMemoryTTLNotFound }
[ "func", "(", "c", "*", "MemoryGroupService", ")", "GroupRenewTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "memoryGroupsMu", ".", "Lock", "(", ")", "\n", "defer", "memoryGroupsMu", ".", "Unlock", "(", ")", "\n\n", "mg", ",", "ok", ":=", "memoryGroups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n\n", "if", "mg", ".", "TTL", "!=", "0", "{", "mg", ".", "LastRefresh", "=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "memoryGroups", "[", "groupName", "]", "=", "mg", "\n", "return", "nil", "\n", "}", "\n", "return", "constants", ".", "ErrMemoryTTLNotFound", "\n", "}" ]
// GroupRenewTTL will renew lease TTL
[ "GroupRenewTTL", "will", "renew", "lease", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/memory_group_service.go#L188-L203
train
topfreegames/pitaya
modules/binding_storage.go
NewETCDBindingStorage
func NewETCDBindingStorage(server *cluster.Server, conf *config.Config) *ETCDBindingStorage { b := &ETCDBindingStorage{ config: conf, thisServer: server, stopChan: make(chan struct{}), } b.configure() return b }
go
func NewETCDBindingStorage(server *cluster.Server, conf *config.Config) *ETCDBindingStorage { b := &ETCDBindingStorage{ config: conf, thisServer: server, stopChan: make(chan struct{}), } b.configure() return b }
[ "func", "NewETCDBindingStorage", "(", "server", "*", "cluster", ".", "Server", ",", "conf", "*", "config", ".", "Config", ")", "*", "ETCDBindingStorage", "{", "b", ":=", "&", "ETCDBindingStorage", "{", "config", ":", "conf", ",", "thisServer", ":", "server", ",", "stopChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "b", ".", "configure", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewETCDBindingStorage returns a new instance of BindingStorage
[ "NewETCDBindingStorage", "returns", "a", "new", "instance", "of", "BindingStorage" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/binding_storage.go#L52-L60
train
topfreegames/pitaya
modules/binding_storage.go
PutBinding
func (b *ETCDBindingStorage) PutBinding(uid string) error { _, err := b.cli.Put(context.Background(), getUserBindingKey(uid, b.thisServer.Type), b.thisServer.ID, clientv3.WithLease(b.leaseID)) return err }
go
func (b *ETCDBindingStorage) PutBinding(uid string) error { _, err := b.cli.Put(context.Background(), getUserBindingKey(uid, b.thisServer.Type), b.thisServer.ID, clientv3.WithLease(b.leaseID)) return err }
[ "func", "(", "b", "*", "ETCDBindingStorage", ")", "PutBinding", "(", "uid", "string", ")", "error", "{", "_", ",", "err", ":=", "b", ".", "cli", ".", "Put", "(", "context", ".", "Background", "(", ")", ",", "getUserBindingKey", "(", "uid", ",", "b", ".", "thisServer", ".", "Type", ")", ",", "b", ".", "thisServer", ".", "ID", ",", "clientv3", ".", "WithLease", "(", "b", ".", "leaseID", ")", ")", "\n", "return", "err", "\n", "}" ]
// PutBinding puts the binding info into etcd
[ "PutBinding", "puts", "the", "binding", "info", "into", "etcd" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/binding_storage.go#L74-L77
train
topfreegames/pitaya
modules/binding_storage.go
Init
func (b *ETCDBindingStorage) Init() error { var cli *clientv3.Client var err error if b.cli == nil { cli, err = clientv3.New(clientv3.Config{ Endpoints: b.etcdEndpoints, DialTimeout: b.etcdDialTimeout, }) if err != nil { return err } b.cli = cli } // namespaced etcd :) b.cli.KV = namespace.NewKV(b.cli.KV, b.etcdPrefix) err = b.bootstrapLease() if err != nil { return err } if b.thisServer.Frontend { b.setupOnSessionCloseCB() b.setupOnAfterSessionBindCB() } return nil }
go
func (b *ETCDBindingStorage) Init() error { var cli *clientv3.Client var err error if b.cli == nil { cli, err = clientv3.New(clientv3.Config{ Endpoints: b.etcdEndpoints, DialTimeout: b.etcdDialTimeout, }) if err != nil { return err } b.cli = cli } // namespaced etcd :) b.cli.KV = namespace.NewKV(b.cli.KV, b.etcdPrefix) err = b.bootstrapLease() if err != nil { return err } if b.thisServer.Frontend { b.setupOnSessionCloseCB() b.setupOnAfterSessionBindCB() } return nil }
[ "func", "(", "b", "*", "ETCDBindingStorage", ")", "Init", "(", ")", "error", "{", "var", "cli", "*", "clientv3", ".", "Client", "\n", "var", "err", "error", "\n", "if", "b", ".", "cli", "==", "nil", "{", "cli", ",", "err", "=", "clientv3", ".", "New", "(", "clientv3", ".", "Config", "{", "Endpoints", ":", "b", ".", "etcdEndpoints", ",", "DialTimeout", ":", "b", ".", "etcdDialTimeout", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "b", ".", "cli", "=", "cli", "\n", "}", "\n", "// namespaced etcd :)", "b", ".", "cli", ".", "KV", "=", "namespace", ".", "NewKV", "(", "b", ".", "cli", ".", "KV", ",", "b", ".", "etcdPrefix", ")", "\n", "err", "=", "b", ".", "bootstrapLease", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "b", ".", "thisServer", ".", "Frontend", "{", "b", ".", "setupOnSessionCloseCB", "(", ")", "\n", "b", ".", "setupOnAfterSessionBindCB", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Init starts the binding storage module
[ "Init", "starts", "the", "binding", "storage", "module" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/binding_storage.go#L159-L185
train
topfreegames/pitaya
modules/api_docs_gen.go
NewAPIDocsGen
func NewAPIDocsGen(basePath string, services []*component.Service) *APIDocsGen { return &APIDocsGen{ basePath: basePath, services: services, } }
go
func NewAPIDocsGen(basePath string, services []*component.Service) *APIDocsGen { return &APIDocsGen{ basePath: basePath, services: services, } }
[ "func", "NewAPIDocsGen", "(", "basePath", "string", ",", "services", "[", "]", "*", "component", ".", "Service", ")", "*", "APIDocsGen", "{", "return", "&", "APIDocsGen", "{", "basePath", ":", "basePath", ",", "services", ":", "services", ",", "}", "\n", "}" ]
// NewAPIDocsGen creates a new APIDocsGen
[ "NewAPIDocsGen", "creates", "a", "new", "APIDocsGen" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/api_docs_gen.go#L36-L41
train
topfreegames/pitaya
modules/api_docs_gen.go
Init
func (a *APIDocsGen) Init() error { for _, s := range a.services { logger.Log.Infof("loaded svc: %s", s.Name) } return nil }
go
func (a *APIDocsGen) Init() error { for _, s := range a.services { logger.Log.Infof("loaded svc: %s", s.Name) } return nil }
[ "func", "(", "a", "*", "APIDocsGen", ")", "Init", "(", ")", "error", "{", "for", "_", ",", "s", ":=", "range", "a", ".", "services", "{", "logger", ".", "Log", ".", "Infof", "(", "\"", "\"", ",", "s", ".", "Name", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init is called on init method
[ "Init", "is", "called", "on", "init", "method" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/modules/api_docs_gen.go#L44-L49
train
topfreegames/pitaya
tracing/jaeger/config.go
Configure
func Configure(options Options) (io.Closer, error) { cfg := config.Configuration{ Disabled: options.Disabled, Sampler: &config.SamplerConfig{ Type: jaeger.SamplerTypeProbabilistic, Param: options.Probability, }, } return cfg.InitGlobalTracer(options.ServiceName) }
go
func Configure(options Options) (io.Closer, error) { cfg := config.Configuration{ Disabled: options.Disabled, Sampler: &config.SamplerConfig{ Type: jaeger.SamplerTypeProbabilistic, Param: options.Probability, }, } return cfg.InitGlobalTracer(options.ServiceName) }
[ "func", "Configure", "(", "options", "Options", ")", "(", "io", ".", "Closer", ",", "error", ")", "{", "cfg", ":=", "config", ".", "Configuration", "{", "Disabled", ":", "options", ".", "Disabled", ",", "Sampler", ":", "&", "config", ".", "SamplerConfig", "{", "Type", ":", "jaeger", ".", "SamplerTypeProbabilistic", ",", "Param", ":", "options", ".", "Probability", ",", "}", ",", "}", "\n\n", "return", "cfg", ".", "InitGlobalTracer", "(", "options", ".", "ServiceName", ")", "\n", "}" ]
// Configure configures a global Jaeger tracer
[ "Configure", "configures", "a", "global", "Jaeger", "tracer" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/tracing/jaeger/config.go#L40-L50
train
topfreegames/pitaya
config/config.go
NewConfig
func NewConfig(cfgs ...*viper.Viper) *Config { var cfg *viper.Viper if len(cfgs) > 0 { cfg = cfgs[0] } else { cfg = viper.New() } cfg.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) cfg.AutomaticEnv() c := &Config{config: cfg} c.fillDefaultValues() return c }
go
func NewConfig(cfgs ...*viper.Viper) *Config { var cfg *viper.Viper if len(cfgs) > 0 { cfg = cfgs[0] } else { cfg = viper.New() } cfg.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) cfg.AutomaticEnv() c := &Config{config: cfg} c.fillDefaultValues() return c }
[ "func", "NewConfig", "(", "cfgs", "...", "*", "viper", ".", "Viper", ")", "*", "Config", "{", "var", "cfg", "*", "viper", ".", "Viper", "\n", "if", "len", "(", "cfgs", ")", ">", "0", "{", "cfg", "=", "cfgs", "[", "0", "]", "\n", "}", "else", "{", "cfg", "=", "viper", ".", "New", "(", ")", "\n", "}", "\n\n", "cfg", ".", "SetEnvKeyReplacer", "(", "strings", ".", "NewReplacer", "(", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "cfg", ".", "AutomaticEnv", "(", ")", "\n", "c", ":=", "&", "Config", "{", "config", ":", "cfg", "}", "\n", "c", ".", "fillDefaultValues", "(", ")", "\n", "return", "c", "\n", "}" ]
// NewConfig creates a new config with a given viper config if given
[ "NewConfig", "creates", "a", "new", "config", "with", "a", "given", "viper", "config", "if", "given" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L36-L49
train
topfreegames/pitaya
config/config.go
GetDuration
func (c *Config) GetDuration(s string) time.Duration { return c.config.GetDuration(s) }
go
func (c *Config) GetDuration(s string) time.Duration { return c.config.GetDuration(s) }
[ "func", "(", "c", "*", "Config", ")", "GetDuration", "(", "s", "string", ")", "time", ".", "Duration", "{", "return", "c", ".", "config", ".", "GetDuration", "(", "s", ")", "\n", "}" ]
// GetDuration returns a duration from the inner config
[ "GetDuration", "returns", "a", "duration", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L128-L130
train
topfreegames/pitaya
config/config.go
GetString
func (c *Config) GetString(s string) string { return c.config.GetString(s) }
go
func (c *Config) GetString(s string) string { return c.config.GetString(s) }
[ "func", "(", "c", "*", "Config", ")", "GetString", "(", "s", "string", ")", "string", "{", "return", "c", ".", "config", ".", "GetString", "(", "s", ")", "\n", "}" ]
// GetString returns a string from the inner config
[ "GetString", "returns", "a", "string", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L133-L135
train
topfreegames/pitaya
config/config.go
GetInt
func (c *Config) GetInt(s string) int { return c.config.GetInt(s) }
go
func (c *Config) GetInt(s string) int { return c.config.GetInt(s) }
[ "func", "(", "c", "*", "Config", ")", "GetInt", "(", "s", "string", ")", "int", "{", "return", "c", ".", "config", ".", "GetInt", "(", "s", ")", "\n", "}" ]
// GetInt returns an int from the inner config
[ "GetInt", "returns", "an", "int", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L138-L140
train
topfreegames/pitaya
config/config.go
GetBool
func (c *Config) GetBool(s string) bool { return c.config.GetBool(s) }
go
func (c *Config) GetBool(s string) bool { return c.config.GetBool(s) }
[ "func", "(", "c", "*", "Config", ")", "GetBool", "(", "s", "string", ")", "bool", "{", "return", "c", ".", "config", ".", "GetBool", "(", "s", ")", "\n", "}" ]
// GetBool returns an boolean from the inner config
[ "GetBool", "returns", "an", "boolean", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L143-L145
train
topfreegames/pitaya
config/config.go
GetStringSlice
func (c *Config) GetStringSlice(s string) []string { return c.config.GetStringSlice(s) }
go
func (c *Config) GetStringSlice(s string) []string { return c.config.GetStringSlice(s) }
[ "func", "(", "c", "*", "Config", ")", "GetStringSlice", "(", "s", "string", ")", "[", "]", "string", "{", "return", "c", ".", "config", ".", "GetStringSlice", "(", "s", ")", "\n", "}" ]
// GetStringSlice returns a string slice from the inner config
[ "GetStringSlice", "returns", "a", "string", "slice", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L148-L150
train
topfreegames/pitaya
config/config.go
GetStringMapString
func (c *Config) GetStringMapString(s string) map[string]string { return c.config.GetStringMapString(s) }
go
func (c *Config) GetStringMapString(s string) map[string]string { return c.config.GetStringMapString(s) }
[ "func", "(", "c", "*", "Config", ")", "GetStringMapString", "(", "s", "string", ")", "map", "[", "string", "]", "string", "{", "return", "c", ".", "config", ".", "GetStringMapString", "(", "s", ")", "\n", "}" ]
// GetStringMapString returns a string map string from the inner config
[ "GetStringMapString", "returns", "a", "string", "map", "string", "from", "the", "inner", "config" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L158-L160
train
topfreegames/pitaya
config/config.go
UnmarshalKey
func (c *Config) UnmarshalKey(s string, v interface{}) error { return c.config.UnmarshalKey(s, v) }
go
func (c *Config) UnmarshalKey(s string, v interface{}) error { return c.config.UnmarshalKey(s, v) }
[ "func", "(", "c", "*", "Config", ")", "UnmarshalKey", "(", "s", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "config", ".", "UnmarshalKey", "(", "s", ",", "v", ")", "\n", "}" ]
// UnmarshalKey unmarshals key into v
[ "UnmarshalKey", "unmarshals", "key", "into", "v" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/config/config.go#L163-L165
train
topfreegames/pitaya
groups/etcd_group_service.go
NewEtcdGroupService
func NewEtcdGroupService(conf *config.Config, clientOrNil *clientv3.Client) (*EtcdGroupService, error) { err := initClientInstance(conf, clientOrNil) if err != nil { return nil, err } return &EtcdGroupService{}, err }
go
func NewEtcdGroupService(conf *config.Config, clientOrNil *clientv3.Client) (*EtcdGroupService, error) { err := initClientInstance(conf, clientOrNil) if err != nil { return nil, err } return &EtcdGroupService{}, err }
[ "func", "NewEtcdGroupService", "(", "conf", "*", "config", ".", "Config", ",", "clientOrNil", "*", "clientv3", ".", "Client", ")", "(", "*", "EtcdGroupService", ",", "error", ")", "{", "err", ":=", "initClientInstance", "(", "conf", ",", "clientOrNil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "EtcdGroupService", "{", "}", ",", "err", "\n", "}" ]
// NewEtcdGroupService returns a new group instance
[ "NewEtcdGroupService", "returns", "a", "new", "group", "instance" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L28-L34
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupCreate
func (c *EtcdGroupService) GroupCreate(ctx context.Context, groupName string) error { return c.createGroup(ctx, groupName, 0) }
go
func (c *EtcdGroupService) GroupCreate(ctx context.Context, groupName string) error { return c.createGroup(ctx, groupName, 0) }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupCreate", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "return", "c", ".", "createGroup", "(", "ctx", ",", "groupName", ",", "0", ")", "\n", "}" ]
// GroupCreate creates a group struct inside ETCD, without TTL
[ "GroupCreate", "creates", "a", "group", "struct", "inside", "ETCD", "without", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L114-L116
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupCreateWithTTL
func (c *EtcdGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() lease, err := clientInstance.Grant(ctxT, int64(ttlTime.Seconds())) if err != nil { return err } return c.createGroup(ctx, groupName, lease.ID) }
go
func (c *EtcdGroupService) GroupCreateWithTTL(ctx context.Context, groupName string, ttlTime time.Duration) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() lease, err := clientInstance.Grant(ctxT, int64(ttlTime.Seconds())) if err != nil { return err } return c.createGroup(ctx, groupName, lease.ID) }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupCreateWithTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ",", "ttlTime", "time", ".", "Duration", ")", "error", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "lease", ",", "err", ":=", "clientInstance", ".", "Grant", "(", "ctxT", ",", "int64", "(", "ttlTime", ".", "Seconds", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "createGroup", "(", "ctx", ",", "groupName", ",", "lease", ".", "ID", ")", "\n", "}" ]
// GroupCreateWithTTL creates a group struct inside ETCD, with TTL, using leaseID
[ "GroupCreateWithTTL", "creates", "a", "group", "struct", "inside", "ETCD", "with", "TTL", "using", "leaseID" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L119-L127
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupContainsMember
func (c *EtcdGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpGet(memberKey(groupName, uid), clientv3.WithCountOnly())). Commit() if err != nil { return false, err } if !etcdRes.Succeeded { return false, constants.ErrGroupNotFound } return etcdRes.Responses[0].GetResponseRange().GetCount() > 0, nil }
go
func (c *EtcdGroupService) GroupContainsMember(ctx context.Context, groupName, uid string) (bool, error) { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpGet(memberKey(groupName, uid), clientv3.WithCountOnly())). Commit() if err != nil { return false, err } if !etcdRes.Succeeded { return false, constants.ErrGroupNotFound } return etcdRes.Responses[0].GetResponseRange().GetCount() > 0, nil }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupContainsMember", "(", "ctx", "context", ".", "Context", ",", "groupName", ",", "uid", "string", ")", "(", "bool", ",", "error", ")", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "etcdRes", ",", "err", ":=", "clientInstance", ".", "Txn", "(", "ctxT", ")", ".", "If", "(", "clientv3", ".", "Compare", "(", "clientv3", ".", "CreateRevision", "(", "groupKey", "(", "groupName", ")", ")", ",", "\"", "\"", ",", "0", ")", ")", ".", "Then", "(", "clientv3", ".", "OpGet", "(", "memberKey", "(", "groupName", ",", "uid", ")", ",", "clientv3", ".", "WithCountOnly", "(", ")", ")", ")", ".", "Commit", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "!", "etcdRes", ".", "Succeeded", "{", "return", "false", ",", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "return", "etcdRes", ".", "Responses", "[", "0", "]", ".", "GetResponseRange", "(", ")", ".", "GetCount", "(", ")", ">", "0", ",", "nil", "\n", "}" ]
// GroupContainsMember checks whether a UID is contained in current group or not
[ "GroupContainsMember", "checks", "whether", "a", "UID", "is", "contained", "in", "current", "group", "or", "not" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L155-L170
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupRemoveAll
func (c *EtcdGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpDelete(memberKey(groupName, ""), clientv3.WithPrefix())). Commit() if err != nil { return err } if !etcdRes.Succeeded { return constants.ErrGroupNotFound } return nil }
go
func (c *EtcdGroupService) GroupRemoveAll(ctx context.Context, groupName string) error { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() etcdRes, err := clientInstance.Txn(ctxT). If(clientv3.Compare(clientv3.CreateRevision(groupKey(groupName)), ">", 0)). Then(clientv3.OpDelete(memberKey(groupName, ""), clientv3.WithPrefix())). Commit() if err != nil { return err } if !etcdRes.Succeeded { return constants.ErrGroupNotFound } return nil }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupRemoveAll", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "etcdRes", ",", "err", ":=", "clientInstance", ".", "Txn", "(", "ctxT", ")", ".", "If", "(", "clientv3", ".", "Compare", "(", "clientv3", ".", "CreateRevision", "(", "groupKey", "(", "groupName", ")", ")", ",", "\"", "\"", ",", "0", ")", ")", ".", "Then", "(", "clientv3", ".", "OpDelete", "(", "memberKey", "(", "groupName", ",", "\"", "\"", ")", ",", "clientv3", ".", "WithPrefix", "(", ")", ")", ")", ".", "Commit", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "etcdRes", ".", "Succeeded", "{", "return", "constants", ".", "ErrGroupNotFound", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GroupRemoveAll clears all UIDs in the group
[ "GroupRemoveAll", "clears", "all", "UIDs", "in", "the", "group" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L224-L239
train
topfreegames/pitaya
groups/etcd_group_service.go
GroupRenewTTL
func (c *EtcdGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { kv, err := getGroupKV(ctx, groupName) if err != nil { return err } if kv.Lease != 0 { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() _, err = clientInstance.KeepAliveOnce(ctxT, clientv3.LeaseID(kv.Lease)) return err } return constants.ErrEtcdLeaseNotFound }
go
func (c *EtcdGroupService) GroupRenewTTL(ctx context.Context, groupName string) error { kv, err := getGroupKV(ctx, groupName) if err != nil { return err } if kv.Lease != 0 { ctxT, cancel := context.WithTimeout(ctx, transactionTimeout) defer cancel() _, err = clientInstance.KeepAliveOnce(ctxT, clientv3.LeaseID(kv.Lease)) return err } return constants.ErrEtcdLeaseNotFound }
[ "func", "(", "c", "*", "EtcdGroupService", ")", "GroupRenewTTL", "(", "ctx", "context", ".", "Context", ",", "groupName", "string", ")", "error", "{", "kv", ",", "err", ":=", "getGroupKV", "(", "ctx", ",", "groupName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "kv", ".", "Lease", "!=", "0", "{", "ctxT", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "transactionTimeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "_", ",", "err", "=", "clientInstance", ".", "KeepAliveOnce", "(", "ctxT", ",", "clientv3", ".", "LeaseID", "(", "kv", ".", "Lease", ")", ")", "\n", "return", "err", "\n", "}", "\n", "return", "constants", ".", "ErrEtcdLeaseNotFound", "\n", "}" ]
// GroupRenewTTL will renew ETCD lease TTL
[ "GroupRenewTTL", "will", "renew", "ETCD", "lease", "TTL" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/groups/etcd_group_service.go#L272-L284
train
topfreegames/pitaya
worker/report.go
Report
func Report(reporters []metrics.Reporter, period time.Duration) { for { time.Sleep(period) workerStats := workers.GetStats() for _, r := range reporters { reportJobsRetry(r, workerStats.Retries) reportQueueSizes(r, workerStats.Enqueued) reportJobsTotal(r, workerStats.Failed, workerStats.Processed) } } }
go
func Report(reporters []metrics.Reporter, period time.Duration) { for { time.Sleep(period) workerStats := workers.GetStats() for _, r := range reporters { reportJobsRetry(r, workerStats.Retries) reportQueueSizes(r, workerStats.Enqueued) reportJobsTotal(r, workerStats.Failed, workerStats.Processed) } } }
[ "func", "Report", "(", "reporters", "[", "]", "metrics", ".", "Reporter", ",", "period", "time", ".", "Duration", ")", "{", "for", "{", "time", ".", "Sleep", "(", "period", ")", "\n\n", "workerStats", ":=", "workers", ".", "GetStats", "(", ")", "\n", "for", "_", ",", "r", ":=", "range", "reporters", "{", "reportJobsRetry", "(", "r", ",", "workerStats", ".", "Retries", ")", "\n", "reportQueueSizes", "(", "r", ",", "workerStats", ".", "Enqueued", ")", "\n", "reportJobsTotal", "(", "r", ",", "workerStats", ".", "Failed", ",", "workerStats", ".", "Processed", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Report sends periodic of worker reports
[ "Report", "sends", "periodic", "of", "worker", "reports" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/worker/report.go#L14-L25
train
topfreegames/pitaya
util/util.go
Pcall
func Pcall(method reflect.Method, args []reflect.Value) (rets interface{}, err error) { defer func() { if rec := recover(); rec != nil { // Try to use logger from context here to help trace error cause log := getLoggerFromArgs(args) log.Errorf("panic - pitaya/dispatch: %s: %v", method.Name, rec) log.Debugf("%s", debug.Stack()) if s, ok := rec.(string); ok { err = errors.New(s) } else { err = fmt.Errorf("rpc call internal error - %s: %v", method.Name, rec) } } }() r := method.Func.Call(args) // r can have 0 length in case of notify handlers // otherwise it will have 2 outputs: an interface and an error if len(r) == 2 { if v := r[1].Interface(); v != nil { err = v.(error) } else if !r[0].IsNil() { rets = r[0].Interface() } else { err = constants.ErrReplyShouldBeNotNull } } return }
go
func Pcall(method reflect.Method, args []reflect.Value) (rets interface{}, err error) { defer func() { if rec := recover(); rec != nil { // Try to use logger from context here to help trace error cause log := getLoggerFromArgs(args) log.Errorf("panic - pitaya/dispatch: %s: %v", method.Name, rec) log.Debugf("%s", debug.Stack()) if s, ok := rec.(string); ok { err = errors.New(s) } else { err = fmt.Errorf("rpc call internal error - %s: %v", method.Name, rec) } } }() r := method.Func.Call(args) // r can have 0 length in case of notify handlers // otherwise it will have 2 outputs: an interface and an error if len(r) == 2 { if v := r[1].Interface(); v != nil { err = v.(error) } else if !r[0].IsNil() { rets = r[0].Interface() } else { err = constants.ErrReplyShouldBeNotNull } } return }
[ "func", "Pcall", "(", "method", "reflect", ".", "Method", ",", "args", "[", "]", "reflect", ".", "Value", ")", "(", "rets", "interface", "{", "}", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "rec", ":=", "recover", "(", ")", ";", "rec", "!=", "nil", "{", "// Try to use logger from context here to help trace error cause", "log", ":=", "getLoggerFromArgs", "(", "args", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "method", ".", "Name", ",", "rec", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "debug", ".", "Stack", "(", ")", ")", "\n", "if", "s", ",", "ok", ":=", "rec", ".", "(", "string", ")", ";", "ok", "{", "err", "=", "errors", ".", "New", "(", "s", ")", "\n", "}", "else", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "method", ".", "Name", ",", "rec", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "r", ":=", "method", ".", "Func", ".", "Call", "(", "args", ")", "\n", "// r can have 0 length in case of notify handlers", "// otherwise it will have 2 outputs: an interface and an error", "if", "len", "(", "r", ")", "==", "2", "{", "if", "v", ":=", "r", "[", "1", "]", ".", "Interface", "(", ")", ";", "v", "!=", "nil", "{", "err", "=", "v", ".", "(", "error", ")", "\n", "}", "else", "if", "!", "r", "[", "0", "]", ".", "IsNil", "(", ")", "{", "rets", "=", "r", "[", "0", "]", ".", "Interface", "(", ")", "\n", "}", "else", "{", "err", "=", "constants", ".", "ErrReplyShouldBeNotNull", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Pcall calls a method that returns an interface and an error and recovers in case of panic
[ "Pcall", "calls", "a", "method", "that", "returns", "an", "interface", "and", "an", "error", "and", "recovers", "in", "case", "of", "panic" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L61-L89
train
topfreegames/pitaya
util/util.go
SliceContainsString
func SliceContainsString(slice []string, str string) bool { for _, value := range slice { if value == str { return true } } return false }
go
func SliceContainsString(slice []string, str string) bool { for _, value := range slice { if value == str { return true } } return false }
[ "func", "SliceContainsString", "(", "slice", "[", "]", "string", ",", "str", "string", ")", "bool", "{", "for", "_", ",", "value", ":=", "range", "slice", "{", "if", "value", "==", "str", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// SliceContainsString returns true if a slice contains the string
[ "SliceContainsString", "returns", "true", "if", "a", "slice", "contains", "the", "string" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L92-L99
train
topfreegames/pitaya
util/util.go
SerializeOrRaw
func SerializeOrRaw(serializer serialize.Serializer, v interface{}) ([]byte, error) { if data, ok := v.([]byte); ok { return data, nil } data, err := serializer.Marshal(v) if err != nil { return nil, err } return data, nil }
go
func SerializeOrRaw(serializer serialize.Serializer, v interface{}) ([]byte, error) { if data, ok := v.([]byte); ok { return data, nil } data, err := serializer.Marshal(v) if err != nil { return nil, err } return data, nil }
[ "func", "SerializeOrRaw", "(", "serializer", "serialize", ".", "Serializer", ",", "v", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "data", ",", "ok", ":=", "v", ".", "(", "[", "]", "byte", ")", ";", "ok", "{", "return", "data", ",", "nil", "\n", "}", "\n", "data", ",", "err", ":=", "serializer", ".", "Marshal", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "data", ",", "nil", "\n", "}" ]
// SerializeOrRaw serializes the interface if its not an array of bytes already
[ "SerializeOrRaw", "serializes", "the", "interface", "if", "its", "not", "an", "array", "of", "bytes", "already" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L102-L111
train
topfreegames/pitaya
util/util.go
GetErrorPayload
func GetErrorPayload(serializer serialize.Serializer, err error) ([]byte, error) { code := e.ErrUnknownCode msg := err.Error() metadata := map[string]string{} if val, ok := err.(*e.Error); ok { code = val.Code metadata = val.Metadata } errPayload := &protos.Error{ Code: code, Msg: msg, } if len(metadata) > 0 { errPayload.Metadata = metadata } return SerializeOrRaw(serializer, errPayload) }
go
func GetErrorPayload(serializer serialize.Serializer, err error) ([]byte, error) { code := e.ErrUnknownCode msg := err.Error() metadata := map[string]string{} if val, ok := err.(*e.Error); ok { code = val.Code metadata = val.Metadata } errPayload := &protos.Error{ Code: code, Msg: msg, } if len(metadata) > 0 { errPayload.Metadata = metadata } return SerializeOrRaw(serializer, errPayload) }
[ "func", "GetErrorPayload", "(", "serializer", "serialize", ".", "Serializer", ",", "err", "error", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "code", ":=", "e", ".", "ErrUnknownCode", "\n", "msg", ":=", "err", ".", "Error", "(", ")", "\n", "metadata", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "if", "val", ",", "ok", ":=", "err", ".", "(", "*", "e", ".", "Error", ")", ";", "ok", "{", "code", "=", "val", ".", "Code", "\n", "metadata", "=", "val", ".", "Metadata", "\n", "}", "\n", "errPayload", ":=", "&", "protos", ".", "Error", "{", "Code", ":", "code", ",", "Msg", ":", "msg", ",", "}", "\n", "if", "len", "(", "metadata", ")", ">", "0", "{", "errPayload", ".", "Metadata", "=", "metadata", "\n", "}", "\n", "return", "SerializeOrRaw", "(", "serializer", ",", "errPayload", ")", "\n", "}" ]
// GetErrorPayload creates and serializes an error payload
[ "GetErrorPayload", "creates", "and", "serializes", "an", "error", "payload" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L120-L136
train
topfreegames/pitaya
util/util.go
ConvertProtoToMessageType
func ConvertProtoToMessageType(protoMsgType protos.MsgType) message.Type { var msgType message.Type switch protoMsgType { case protos.MsgType_MsgRequest: msgType = message.Request case protos.MsgType_MsgNotify: msgType = message.Notify } return msgType }
go
func ConvertProtoToMessageType(protoMsgType protos.MsgType) message.Type { var msgType message.Type switch protoMsgType { case protos.MsgType_MsgRequest: msgType = message.Request case protos.MsgType_MsgNotify: msgType = message.Notify } return msgType }
[ "func", "ConvertProtoToMessageType", "(", "protoMsgType", "protos", ".", "MsgType", ")", "message", ".", "Type", "{", "var", "msgType", "message", ".", "Type", "\n", "switch", "protoMsgType", "{", "case", "protos", ".", "MsgType_MsgRequest", ":", "msgType", "=", "message", ".", "Request", "\n", "case", "protos", ".", "MsgType_MsgNotify", ":", "msgType", "=", "message", ".", "Notify", "\n", "}", "\n", "return", "msgType", "\n", "}" ]
// ConvertProtoToMessageType converts a protos.MsgType to a message.Type
[ "ConvertProtoToMessageType", "converts", "a", "protos", ".", "MsgType", "to", "a", "message", ".", "Type" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L139-L148
train
topfreegames/pitaya
util/util.go
CtxWithDefaultLogger
func CtxWithDefaultLogger(ctx context.Context, route, userID string) context.Context { var defaultLogger logger.Logger logrusLogger, ok := logger.Log.(logrus.FieldLogger) if ok { requestID := pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey) if rID, ok := requestID.(string); ok { if rID == "" { requestID = uuid.New() } } else { requestID = uuid.New() } defaultLogger = logrusLogger.WithFields( logrus.Fields{ "route": route, "requestId": requestID, "userId": userID, }) } else { defaultLogger = logger.Log } return context.WithValue(ctx, constants.LoggerCtxKey, defaultLogger) }
go
func CtxWithDefaultLogger(ctx context.Context, route, userID string) context.Context { var defaultLogger logger.Logger logrusLogger, ok := logger.Log.(logrus.FieldLogger) if ok { requestID := pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey) if rID, ok := requestID.(string); ok { if rID == "" { requestID = uuid.New() } } else { requestID = uuid.New() } defaultLogger = logrusLogger.WithFields( logrus.Fields{ "route": route, "requestId": requestID, "userId": userID, }) } else { defaultLogger = logger.Log } return context.WithValue(ctx, constants.LoggerCtxKey, defaultLogger) }
[ "func", "CtxWithDefaultLogger", "(", "ctx", "context", ".", "Context", ",", "route", ",", "userID", "string", ")", "context", ".", "Context", "{", "var", "defaultLogger", "logger", ".", "Logger", "\n", "logrusLogger", ",", "ok", ":=", "logger", ".", "Log", ".", "(", "logrus", ".", "FieldLogger", ")", "\n", "if", "ok", "{", "requestID", ":=", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RequestIDKey", ")", "\n", "if", "rID", ",", "ok", ":=", "requestID", ".", "(", "string", ")", ";", "ok", "{", "if", "rID", "==", "\"", "\"", "{", "requestID", "=", "uuid", ".", "New", "(", ")", "\n", "}", "\n", "}", "else", "{", "requestID", "=", "uuid", ".", "New", "(", ")", "\n", "}", "\n", "defaultLogger", "=", "logrusLogger", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "route", ",", "\"", "\"", ":", "requestID", ",", "\"", "\"", ":", "userID", ",", "}", ")", "\n", "}", "else", "{", "defaultLogger", "=", "logger", ".", "Log", "\n", "}", "\n\n", "return", "context", ".", "WithValue", "(", "ctx", ",", "constants", ".", "LoggerCtxKey", ",", "defaultLogger", ")", "\n", "}" ]
// CtxWithDefaultLogger inserts a default logger on ctx to be used on handlers and remotes. // If using logrus, userId, route and requestId will be added as fields. // Otherwise the pitaya logger will be used as it is.
[ "CtxWithDefaultLogger", "inserts", "a", "default", "logger", "on", "ctx", "to", "be", "used", "on", "handlers", "and", "remotes", ".", "If", "using", "logrus", "userId", "route", "and", "requestId", "will", "be", "added", "as", "fields", ".", "Otherwise", "the", "pitaya", "logger", "will", "be", "used", "as", "it", "is", "." ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L153-L176
train
topfreegames/pitaya
util/util.go
GetContextFromRequest
func GetContextFromRequest(req *protos.Request, serverID string) (context.Context, error) { ctx, err := pcontext.Decode(req.GetMetadata()) if err != nil { return nil, err } if ctx == nil { return nil, constants.ErrNoContextFound } tags := opentracing.Tags{ "local.id": serverID, "span.kind": "server", "peer.id": pcontext.GetFromPropagateCtx(ctx, constants.PeerIDKey), "peer.service": pcontext.GetFromPropagateCtx(ctx, constants.PeerServiceKey), "request.id": pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey), } parent, err := tracing.ExtractSpan(ctx) if err != nil { logger.Log.Warnf("failed to retrieve parent span: %s", err.Error()) } ctx = tracing.StartSpan(ctx, req.GetMsg().GetRoute(), tags, parent) ctx = CtxWithDefaultLogger(ctx, req.GetMsg().GetRoute(), "") return ctx, nil }
go
func GetContextFromRequest(req *protos.Request, serverID string) (context.Context, error) { ctx, err := pcontext.Decode(req.GetMetadata()) if err != nil { return nil, err } if ctx == nil { return nil, constants.ErrNoContextFound } tags := opentracing.Tags{ "local.id": serverID, "span.kind": "server", "peer.id": pcontext.GetFromPropagateCtx(ctx, constants.PeerIDKey), "peer.service": pcontext.GetFromPropagateCtx(ctx, constants.PeerServiceKey), "request.id": pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey), } parent, err := tracing.ExtractSpan(ctx) if err != nil { logger.Log.Warnf("failed to retrieve parent span: %s", err.Error()) } ctx = tracing.StartSpan(ctx, req.GetMsg().GetRoute(), tags, parent) ctx = CtxWithDefaultLogger(ctx, req.GetMsg().GetRoute(), "") return ctx, nil }
[ "func", "GetContextFromRequest", "(", "req", "*", "protos", ".", "Request", ",", "serverID", "string", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "ctx", ",", "err", ":=", "pcontext", ".", "Decode", "(", "req", ".", "GetMetadata", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "ctx", "==", "nil", "{", "return", "nil", ",", "constants", ".", "ErrNoContextFound", "\n", "}", "\n", "tags", ":=", "opentracing", ".", "Tags", "{", "\"", "\"", ":", "serverID", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "PeerIDKey", ")", ",", "\"", "\"", ":", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "PeerServiceKey", ")", ",", "\"", "\"", ":", "pcontext", ".", "GetFromPropagateCtx", "(", "ctx", ",", "constants", ".", "RequestIDKey", ")", ",", "}", "\n", "parent", ",", "err", ":=", "tracing", ".", "ExtractSpan", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Log", ".", "Warnf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "ctx", "=", "tracing", ".", "StartSpan", "(", "ctx", ",", "req", ".", "GetMsg", "(", ")", ".", "GetRoute", "(", ")", ",", "tags", ",", "parent", ")", "\n", "ctx", "=", "CtxWithDefaultLogger", "(", "ctx", ",", "req", ".", "GetMsg", "(", ")", ".", "GetRoute", "(", ")", ",", "\"", "\"", ")", "\n", "return", "ctx", ",", "nil", "\n", "}" ]
// GetContextFromRequest gets the context from a request
[ "GetContextFromRequest", "gets", "the", "context", "from", "a", "request" ]
b92161d7a48c87a7759ac9cabcc23e7d56f9eebd
https://github.com/topfreegames/pitaya/blob/b92161d7a48c87a7759ac9cabcc23e7d56f9eebd/util/util.go#L179-L201
train
chrislusf/gleam
sql/sessionctx/variable/session.go
SetStatusFlag
func (s *SessionVars) SetStatusFlag(flag uint16, on bool) { if on { s.Status |= flag return } s.Status &= (^flag) }
go
func (s *SessionVars) SetStatusFlag(flag uint16, on bool) { if on { s.Status |= flag return } s.Status &= (^flag) }
[ "func", "(", "s", "*", "SessionVars", ")", "SetStatusFlag", "(", "flag", "uint16", ",", "on", "bool", ")", "{", "if", "on", "{", "s", ".", "Status", "|=", "flag", "\n", "return", "\n", "}", "\n", "s", ".", "Status", "&=", "(", "^", "flag", ")", "\n", "}" ]
// SetStatusFlag sets the session server status variable. // If on is ture sets the flag in session status, // otherwise removes the flag.
[ "SetStatusFlag", "sets", "the", "session", "server", "status", "variable", ".", "If", "on", "is", "ture", "sets", "the", "flag", "in", "session", "status", "otherwise", "removes", "the", "flag", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/session.go#L160-L166
train
chrislusf/gleam
sql/sessionctx/variable/session.go
GetWarnings
func (sc *StatementContext) GetWarnings() []error { sc.mu.Lock() warns := make([]error, len(sc.mu.warnings)) copy(warns, sc.mu.warnings) sc.mu.Unlock() return warns }
go
func (sc *StatementContext) GetWarnings() []error { sc.mu.Lock() warns := make([]error, len(sc.mu.warnings)) copy(warns, sc.mu.warnings) sc.mu.Unlock() return warns }
[ "func", "(", "sc", "*", "StatementContext", ")", "GetWarnings", "(", ")", "[", "]", "error", "{", "sc", ".", "mu", ".", "Lock", "(", ")", "\n", "warns", ":=", "make", "(", "[", "]", "error", ",", "len", "(", "sc", ".", "mu", ".", "warnings", ")", ")", "\n", "copy", "(", "warns", ",", "sc", ".", "mu", ".", "warnings", ")", "\n", "sc", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "warns", "\n", "}" ]
// GetWarnings gets warnings.
[ "GetWarnings", "gets", "warnings", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/session.go#L240-L246
train
chrislusf/gleam
sql/sessionctx/variable/session.go
AppendWarning
func (sc *StatementContext) AppendWarning(warn error) { sc.mu.Lock() sc.mu.warnings = append(sc.mu.warnings, warn) sc.mu.Unlock() }
go
func (sc *StatementContext) AppendWarning(warn error) { sc.mu.Lock() sc.mu.warnings = append(sc.mu.warnings, warn) sc.mu.Unlock() }
[ "func", "(", "sc", "*", "StatementContext", ")", "AppendWarning", "(", "warn", "error", ")", "{", "sc", ".", "mu", ".", "Lock", "(", ")", "\n", "sc", ".", "mu", ".", "warnings", "=", "append", "(", "sc", ".", "mu", ".", "warnings", ",", "warn", ")", "\n", "sc", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// AppendWarning appends a warning.
[ "AppendWarning", "appends", "a", "warning", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/session.go#L256-L260
train
chrislusf/gleam
sql/model/model.go
Clone
func (t *TableInfo) Clone() *TableInfo { nt := *t nt.Columns = make([]*ColumnInfo, len(t.Columns)) nt.Indices = make([]*IndexInfo, len(t.Indices)) for i := range t.Columns { nt.Columns[i] = t.Columns[i].Clone() } for i := range t.Indices { nt.Indices[i] = t.Indices[i].Clone() } return &nt }
go
func (t *TableInfo) Clone() *TableInfo { nt := *t nt.Columns = make([]*ColumnInfo, len(t.Columns)) nt.Indices = make([]*IndexInfo, len(t.Indices)) for i := range t.Columns { nt.Columns[i] = t.Columns[i].Clone() } for i := range t.Indices { nt.Indices[i] = t.Indices[i].Clone() } return &nt }
[ "func", "(", "t", "*", "TableInfo", ")", "Clone", "(", ")", "*", "TableInfo", "{", "nt", ":=", "*", "t", "\n", "nt", ".", "Columns", "=", "make", "(", "[", "]", "*", "ColumnInfo", ",", "len", "(", "t", ".", "Columns", ")", ")", "\n", "nt", ".", "Indices", "=", "make", "(", "[", "]", "*", "IndexInfo", ",", "len", "(", "t", ".", "Indices", ")", ")", "\n\n", "for", "i", ":=", "range", "t", ".", "Columns", "{", "nt", ".", "Columns", "[", "i", "]", "=", "t", ".", "Columns", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n\n", "for", "i", ":=", "range", "t", ".", "Indices", "{", "nt", ".", "Indices", "[", "i", "]", "=", "t", ".", "Indices", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n\n", "return", "&", "nt", "\n", "}" ]
// Clone clones TableInfo.
[ "Clone", "clones", "TableInfo", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L46-L60
train
chrislusf/gleam
sql/model/model.go
Clone
func (index *IndexInfo) Clone() *IndexInfo { ni := *index ni.Columns = make([]*IndexColumn, len(index.Columns)) for i := range index.Columns { ni.Columns[i] = index.Columns[i].Clone() } return &ni }
go
func (index *IndexInfo) Clone() *IndexInfo { ni := *index ni.Columns = make([]*IndexColumn, len(index.Columns)) for i := range index.Columns { ni.Columns[i] = index.Columns[i].Clone() } return &ni }
[ "func", "(", "index", "*", "IndexInfo", ")", "Clone", "(", ")", "*", "IndexInfo", "{", "ni", ":=", "*", "index", "\n", "ni", ".", "Columns", "=", "make", "(", "[", "]", "*", "IndexColumn", ",", "len", "(", "index", ".", "Columns", ")", ")", "\n", "for", "i", ":=", "range", "index", ".", "Columns", "{", "ni", ".", "Columns", "[", "i", "]", "=", "index", ".", "Columns", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n", "return", "&", "ni", "\n", "}" ]
// Clone clones IndexInfo.
[ "Clone", "clones", "IndexInfo", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L107-L114
train
chrislusf/gleam
sql/model/model.go
Clone
func (db *DBInfo) Clone() *DBInfo { newInfo := *db newInfo.Tables = make([]*TableInfo, len(db.Tables)) for i := range db.Tables { newInfo.Tables[i] = db.Tables[i].Clone() } return &newInfo }
go
func (db *DBInfo) Clone() *DBInfo { newInfo := *db newInfo.Tables = make([]*TableInfo, len(db.Tables)) for i := range db.Tables { newInfo.Tables[i] = db.Tables[i].Clone() } return &newInfo }
[ "func", "(", "db", "*", "DBInfo", ")", "Clone", "(", ")", "*", "DBInfo", "{", "newInfo", ":=", "*", "db", "\n", "newInfo", ".", "Tables", "=", "make", "(", "[", "]", "*", "TableInfo", ",", "len", "(", "db", ".", "Tables", ")", ")", "\n", "for", "i", ":=", "range", "db", ".", "Tables", "{", "newInfo", ".", "Tables", "[", "i", "]", "=", "db", ".", "Tables", "[", "i", "]", ".", "Clone", "(", ")", "\n", "}", "\n", "return", "&", "newInfo", "\n", "}" ]
// Clone clones DBInfo.
[ "Clone", "clones", "DBInfo", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L123-L130
train
chrislusf/gleam
sql/model/model.go
NewCIStr
func NewCIStr(s string) (cs CIStr) { cs.O = s cs.L = strings.ToLower(s) return }
go
func NewCIStr(s string) (cs CIStr) { cs.O = s cs.L = strings.ToLower(s) return }
[ "func", "NewCIStr", "(", "s", "string", ")", "(", "cs", "CIStr", ")", "{", "cs", ".", "O", "=", "s", "\n", "cs", ".", "L", "=", "strings", ".", "ToLower", "(", "s", ")", "\n", "return", "\n", "}" ]
// NewCIStr creates a new CIStr.
[ "NewCIStr", "creates", "a", "new", "CIStr", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/model/model.go#L144-L148
train
chrislusf/gleam
flow/dataset_output.go
Output
func (d *Dataset) Output(f func(io.Reader) error) *Dataset { step := d.Flow.AddAllToOneStep(d, nil) step.IsOnDriverSide = true step.Name = "Output" step.Function = func(readers []io.Reader, writers []io.Writer, stat *pb.InstructionStat) error { errChan := make(chan error, len(readers)) for i, reader := range readers { go func(i int, reader io.Reader) { errChan <- f(reader) }(i, reader) } for range readers { err := <-errChan if err != nil { fmt.Fprintf(os.Stderr, "Failed to process output: %v\n", err) return err } } return nil } return d }
go
func (d *Dataset) Output(f func(io.Reader) error) *Dataset { step := d.Flow.AddAllToOneStep(d, nil) step.IsOnDriverSide = true step.Name = "Output" step.Function = func(readers []io.Reader, writers []io.Writer, stat *pb.InstructionStat) error { errChan := make(chan error, len(readers)) for i, reader := range readers { go func(i int, reader io.Reader) { errChan <- f(reader) }(i, reader) } for range readers { err := <-errChan if err != nil { fmt.Fprintf(os.Stderr, "Failed to process output: %v\n", err) return err } } return nil } return d }
[ "func", "(", "d", "*", "Dataset", ")", "Output", "(", "f", "func", "(", "io", ".", "Reader", ")", "error", ")", "*", "Dataset", "{", "step", ":=", "d", ".", "Flow", ".", "AddAllToOneStep", "(", "d", ",", "nil", ")", "\n", "step", ".", "IsOnDriverSide", "=", "true", "\n", "step", ".", "Name", "=", "\"", "\"", "\n", "step", ".", "Function", "=", "func", "(", "readers", "[", "]", "io", ".", "Reader", ",", "writers", "[", "]", "io", ".", "Writer", ",", "stat", "*", "pb", ".", "InstructionStat", ")", "error", "{", "errChan", ":=", "make", "(", "chan", "error", ",", "len", "(", "readers", ")", ")", "\n", "for", "i", ",", "reader", ":=", "range", "readers", "{", "go", "func", "(", "i", "int", ",", "reader", "io", ".", "Reader", ")", "{", "errChan", "<-", "f", "(", "reader", ")", "\n", "}", "(", "i", ",", "reader", ")", "\n", "}", "\n", "for", "range", "readers", "{", "err", ":=", "<-", "errChan", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "d", "\n", "}" ]
// Output concurrently collects outputs from previous step to the driver.
[ "Output", "concurrently", "collects", "outputs", "from", "previous", "step", "to", "the", "driver", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L17-L38
train
chrislusf/gleam
flow/dataset_output.go
Fprintf
func (d *Dataset) Fprintf(writer io.Writer, format string) *Dataset { fn := func(r io.Reader) error { w := bufio.NewWriter(writer) defer w.Flush() return util.Fprintf(w, r, format) } return d.Output(fn) }
go
func (d *Dataset) Fprintf(writer io.Writer, format string) *Dataset { fn := func(r io.Reader) error { w := bufio.NewWriter(writer) defer w.Flush() return util.Fprintf(w, r, format) } return d.Output(fn) }
[ "func", "(", "d", "*", "Dataset", ")", "Fprintf", "(", "writer", "io", ".", "Writer", ",", "format", "string", ")", "*", "Dataset", "{", "fn", ":=", "func", "(", "r", "io", ".", "Reader", ")", "error", "{", "w", ":=", "bufio", ".", "NewWriter", "(", "writer", ")", "\n", "defer", "w", ".", "Flush", "(", ")", "\n", "return", "util", ".", "Fprintf", "(", "w", ",", "r", ",", "format", ")", "\n", "}", "\n", "return", "d", ".", "Output", "(", "fn", ")", "\n", "}" ]
// Fprintf formats using the format for each row and writes to writer.
[ "Fprintf", "formats", "using", "the", "format", "for", "each", "row", "and", "writes", "to", "writer", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L41-L48
train
chrislusf/gleam
flow/dataset_output.go
Fprintlnf
func (d *Dataset) Fprintlnf(writer io.Writer, format string) *Dataset { return d.Fprintf(writer, format+"\n") }
go
func (d *Dataset) Fprintlnf(writer io.Writer, format string) *Dataset { return d.Fprintf(writer, format+"\n") }
[ "func", "(", "d", "*", "Dataset", ")", "Fprintlnf", "(", "writer", "io", ".", "Writer", ",", "format", "string", ")", "*", "Dataset", "{", "return", "d", ".", "Fprintf", "(", "writer", ",", "format", "+", "\"", "\\n", "\"", ")", "\n", "}" ]
// Fprintlnf add "\n" at the end of each format
[ "Fprintlnf", "add", "\\", "n", "at", "the", "end", "of", "each", "format" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L51-L53
train
chrislusf/gleam
flow/dataset_output.go
Printf
func (d *Dataset) Printf(format string) *Dataset { return d.Fprintf(os.Stdout, format) }
go
func (d *Dataset) Printf(format string) *Dataset { return d.Fprintf(os.Stdout, format) }
[ "func", "(", "d", "*", "Dataset", ")", "Printf", "(", "format", "string", ")", "*", "Dataset", "{", "return", "d", ".", "Fprintf", "(", "os", ".", "Stdout", ",", "format", ")", "\n", "}" ]
// Printf prints to os.Stdout in the specified format
[ "Printf", "prints", "to", "os", ".", "Stdout", "in", "the", "specified", "format" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L56-L58
train
chrislusf/gleam
flow/dataset_output.go
Printlnf
func (d *Dataset) Printlnf(format string) *Dataset { return d.Fprintf(os.Stdout, format+"\n") }
go
func (d *Dataset) Printlnf(format string) *Dataset { return d.Fprintf(os.Stdout, format+"\n") }
[ "func", "(", "d", "*", "Dataset", ")", "Printlnf", "(", "format", "string", ")", "*", "Dataset", "{", "return", "d", ".", "Fprintf", "(", "os", ".", "Stdout", ",", "format", "+", "\"", "\\n", "\"", ")", "\n", "}" ]
// Printlnf prints to os.Stdout in the specified format, // adding an "\n" at the end of each format
[ "Printlnf", "prints", "to", "os", ".", "Stdout", "in", "the", "specified", "format", "adding", "an", "\\", "n", "at", "the", "end", "of", "each", "format" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L62-L64
train
chrislusf/gleam
flow/dataset_output.go
SaveFirstRowTo
func (d *Dataset) SaveFirstRowTo(decodedObjects ...interface{}) *Dataset { fn := func(reader io.Reader) error { return util.TakeMessage(reader, 1, func(encodedBytes []byte) error { row, err := util.DecodeRow(encodedBytes) if err != nil { fmt.Fprintf(os.Stderr, "Failed to decode byte: %v\n", err) return err } var counter int for _, v := range row.K { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } for _, v := range row.V { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } return nil }) } return d.Output(fn) }
go
func (d *Dataset) SaveFirstRowTo(decodedObjects ...interface{}) *Dataset { fn := func(reader io.Reader) error { return util.TakeMessage(reader, 1, func(encodedBytes []byte) error { row, err := util.DecodeRow(encodedBytes) if err != nil { fmt.Fprintf(os.Stderr, "Failed to decode byte: %v\n", err) return err } var counter int for _, v := range row.K { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } for _, v := range row.V { if err := setValueTo(v, decodedObjects[counter]); err != nil { return err } counter++ } return nil }) } return d.Output(fn) }
[ "func", "(", "d", "*", "Dataset", ")", "SaveFirstRowTo", "(", "decodedObjects", "...", "interface", "{", "}", ")", "*", "Dataset", "{", "fn", ":=", "func", "(", "reader", "io", ".", "Reader", ")", "error", "{", "return", "util", ".", "TakeMessage", "(", "reader", ",", "1", ",", "func", "(", "encodedBytes", "[", "]", "byte", ")", "error", "{", "row", ",", "err", ":=", "util", ".", "DecodeRow", "(", "encodedBytes", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "var", "counter", "int", "\n", "for", "_", ",", "v", ":=", "range", "row", ".", "K", "{", "if", "err", ":=", "setValueTo", "(", "v", ",", "decodedObjects", "[", "counter", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "counter", "++", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "row", ".", "V", "{", "if", "err", ":=", "setValueTo", "(", "v", ",", "decodedObjects", "[", "counter", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "counter", "++", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}", "\n", "return", "d", ".", "Output", "(", "fn", ")", "\n", "}" ]
// SaveFirstRowTo saves the first row's values into the operands.
[ "SaveFirstRowTo", "saves", "the", "first", "row", "s", "values", "into", "the", "operands", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_output.go#L67-L93
train
chrislusf/gleam
sql/session.go
runStmt
func runStmt(ctx context.Context, s ast.Statement) (ast.RecordSet, error) { var err error var rs ast.RecordSet rs, err = s.Exec(ctx) return rs, errors.Trace(err) }
go
func runStmt(ctx context.Context, s ast.Statement) (ast.RecordSet, error) { var err error var rs ast.RecordSet rs, err = s.Exec(ctx) return rs, errors.Trace(err) }
[ "func", "runStmt", "(", "ctx", "context", ".", "Context", ",", "s", "ast", ".", "Statement", ")", "(", "ast", ".", "RecordSet", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "rs", "ast", ".", "RecordSet", "\n", "rs", ",", "err", "=", "s", ".", "Exec", "(", "ctx", ")", "\n", "return", "rs", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}" ]
// runStmt executes the ast.Statement and commit or rollback the current transaction.
[ "runStmt", "executes", "the", "ast", ".", "Statement", "and", "commit", "or", "rollback", "the", "current", "transaction", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/session.go#L209-L214
train
chrislusf/gleam
flow/dataset_cogroup.go
CoGroupPartitionedSorted
func (this *Dataset) CoGroupPartitionedSorted(name string, that *Dataset, indexes []int) (ret *Dataset) { ret = this.Flow.NewNextDataset(len(this.Shards)) ret.IsPartitionedBy = indexes inputs := []*Dataset{this, that} step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret) step.SetInstruction(name, instruction.NewCoGroupPartitionedSorted(indexes)) return ret }
go
func (this *Dataset) CoGroupPartitionedSorted(name string, that *Dataset, indexes []int) (ret *Dataset) { ret = this.Flow.NewNextDataset(len(this.Shards)) ret.IsPartitionedBy = indexes inputs := []*Dataset{this, that} step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret) step.SetInstruction(name, instruction.NewCoGroupPartitionedSorted(indexes)) return ret }
[ "func", "(", "this", "*", "Dataset", ")", "CoGroupPartitionedSorted", "(", "name", "string", ",", "that", "*", "Dataset", ",", "indexes", "[", "]", "int", ")", "(", "ret", "*", "Dataset", ")", "{", "ret", "=", "this", ".", "Flow", ".", "NewNextDataset", "(", "len", "(", "this", ".", "Shards", ")", ")", "\n", "ret", ".", "IsPartitionedBy", "=", "indexes", "\n\n", "inputs", ":=", "[", "]", "*", "Dataset", "{", "this", ",", "that", "}", "\n", "step", ":=", "this", ".", "Flow", ".", "MergeDatasets1ShardTo1Step", "(", "inputs", ",", "ret", ")", "\n", "step", ".", "SetInstruction", "(", "name", ",", "instruction", ".", "NewCoGroupPartitionedSorted", "(", "indexes", ")", ")", "\n", "return", "ret", "\n", "}" ]
// CoGroupPartitionedSorted joins 2 datasets that are sharded // by the same key and already locally sorted within each shard.
[ "CoGroupPartitionedSorted", "joins", "2", "datasets", "that", "are", "sharded", "by", "the", "same", "key", "and", "already", "locally", "sorted", "within", "each", "shard", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_cogroup.go#L24-L32
train
chrislusf/gleam
sql/expression/aggregation.go
NewAggFunction
func NewAggFunction(funcType string, funcArgs []Expression, distinct bool) AggregationFunction { switch tp := strings.ToLower(funcType); tp { case ast.AggFuncSum: return &sumFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncCount: return &countFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncAvg: return &avgFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncGroupConcat: return &concatFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncMax: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: true} case ast.AggFuncMin: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: false} case ast.AggFuncFirstRow: return &firstRowFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} } return nil }
go
func NewAggFunction(funcType string, funcArgs []Expression, distinct bool) AggregationFunction { switch tp := strings.ToLower(funcType); tp { case ast.AggFuncSum: return &sumFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncCount: return &countFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncAvg: return &avgFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncGroupConcat: return &concatFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} case ast.AggFuncMax: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: true} case ast.AggFuncMin: return &maxMinFunction{aggFunction: newAggFunc(tp, funcArgs, distinct), isMax: false} case ast.AggFuncFirstRow: return &firstRowFunction{aggFunction: newAggFunc(tp, funcArgs, distinct)} } return nil }
[ "func", "NewAggFunction", "(", "funcType", "string", ",", "funcArgs", "[", "]", "Expression", ",", "distinct", "bool", ")", "AggregationFunction", "{", "switch", "tp", ":=", "strings", ".", "ToLower", "(", "funcType", ")", ";", "tp", "{", "case", "ast", ".", "AggFuncSum", ":", "return", "&", "sumFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncCount", ":", "return", "&", "countFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncAvg", ":", "return", "&", "avgFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncGroupConcat", ":", "return", "&", "concatFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "case", "ast", ".", "AggFuncMax", ":", "return", "&", "maxMinFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", ",", "isMax", ":", "true", "}", "\n", "case", "ast", ".", "AggFuncMin", ":", "return", "&", "maxMinFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", ",", "isMax", ":", "false", "}", "\n", "case", "ast", ".", "AggFuncFirstRow", ":", "return", "&", "firstRowFunction", "{", "aggFunction", ":", "newAggFunc", "(", "tp", ",", "funcArgs", ",", "distinct", ")", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// NewAggFunction creates a new AggregationFunction.
[ "NewAggFunction", "creates", "a", "new", "AggregationFunction", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/aggregation.go#L98-L116
train
chrislusf/gleam
sql/expression/aggregation.go
Equal
func (af *aggFunction) Equal(b AggregationFunction, ctx context.Context) bool { if af.GetName() != b.GetName() { return false } if af.Distinct != b.IsDistinct() { return false } if len(af.GetArgs()) == len(b.GetArgs()) { for i, argA := range af.GetArgs() { if !argA.Equal(b.GetArgs()[i], ctx) { return false } } } return true }
go
func (af *aggFunction) Equal(b AggregationFunction, ctx context.Context) bool { if af.GetName() != b.GetName() { return false } if af.Distinct != b.IsDistinct() { return false } if len(af.GetArgs()) == len(b.GetArgs()) { for i, argA := range af.GetArgs() { if !argA.Equal(b.GetArgs()[i], ctx) { return false } } } return true }
[ "func", "(", "af", "*", "aggFunction", ")", "Equal", "(", "b", "AggregationFunction", ",", "ctx", "context", ".", "Context", ")", "bool", "{", "if", "af", ".", "GetName", "(", ")", "!=", "b", ".", "GetName", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "af", ".", "Distinct", "!=", "b", ".", "IsDistinct", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "af", ".", "GetArgs", "(", ")", ")", "==", "len", "(", "b", ".", "GetArgs", "(", ")", ")", "{", "for", "i", ",", "argA", ":=", "range", "af", ".", "GetArgs", "(", ")", "{", "if", "!", "argA", ".", "Equal", "(", "b", ".", "GetArgs", "(", ")", "[", "i", "]", ",", "ctx", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equal implements AggregationFunction interface.
[ "Equal", "implements", "AggregationFunction", "interface", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/aggregation.go#L140-L155
train
chrislusf/gleam
sql/expression/aggregation.go
Clear
func (af *aggFunction) Clear() { af.resultMapper = make(aggCtxMapper, 0) af.streamCtx = nil }
go
func (af *aggFunction) Clear() { af.resultMapper = make(aggCtxMapper, 0) af.streamCtx = nil }
[ "func", "(", "af", "*", "aggFunction", ")", "Clear", "(", ")", "{", "af", ".", "resultMapper", "=", "make", "(", "aggCtxMapper", ",", "0", ")", "\n", "af", ".", "streamCtx", "=", "nil", "\n", "}" ]
// Clear implements AggregationFunction interface.
[ "Clear", "implements", "AggregationFunction", "interface", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/aggregation.go#L196-L199
train
chrislusf/gleam
sql/mysql/error.go
Error
func (e *SQLError) Error() string { return fmt.Sprintf("ERROR %d (%s): %s", e.Code, e.State, e.Message) }
go
func (e *SQLError) Error() string { return fmt.Sprintf("ERROR %d (%s): %s", e.Code, e.State, e.Message) }
[ "func", "(", "e", "*", "SQLError", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Code", ",", "e", ".", "State", ",", "e", ".", "Message", ")", "\n", "}" ]
// Error prints errors, with a formatted string.
[ "Error", "prints", "errors", "with", "a", "formatted", "string", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/mysql/error.go#L35-L37
train
chrislusf/gleam
sql/mysql/error.go
NewErr
func NewErr(errCode uint16, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } if format, ok := MySQLErrName[errCode]; ok { e.Message = fmt.Sprintf(format, args...) } else { e.Message = fmt.Sprint(args...) } return e }
go
func NewErr(errCode uint16, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } if format, ok := MySQLErrName[errCode]; ok { e.Message = fmt.Sprintf(format, args...) } else { e.Message = fmt.Sprint(args...) } return e }
[ "func", "NewErr", "(", "errCode", "uint16", ",", "args", "...", "interface", "{", "}", ")", "*", "SQLError", "{", "e", ":=", "&", "SQLError", "{", "Code", ":", "errCode", "}", "\n\n", "if", "s", ",", "ok", ":=", "MySQLState", "[", "errCode", "]", ";", "ok", "{", "e", ".", "State", "=", "s", "\n", "}", "else", "{", "e", ".", "State", "=", "DefaultMySQLState", "\n", "}", "\n\n", "if", "format", ",", "ok", ":=", "MySQLErrName", "[", "errCode", "]", ";", "ok", "{", "e", ".", "Message", "=", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", "\n", "}", "else", "{", "e", ".", "Message", "=", "fmt", ".", "Sprint", "(", "args", "...", ")", "\n", "}", "\n\n", "return", "e", "\n", "}" ]
// NewErr generates a SQL error, with an error code and default format specifier defined in MySQLErrName.
[ "NewErr", "generates", "a", "SQL", "error", "with", "an", "error", "code", "and", "default", "format", "specifier", "defined", "in", "MySQLErrName", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/mysql/error.go#L40-L56
train
chrislusf/gleam
sql/mysql/error.go
NewErrf
func NewErrf(errCode uint16, format string, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } e.Message = fmt.Sprintf(format, args...) return e }
go
func NewErrf(errCode uint16, format string, args ...interface{}) *SQLError { e := &SQLError{Code: errCode} if s, ok := MySQLState[errCode]; ok { e.State = s } else { e.State = DefaultMySQLState } e.Message = fmt.Sprintf(format, args...) return e }
[ "func", "NewErrf", "(", "errCode", "uint16", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "*", "SQLError", "{", "e", ":=", "&", "SQLError", "{", "Code", ":", "errCode", "}", "\n\n", "if", "s", ",", "ok", ":=", "MySQLState", "[", "errCode", "]", ";", "ok", "{", "e", ".", "State", "=", "s", "\n", "}", "else", "{", "e", ".", "State", "=", "DefaultMySQLState", "\n", "}", "\n\n", "e", ".", "Message", "=", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", "\n\n", "return", "e", "\n", "}" ]
// NewErrf creates a SQL error, with an error code and a format specifier.
[ "NewErrf", "creates", "a", "SQL", "error", "with", "an", "error", "code", "and", "a", "format", "specifier", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/mysql/error.go#L59-L71
train
chrislusf/gleam
instruction/local_limit.go
DoLocalLimit
func DoLocalLimit(reader io.Reader, writer io.Writer, n int, offset int, stats *pb.InstructionStat) error { return util.ProcessRow(reader, nil, func(row *util.Row) error { stats.InputCounter++ if offset > 0 { offset-- } else { if n > 0 { row.WriteTo(writer) stats.OutputCounter++ } n-- } return nil }) }
go
func DoLocalLimit(reader io.Reader, writer io.Writer, n int, offset int, stats *pb.InstructionStat) error { return util.ProcessRow(reader, nil, func(row *util.Row) error { stats.InputCounter++ if offset > 0 { offset-- } else { if n > 0 { row.WriteTo(writer) stats.OutputCounter++ } n-- } return nil }) }
[ "func", "DoLocalLimit", "(", "reader", "io", ".", "Reader", ",", "writer", "io", ".", "Writer", ",", "n", "int", ",", "offset", "int", ",", "stats", "*", "pb", ".", "InstructionStat", ")", "error", "{", "return", "util", ".", "ProcessRow", "(", "reader", ",", "nil", ",", "func", "(", "row", "*", "util", ".", "Row", ")", "error", "{", "stats", ".", "InputCounter", "++", "\n\n", "if", "offset", ">", "0", "{", "offset", "--", "\n", "}", "else", "{", "if", "n", ">", "0", "{", "row", ".", "WriteTo", "(", "writer", ")", "\n", "stats", ".", "OutputCounter", "++", "\n", "}", "\n", "n", "--", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n\n", "}" ]
// DoLocalLimit streamingly get the n items starting from offset
[ "DoLocalLimit", "streamingly", "get", "the", "n", "items", "starting", "from", "offset" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/instruction/local_limit.go#L55-L73
train
chrislusf/gleam
sql/plan/column_pruning.go
exprHasSetVar
func exprHasSetVar(expr expression.Expression) bool { if fun, ok := expr.(*expression.ScalarFunction); ok { canPrune := true if fun.FuncName.L == ast.SetVar { return false } for _, arg := range fun.GetArgs() { canPrune = canPrune && exprHasSetVar(arg) if !canPrune { return false } } } return true }
go
func exprHasSetVar(expr expression.Expression) bool { if fun, ok := expr.(*expression.ScalarFunction); ok { canPrune := true if fun.FuncName.L == ast.SetVar { return false } for _, arg := range fun.GetArgs() { canPrune = canPrune && exprHasSetVar(arg) if !canPrune { return false } } } return true }
[ "func", "exprHasSetVar", "(", "expr", "expression", ".", "Expression", ")", "bool", "{", "if", "fun", ",", "ok", ":=", "expr", ".", "(", "*", "expression", ".", "ScalarFunction", ")", ";", "ok", "{", "canPrune", ":=", "true", "\n", "if", "fun", ".", "FuncName", ".", "L", "==", "ast", ".", "SetVar", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "arg", ":=", "range", "fun", ".", "GetArgs", "(", ")", "{", "canPrune", "=", "canPrune", "&&", "exprHasSetVar", "(", "arg", ")", "\n", "if", "!", "canPrune", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// exprHasSetVar checks if the expression has set-var function. If do, we should not prune it.
[ "exprHasSetVar", "checks", "if", "the", "expression", "has", "set", "-", "var", "function", ".", "If", "do", "we", "should", "not", "prune", "it", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/column_pruning.go#L35-L49
train
chrislusf/gleam
sql/util/segmentmap/segmentmap.go
NewSegmentMap
func NewSegmentMap(size int64) (*SegmentMap, error) { if size <= 0 { return nil, errors.Errorf("Invalid size: %d", size) } sm := &SegmentMap{ maps: make([]map[string]interface{}, size), size: size, } for i := int64(0); i < size; i++ { sm.maps[i] = make(map[string]interface{}) } sm.crcTable = crc32.MakeTable(crc32.Castagnoli) return sm, nil }
go
func NewSegmentMap(size int64) (*SegmentMap, error) { if size <= 0 { return nil, errors.Errorf("Invalid size: %d", size) } sm := &SegmentMap{ maps: make([]map[string]interface{}, size), size: size, } for i := int64(0); i < size; i++ { sm.maps[i] = make(map[string]interface{}) } sm.crcTable = crc32.MakeTable(crc32.Castagnoli) return sm, nil }
[ "func", "NewSegmentMap", "(", "size", "int64", ")", "(", "*", "SegmentMap", ",", "error", ")", "{", "if", "size", "<=", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "size", ")", "\n", "}", "\n\n", "sm", ":=", "&", "SegmentMap", "{", "maps", ":", "make", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "size", ")", ",", "size", ":", "size", ",", "}", "\n", "for", "i", ":=", "int64", "(", "0", ")", ";", "i", "<", "size", ";", "i", "++", "{", "sm", ".", "maps", "[", "i", "]", "=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "}", "\n\n", "sm", ".", "crcTable", "=", "crc32", ".", "MakeTable", "(", "crc32", ".", "Castagnoli", ")", "\n", "return", "sm", ",", "nil", "\n", "}" ]
// NewSegmentMap creates a new SegmentMap.
[ "NewSegmentMap", "creates", "a", "new", "SegmentMap", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/segmentmap/segmentmap.go#L32-L47
train
chrislusf/gleam
sql/util/segmentmap/segmentmap.go
GetSegment
func (sm *SegmentMap) GetSegment(index int64) (map[string]interface{}, error) { if index >= sm.size || index < 0 { return nil, errors.Errorf("index out of bound: %d", index) } return sm.maps[index], nil }
go
func (sm *SegmentMap) GetSegment(index int64) (map[string]interface{}, error) { if index >= sm.size || index < 0 { return nil, errors.Errorf("index out of bound: %d", index) } return sm.maps[index], nil }
[ "func", "(", "sm", "*", "SegmentMap", ")", "GetSegment", "(", "index", "int64", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "if", "index", ">=", "sm", ".", "size", "||", "index", "<", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "index", ")", "\n", "}", "\n\n", "return", "sm", ".", "maps", "[", "index", "]", ",", "nil", "\n", "}" ]
// GetSegment gets the map specific by index.
[ "GetSegment", "gets", "the", "map", "specific", "by", "index", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/segmentmap/segmentmap.go#L57-L63
train
chrislusf/gleam
sql/util/segmentmap/segmentmap.go
Set
func (sm *SegmentMap) Set(key []byte, value interface{}, force bool) bool { idx := int64(crc32.Checksum(key, sm.crcTable)) % sm.size k := string(key) _, exist := sm.maps[idx][k] if exist && !force { return exist } sm.maps[idx][k] = value return exist }
go
func (sm *SegmentMap) Set(key []byte, value interface{}, force bool) bool { idx := int64(crc32.Checksum(key, sm.crcTable)) % sm.size k := string(key) _, exist := sm.maps[idx][k] if exist && !force { return exist } sm.maps[idx][k] = value return exist }
[ "func", "(", "sm", "*", "SegmentMap", ")", "Set", "(", "key", "[", "]", "byte", ",", "value", "interface", "{", "}", ",", "force", "bool", ")", "bool", "{", "idx", ":=", "int64", "(", "crc32", ".", "Checksum", "(", "key", ",", "sm", ".", "crcTable", ")", ")", "%", "sm", ".", "size", "\n", "k", ":=", "string", "(", "key", ")", "\n", "_", ",", "exist", ":=", "sm", ".", "maps", "[", "idx", "]", "[", "k", "]", "\n", "if", "exist", "&&", "!", "force", "{", "return", "exist", "\n", "}", "\n\n", "sm", ".", "maps", "[", "idx", "]", "[", "k", "]", "=", "value", "\n", "return", "exist", "\n", "}" ]
// Set if key not exists, returns whether already exists.
[ "Set", "if", "key", "not", "exists", "returns", "whether", "already", "exists", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/segmentmap/segmentmap.go#L66-L76
train
chrislusf/gleam
sql/sessionctx/variable/statusvar.go
GetStatusVars
func GetStatusVars() (map[string]*StatusVal, error) { statusVars := make(map[string]*StatusVal) for _, statistics := range statisticsList { vals, err := statistics.Stats() if err != nil { return nil, errors.Trace(err) } for name, val := range vals { scope := statistics.GetScope(name) statusVars[name] = &StatusVal{Value: val, Scope: scope} } } return statusVars, nil }
go
func GetStatusVars() (map[string]*StatusVal, error) { statusVars := make(map[string]*StatusVal) for _, statistics := range statisticsList { vals, err := statistics.Stats() if err != nil { return nil, errors.Trace(err) } for name, val := range vals { scope := statistics.GetScope(name) statusVars[name] = &StatusVal{Value: val, Scope: scope} } } return statusVars, nil }
[ "func", "GetStatusVars", "(", ")", "(", "map", "[", "string", "]", "*", "StatusVal", ",", "error", ")", "{", "statusVars", ":=", "make", "(", "map", "[", "string", "]", "*", "StatusVal", ")", "\n\n", "for", "_", ",", "statistics", ":=", "range", "statisticsList", "{", "vals", ",", "err", ":=", "statistics", ".", "Stats", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n\n", "for", "name", ",", "val", ":=", "range", "vals", "{", "scope", ":=", "statistics", ".", "GetScope", "(", "name", ")", "\n", "statusVars", "[", "name", "]", "=", "&", "StatusVal", "{", "Value", ":", "val", ",", "Scope", ":", "scope", "}", "\n", "}", "\n", "}", "\n\n", "return", "statusVars", ",", "nil", "\n", "}" ]
// GetStatusVars gets registered statistics status variables.
[ "GetStatusVars", "gets", "registered", "statistics", "status", "variables", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/sessionctx/variable/statusvar.go#L46-L62
train
chrislusf/gleam
sql/plan/join_reorder.go
tryToGetJoinGroup
func tryToGetJoinGroup(j *Join) ([]LogicalPlan, bool) { if j.reordered || !j.cartesianJoin { return nil, false } lChild := j.GetChildByIndex(0).(LogicalPlan) rChild := j.GetChildByIndex(1).(LogicalPlan) if nj, ok := lChild.(*Join); ok { plans, valid := tryToGetJoinGroup(nj) return append(plans, rChild), valid } return []LogicalPlan{lChild, rChild}, true }
go
func tryToGetJoinGroup(j *Join) ([]LogicalPlan, bool) { if j.reordered || !j.cartesianJoin { return nil, false } lChild := j.GetChildByIndex(0).(LogicalPlan) rChild := j.GetChildByIndex(1).(LogicalPlan) if nj, ok := lChild.(*Join); ok { plans, valid := tryToGetJoinGroup(nj) return append(plans, rChild), valid } return []LogicalPlan{lChild, rChild}, true }
[ "func", "tryToGetJoinGroup", "(", "j", "*", "Join", ")", "(", "[", "]", "LogicalPlan", ",", "bool", ")", "{", "if", "j", ".", "reordered", "||", "!", "j", ".", "cartesianJoin", "{", "return", "nil", ",", "false", "\n", "}", "\n", "lChild", ":=", "j", ".", "GetChildByIndex", "(", "0", ")", ".", "(", "LogicalPlan", ")", "\n", "rChild", ":=", "j", ".", "GetChildByIndex", "(", "1", ")", ".", "(", "LogicalPlan", ")", "\n", "if", "nj", ",", "ok", ":=", "lChild", ".", "(", "*", "Join", ")", ";", "ok", "{", "plans", ",", "valid", ":=", "tryToGetJoinGroup", "(", "nj", ")", "\n", "return", "append", "(", "plans", ",", "rChild", ")", ",", "valid", "\n", "}", "\n", "return", "[", "]", "LogicalPlan", "{", "lChild", ",", "rChild", "}", ",", "true", "\n", "}" ]
// tryToGetJoinGroup tries to fetch a whole join group, which all joins is cartesian join.
[ "tryToGetJoinGroup", "tries", "to", "fetch", "a", "whole", "join", "group", "which", "all", "joins", "is", "cartesian", "join", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/join_reorder.go#L25-L36
train
chrislusf/gleam
sql/plan/join_reorder.go
walkGraphAndComposeJoin
func (e *joinReOrderSolver) walkGraphAndComposeJoin(u int) { e.visited[u] = true for _, edge := range e.graph[u] { v := edge.nodeID if !e.visited[v] { e.resultJoin = e.newJoin(e.resultJoin, e.group[v]) e.walkGraphAndComposeJoin(v) } } }
go
func (e *joinReOrderSolver) walkGraphAndComposeJoin(u int) { e.visited[u] = true for _, edge := range e.graph[u] { v := edge.nodeID if !e.visited[v] { e.resultJoin = e.newJoin(e.resultJoin, e.group[v]) e.walkGraphAndComposeJoin(v) } } }
[ "func", "(", "e", "*", "joinReOrderSolver", ")", "walkGraphAndComposeJoin", "(", "u", "int", ")", "{", "e", ".", "visited", "[", "u", "]", "=", "true", "\n", "for", "_", ",", "edge", ":=", "range", "e", ".", "graph", "[", "u", "]", "{", "v", ":=", "edge", ".", "nodeID", "\n", "if", "!", "e", ".", "visited", "[", "v", "]", "{", "e", ".", "resultJoin", "=", "e", ".", "newJoin", "(", "e", ".", "resultJoin", ",", "e", ".", "group", "[", "v", "]", ")", "\n", "e", ".", "walkGraphAndComposeJoin", "(", "v", ")", "\n", "}", "\n", "}", "\n", "}" ]
// walkGraph implements a dfs algorithm. Each time it picks a edge with lowest rate, which has been sorted before.
[ "walkGraph", "implements", "a", "dfs", "algorithm", ".", "Each", "time", "it", "picks", "a", "edge", "with", "lowest", "rate", "which", "has", "been", "sorted", "before", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/join_reorder.go#L198-L207
train
chrislusf/gleam
sql/table/column.go
FindCols
func FindCols(cols []*Column, names []string) ([]*Column, error) { var rcols []*Column for _, name := range names { col := FindCol(cols, name) if col != nil { rcols = append(rcols, col) } else { return nil, errUnknownColumn.Gen("unknown column %s", name) } } return rcols, nil }
go
func FindCols(cols []*Column, names []string) ([]*Column, error) { var rcols []*Column for _, name := range names { col := FindCol(cols, name) if col != nil { rcols = append(rcols, col) } else { return nil, errUnknownColumn.Gen("unknown column %s", name) } } return rcols, nil }
[ "func", "FindCols", "(", "cols", "[", "]", "*", "Column", ",", "names", "[", "]", "string", ")", "(", "[", "]", "*", "Column", ",", "error", ")", "{", "var", "rcols", "[", "]", "*", "Column", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "col", ":=", "FindCol", "(", "cols", ",", "name", ")", "\n", "if", "col", "!=", "nil", "{", "rcols", "=", "append", "(", "rcols", ",", "col", ")", "\n", "}", "else", "{", "return", "nil", ",", "errUnknownColumn", ".", "Gen", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n\n", "return", "rcols", ",", "nil", "\n", "}" ]
// FindCols finds columns in cols by names.
[ "FindCols", "finds", "columns", "in", "cols", "by", "names", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/table/column.go#L68-L80
train
chrislusf/gleam
sql/table/column.go
CheckOnce
func CheckOnce(cols []*Column) error { m := map[string]struct{}{} for _, col := range cols { name := col.Name _, ok := m[name.L] if ok { return errDuplicateColumn.Gen("column specified twice - %s", name) } m[name.L] = struct{}{} } return nil }
go
func CheckOnce(cols []*Column) error { m := map[string]struct{}{} for _, col := range cols { name := col.Name _, ok := m[name.L] if ok { return errDuplicateColumn.Gen("column specified twice - %s", name) } m[name.L] = struct{}{} } return nil }
[ "func", "CheckOnce", "(", "cols", "[", "]", "*", "Column", ")", "error", "{", "m", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n", "for", "_", ",", "col", ":=", "range", "cols", "{", "name", ":=", "col", ".", "Name", "\n", "_", ",", "ok", ":=", "m", "[", "name", ".", "L", "]", "\n", "if", "ok", "{", "return", "errDuplicateColumn", ".", "Gen", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "m", "[", "name", ".", "L", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CheckOnce checks if there are duplicated column names in cols.
[ "CheckOnce", "checks", "if", "there", "are", "duplicated", "column", "names", "in", "cols", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/table/column.go#L201-L214
train
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\n", "sort", ".", "Sort", "(", "fs", ")", "\n", "if", "fs", ".", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "fs", ".", "err", ")", "\n", "}", "\n\n", "fileName", ":=", "fs", ".", "getUniqueFileName", "(", ")", "\n\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\n", "for", "_", ",", "row", ":=", "range", "fs", ".", "buf", "{", "var", "body", "[", "]", "byte", "\n", "var", "head", "=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n\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\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "head", ",", "uint64", "(", "len", "(", "body", ")", ")", ")", "\n\n", "outputByte", "=", "append", "(", "outputByte", ",", "head", "...", ")", "\n", "outputByte", "=", "append", "(", "outputByte", ",", "body", "...", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "outputFile", ".", "Write", "(", "outputByte", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\n", "}", "\n", "rowSize", ":=", "int", "(", "binary", ".", "BigEndian", ".", "Uint64", "(", "head", ")", ")", "\n\n", "rowBytes", ":=", "make", "(", "[", "]", "byte", ",", "rowSize", ")", "\n\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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "dcod", ",", "err", "=", "codec", ".", "Decode", "(", "rowBytes", ",", "fs", ".", "keySize", "+", "fs", ".", "valSize", "+", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\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\n", "heap", ".", "Init", "(", "fs", ".", "rowHeap", ")", "\n", "if", "fs", ".", "rowHeap", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "fs", ".", "rowHeap", ".", "err", ")", "\n", "}", "\n\n", "err", ":=", "fs", ".", "openAllFiles", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "im", ":=", "&", "item", "{", "index", ":", "id", ",", "value", ":", "row", ",", "}", "\n\n", "heap", ".", "Push", "(", "fs", ".", "rowHeap", ",", "im", ")", "\n", "if", "fs", ".", "rowHeap", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "fs", ".", "rowHeap", ".", "err", ")", "\n", "}", "\n", "}", "\n\n", "fs", ".", "fetched", "=", "true", "\n", "}", "\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\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\n", "heap", ".", "Push", "(", "fs", ".", "rowHeap", ",", "im", ")", "\n", "if", "fs", ".", "rowHeap", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "fs", ".", "rowHeap", ".", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "im", ".", "value", ",", "nil", "\n", "}", "\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", "(", "\"", "\"", ",", "h", ".", "Value", ")", "\n", "if", "len", "(", "s", ")", "%", "2", "!=", "0", "{", "s", "=", "\"", "\"", "+", "s", "\n", "}", "\n\n", "// should never error.", "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\n", "b", ":=", "newExecutorBuilder", "(", "ctx", ",", "a", ".", "InfoSchema", ")", "\n\n", "exe", ":=", "b", ".", "build", "(", "a", ".", "Plan", ")", "\n", "if", "b", ".", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "b", ".", "err", ")", "\n", "}", "\n\n", "if", "exe", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "plan", ".", "ToString", "(", "a", ".", "Plan", ")", ")", "\n", "}", "\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", "(", "\"", "\"", ",", "cleanupRequest", ".", "GetFlowHashCode", "(", ")", ")", "\n", "dir", ":=", "path", ".", "Join", "(", "*", "as", ".", "Option", ".", "Dir", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cleanupRequest", ".", "GetFlowHashCode", "(", ")", ")", ")", "\n", "os", ".", "RemoveAll", "(", "dir", ")", "\n\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", "(", "\"", "\"", ",", "request", ".", "GetInstructionSet", "(", ")", ".", "GetFlowHashCode", "(", ")", ")", ",", "request", ".", "GetDir", "(", ")", ")", "\n", "os", ".", "MkdirAll", "(", "dir", ",", "0755", ")", "\n\n", "allocated", ":=", "*", "request", ".", "GetResource", "(", ")", "\n\n", "as", ".", "plusAllocated", "(", "allocated", ")", "\n", "defer", "as", ".", "minusAllocated", "(", "allocated", ")", "\n\n", "request", ".", "InstructionSet", ".", "AgentAddress", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "as", ".", "Option", ".", "Host", ",", "*", "as", ".", "Option", ".", "Port", ")", "\n\n", "statsChan", ":=", "createStatsChanByInstructionSet", "(", "request", ".", "InstructionSet", ")", "\n\n", "defer", "deleteStatsChanByInstructionSet", "(", "request", ".", "InstructionSet", ")", "\n\n", "return", "as", ".", "executeCommand", "(", "stream", ",", "request", ",", "dir", ",", "statsChan", ")", "\n\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\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\n", "statsChan", "<-", "stats", "\n", "// fmt.Printf(\"received stats: %+v\\n\", 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", "(", "\"", "\"", ",", "deleteRequest", ".", "Name", ")", "\n", "as", ".", "storageBackend", ".", "DeleteNamedDatasetShard", "(", "deleteRequest", ".", "Name", ")", "\n", "as", ".", "inMemoryChannels", ".", "Cleanup", "(", "deleteRequest", ".", "Name", ")", "\n\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", "==", "'%'", "{", "// 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", "--", "\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", "(", "\"", "\"", ")", "\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", ":", "// Those types are stored in 8 bytes.", "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", "(", "\"", "\"", ",", "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\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\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", "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\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