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
vitessio/vitess
go/vt/topo/helpers/copy.go
CopyRoutingRules
func CopyRoutingRules(ctx context.Context, fromTS, toTS *topo.Server) { rr, err := fromTS.GetRoutingRules(ctx) if err != nil { log.Fatalf("GetRoutingRules: %v", err) } if err := toTS.SaveRoutingRules(ctx, rr); err != nil { log.Errorf("SaveRoutingRules(%v): %v", rr, err) } }
go
func CopyRoutingRules(ctx context.Context, fromTS, toTS *topo.Server) { rr, err := fromTS.GetRoutingRules(ctx) if err != nil { log.Fatalf("GetRoutingRules: %v", err) } if err := toTS.SaveRoutingRules(ctx, rr); err != nil { log.Errorf("SaveRoutingRules(%v): %v", rr, err) } }
[ "func", "CopyRoutingRules", "(", "ctx", "context", ".", "Context", ",", "fromTS", ",", "toTS", "*", "topo", ".", "Server", ")", "{", "rr", ",", "err", ":=", "fromTS", ".", "GetRoutingRules", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "toTS", ".", "SaveRoutingRules", "(", "ctx", ",", "rr", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "rr", ",", "err", ")", "\n", "}", "\n", "}" ]
// CopyRoutingRules will create the routing rules in the destination topo.
[ "CopyRoutingRules", "will", "create", "the", "routing", "rules", "in", "the", "destination", "topo", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/copy.go#L180-L188
train
vitessio/vitess
go/vt/logz/logz_utils.go
Wrappable
func Wrappable(in string) string { buf := bytes.NewBuffer(nil) for _, ch := range in { buf.WriteRune(ch) if ch == ',' || ch == ')' { // zero-width whitespace buf.WriteRune('\u200B') } } return buf.String() }
go
func Wrappable(in string) string { buf := bytes.NewBuffer(nil) for _, ch := range in { buf.WriteRune(ch) if ch == ',' || ch == ')' { // zero-width whitespace buf.WriteRune('\u200B') } } return buf.String() }
[ "func", "Wrappable", "(", "in", "string", ")", "string", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "for", "_", ",", "ch", ":=", "range", "in", "{", "buf", ".", "WriteRune", "(", "ch", ")", "\n", "if", "ch", "==", "','", "||", "ch", "==", "')'", "{", "// zero-width whitespace", "buf", ".", "WriteRune", "(", "'\\u200B'", ")", "\n", "}", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Wrappable inserts zero-width whitespaces to make // the string wrappable.
[ "Wrappable", "inserts", "zero", "-", "width", "whitespaces", "to", "make", "the", "string", "wrappable", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/logz/logz_utils.go#L145-L155
train
vitessio/vitess
go/sqltypes/value.go
NewInt64
func NewInt64(v int64) Value { return MakeTrusted(Int64, strconv.AppendInt(nil, v, 10)) }
go
func NewInt64(v int64) Value { return MakeTrusted(Int64, strconv.AppendInt(nil, v, 10)) }
[ "func", "NewInt64", "(", "v", "int64", ")", "Value", "{", "return", "MakeTrusted", "(", "Int64", ",", "strconv", ".", "AppendInt", "(", "nil", ",", "v", ",", "10", ")", ")", "\n", "}" ]
// NewInt64 builds an Int64 Value.
[ "NewInt64", "builds", "an", "Int64", "Value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L99-L101
train
vitessio/vitess
go/sqltypes/value.go
NewInt8
func NewInt8(v int8) Value { return MakeTrusted(Int8, strconv.AppendInt(nil, int64(v), 10)) }
go
func NewInt8(v int8) Value { return MakeTrusted(Int8, strconv.AppendInt(nil, int64(v), 10)) }
[ "func", "NewInt8", "(", "v", "int8", ")", "Value", "{", "return", "MakeTrusted", "(", "Int8", ",", "strconv", ".", "AppendInt", "(", "nil", ",", "int64", "(", "v", ")", ",", "10", ")", ")", "\n", "}" ]
// NewInt8 builds an Int8 Value.
[ "NewInt8", "builds", "an", "Int8", "Value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L104-L106
train
vitessio/vitess
go/sqltypes/value.go
NewInt32
func NewInt32(v int32) Value { return MakeTrusted(Int32, strconv.AppendInt(nil, int64(v), 10)) }
go
func NewInt32(v int32) Value { return MakeTrusted(Int32, strconv.AppendInt(nil, int64(v), 10)) }
[ "func", "NewInt32", "(", "v", "int32", ")", "Value", "{", "return", "MakeTrusted", "(", "Int32", ",", "strconv", ".", "AppendInt", "(", "nil", ",", "int64", "(", "v", ")", ",", "10", ")", ")", "\n", "}" ]
// NewInt32 builds an Int64 Value.
[ "NewInt32", "builds", "an", "Int64", "Value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L109-L111
train
vitessio/vitess
go/sqltypes/value.go
NewUint64
func NewUint64(v uint64) Value { return MakeTrusted(Uint64, strconv.AppendUint(nil, v, 10)) }
go
func NewUint64(v uint64) Value { return MakeTrusted(Uint64, strconv.AppendUint(nil, v, 10)) }
[ "func", "NewUint64", "(", "v", "uint64", ")", "Value", "{", "return", "MakeTrusted", "(", "Uint64", ",", "strconv", ".", "AppendUint", "(", "nil", ",", "v", ",", "10", ")", ")", "\n", "}" ]
// NewUint64 builds an Uint64 Value.
[ "NewUint64", "builds", "an", "Uint64", "Value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L114-L116
train
vitessio/vitess
go/sqltypes/value.go
NewUint32
func NewUint32(v uint32) Value { return MakeTrusted(Uint32, strconv.AppendUint(nil, uint64(v), 10)) }
go
func NewUint32(v uint32) Value { return MakeTrusted(Uint32, strconv.AppendUint(nil, uint64(v), 10)) }
[ "func", "NewUint32", "(", "v", "uint32", ")", "Value", "{", "return", "MakeTrusted", "(", "Uint32", ",", "strconv", ".", "AppendUint", "(", "nil", ",", "uint64", "(", "v", ")", ",", "10", ")", ")", "\n", "}" ]
// NewUint32 builds an Uint32 Value.
[ "NewUint32", "builds", "an", "Uint32", "Value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L119-L121
train
vitessio/vitess
go/sqltypes/value.go
NewFloat64
func NewFloat64(v float64) Value { return MakeTrusted(Float64, strconv.AppendFloat(nil, v, 'g', -1, 64)) }
go
func NewFloat64(v float64) Value { return MakeTrusted(Float64, strconv.AppendFloat(nil, v, 'g', -1, 64)) }
[ "func", "NewFloat64", "(", "v", "float64", ")", "Value", "{", "return", "MakeTrusted", "(", "Float64", ",", "strconv", ".", "AppendFloat", "(", "nil", ",", "v", ",", "'g'", ",", "-", "1", ",", "64", ")", ")", "\n", "}" ]
// NewFloat64 builds an Float64 Value.
[ "NewFloat64", "builds", "an", "Float64", "Value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L124-L126
train
vitessio/vitess
go/sqltypes/value.go
NewIntegral
func NewIntegral(val string) (n Value, err error) { signed, err := strconv.ParseInt(val, 0, 64) if err == nil { return MakeTrusted(Int64, strconv.AppendInt(nil, signed, 10)), nil } unsigned, err := strconv.ParseUint(val, 0, 64) if err != nil { return Value{}, err } return MakeTrusted(Uint64, strconv.AppendUint(nil, unsigned, 10)), nil }
go
func NewIntegral(val string) (n Value, err error) { signed, err := strconv.ParseInt(val, 0, 64) if err == nil { return MakeTrusted(Int64, strconv.AppendInt(nil, signed, 10)), nil } unsigned, err := strconv.ParseUint(val, 0, 64) if err != nil { return Value{}, err } return MakeTrusted(Uint64, strconv.AppendUint(nil, unsigned, 10)), nil }
[ "func", "NewIntegral", "(", "val", "string", ")", "(", "n", "Value", ",", "err", "error", ")", "{", "signed", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "val", ",", "0", ",", "64", ")", "\n", "if", "err", "==", "nil", "{", "return", "MakeTrusted", "(", "Int64", ",", "strconv", ".", "AppendInt", "(", "nil", ",", "signed", ",", "10", ")", ")", ",", "nil", "\n", "}", "\n", "unsigned", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "val", ",", "0", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Value", "{", "}", ",", "err", "\n", "}", "\n", "return", "MakeTrusted", "(", "Uint64", ",", "strconv", ".", "AppendUint", "(", "nil", ",", "unsigned", ",", "10", ")", ")", ",", "nil", "\n", "}" ]
// NewIntegral builds an integral type from a string representation. // The type will be Int64 or Uint64. Int64 will be preferred where possible.
[ "NewIntegral", "builds", "an", "integral", "type", "from", "a", "string", "representation", ".", "The", "type", "will", "be", "Int64", "or", "Uint64", ".", "Int64", "will", "be", "preferred", "where", "possible", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L141-L151
train
vitessio/vitess
go/sqltypes/value.go
ToString
func (v Value) ToString() string { if v.typ == Expression { return "" } return hack.String(v.val) }
go
func (v Value) ToString() string { if v.typ == Expression { return "" } return hack.String(v.val) }
[ "func", "(", "v", "Value", ")", "ToString", "(", ")", "string", "{", "if", "v", ".", "typ", "==", "Expression", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "hack", ".", "String", "(", "v", ".", "val", ")", "\n", "}" ]
// ToString returns the value as MySQL would return it as string. // If the value is not convertible like in the case of Expression, it returns nil.
[ "ToString", "returns", "the", "value", "as", "MySQL", "would", "return", "it", "as", "string", ".", "If", "the", "value", "is", "not", "convertible", "like", "in", "the", "case", "of", "Expression", "it", "returns", "nil", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L206-L211
train
vitessio/vitess
go/sqltypes/value.go
EncodeASCII
func (v Value) EncodeASCII(b BinWriter) { switch { case v.typ == Null: b.Write(nullstr) case v.IsQuoted() || v.typ == Bit: encodeBytesASCII(v.val, b) default: b.Write(v.val) } }
go
func (v Value) EncodeASCII(b BinWriter) { switch { case v.typ == Null: b.Write(nullstr) case v.IsQuoted() || v.typ == Bit: encodeBytesASCII(v.val, b) default: b.Write(v.val) } }
[ "func", "(", "v", "Value", ")", "EncodeASCII", "(", "b", "BinWriter", ")", "{", "switch", "{", "case", "v", ".", "typ", "==", "Null", ":", "b", ".", "Write", "(", "nullstr", ")", "\n", "case", "v", ".", "IsQuoted", "(", ")", "||", "v", ".", "typ", "==", "Bit", ":", "encodeBytesASCII", "(", "v", ".", "val", ",", "b", ")", "\n", "default", ":", "b", ".", "Write", "(", "v", ".", "val", ")", "\n", "}", "\n", "}" ]
// EncodeASCII encodes the value using 7-bit clean ascii bytes.
[ "EncodeASCII", "encodes", "the", "value", "using", "7", "-", "bit", "clean", "ascii", "bytes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L239-L248
train
vitessio/vitess
go/sqltypes/value.go
MarshalJSON
func (v Value) MarshalJSON() ([]byte, error) { switch { case v.IsQuoted() || v.typ == Bit: return json.Marshal(v.ToString()) case v.typ == Null: return nullstr, nil } return v.val, nil }
go
func (v Value) MarshalJSON() ([]byte, error) { switch { case v.IsQuoted() || v.typ == Bit: return json.Marshal(v.ToString()) case v.typ == Null: return nullstr, nil } return v.val, nil }
[ "func", "(", "v", "Value", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "switch", "{", "case", "v", ".", "IsQuoted", "(", ")", "||", "v", ".", "typ", "==", "Bit", ":", "return", "json", ".", "Marshal", "(", "v", ".", "ToString", "(", ")", ")", "\n", "case", "v", ".", "typ", "==", "Null", ":", "return", "nullstr", ",", "nil", "\n", "}", "\n", "return", "v", ".", "val", ",", "nil", "\n", "}" ]
// MarshalJSON should only be used for testing. // It's not a complete implementation.
[ "MarshalJSON", "should", "only", "be", "used", "for", "testing", ".", "It", "s", "not", "a", "complete", "implementation", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L292-L300
train
vitessio/vitess
go/sqltypes/value.go
UnmarshalJSON
func (v *Value) UnmarshalJSON(b []byte) error { if len(b) == 0 { return fmt.Errorf("error unmarshaling empty bytes") } var val interface{} var err error switch b[0] { case '-': var ival int64 err = json.Unmarshal(b, &ival) val = ival case '"': var bval []byte err = json.Unmarshal(b, &bval) val = bval case 'n': // null err = json.Unmarshal(b, &val) default: var uval uint64 err = json.Unmarshal(b, &uval) val = uval } if err != nil { return err } *v, err = InterfaceToValue(val) return err }
go
func (v *Value) UnmarshalJSON(b []byte) error { if len(b) == 0 { return fmt.Errorf("error unmarshaling empty bytes") } var val interface{} var err error switch b[0] { case '-': var ival int64 err = json.Unmarshal(b, &ival) val = ival case '"': var bval []byte err = json.Unmarshal(b, &bval) val = bval case 'n': // null err = json.Unmarshal(b, &val) default: var uval uint64 err = json.Unmarshal(b, &uval) val = uval } if err != nil { return err } *v, err = InterfaceToValue(val) return err }
[ "func", "(", "v", "*", "Value", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "b", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "val", "interface", "{", "}", "\n", "var", "err", "error", "\n", "switch", "b", "[", "0", "]", "{", "case", "'-'", ":", "var", "ival", "int64", "\n", "err", "=", "json", ".", "Unmarshal", "(", "b", ",", "&", "ival", ")", "\n", "val", "=", "ival", "\n", "case", "'\"'", ":", "var", "bval", "[", "]", "byte", "\n", "err", "=", "json", ".", "Unmarshal", "(", "b", ",", "&", "bval", ")", "\n", "val", "=", "bval", "\n", "case", "'n'", ":", "// null", "err", "=", "json", ".", "Unmarshal", "(", "b", ",", "&", "val", ")", "\n", "default", ":", "var", "uval", "uint64", "\n", "err", "=", "json", ".", "Unmarshal", "(", "b", ",", "&", "uval", ")", "\n", "val", "=", "uval", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "v", ",", "err", "=", "InterfaceToValue", "(", "val", ")", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON should only be used for testing. // It's not a complete implementation.
[ "UnmarshalJSON", "should", "only", "be", "used", "for", "testing", ".", "It", "s", "not", "a", "complete", "implementation", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/value.go#L304-L331
train
vitessio/vitess
go/vt/worker/fakevtworkerclient/fakevtworkerclient.go
FakeVtworkerClientFactory
func (f *FakeVtworkerClient) FakeVtworkerClientFactory(addr string) (vtworkerclient.Client, error) { return &perAddrFakeVtworkerClient{f, addr}, nil }
go
func (f *FakeVtworkerClient) FakeVtworkerClientFactory(addr string) (vtworkerclient.Client, error) { return &perAddrFakeVtworkerClient{f, addr}, nil }
[ "func", "(", "f", "*", "FakeVtworkerClient", ")", "FakeVtworkerClientFactory", "(", "addr", "string", ")", "(", "vtworkerclient", ".", "Client", ",", "error", ")", "{", "return", "&", "perAddrFakeVtworkerClient", "{", "f", ",", "addr", "}", ",", "nil", "\n", "}" ]
// FakeVtworkerClientFactory returns the current instance and stores the // dialed server address in an outer struct.
[ "FakeVtworkerClientFactory", "returns", "the", "current", "instance", "and", "stores", "the", "dialed", "server", "address", "in", "an", "outer", "struct", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/fakevtworkerclient/fakevtworkerclient.go#L42-L44
train
vitessio/vitess
go/vt/worker/fakevtworkerclient/fakevtworkerclient.go
ExecuteVtworkerCommand
func (c *perAddrFakeVtworkerClient) ExecuteVtworkerCommand(ctx context.Context, args []string) (logutil.EventStream, error) { return c.FakeLoggerEventStreamingClient.StreamResult(c.addr, args) }
go
func (c *perAddrFakeVtworkerClient) ExecuteVtworkerCommand(ctx context.Context, args []string) (logutil.EventStream, error) { return c.FakeLoggerEventStreamingClient.StreamResult(c.addr, args) }
[ "func", "(", "c", "*", "perAddrFakeVtworkerClient", ")", "ExecuteVtworkerCommand", "(", "ctx", "context", ".", "Context", ",", "args", "[", "]", "string", ")", "(", "logutil", ".", "EventStream", ",", "error", ")", "{", "return", "c", ".", "FakeLoggerEventStreamingClient", ".", "StreamResult", "(", "c", ".", "addr", ",", "args", ")", "\n", "}" ]
// ExecuteVtworkerCommand is part of the vtworkerclient interface.
[ "ExecuteVtworkerCommand", "is", "part", "of", "the", "vtworkerclient", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/fakevtworkerclient/fakevtworkerclient.go#L54-L56
train
vitessio/vitess
go/cache/lru_cache.go
NewLRUCache
func NewLRUCache(capacity int64) *LRUCache { return &LRUCache{ list: list.New(), table: make(map[string]*list.Element), capacity: capacity, } }
go
func NewLRUCache(capacity int64) *LRUCache { return &LRUCache{ list: list.New(), table: make(map[string]*list.Element), capacity: capacity, } }
[ "func", "NewLRUCache", "(", "capacity", "int64", ")", "*", "LRUCache", "{", "return", "&", "LRUCache", "{", "list", ":", "list", ".", "New", "(", ")", ",", "table", ":", "make", "(", "map", "[", "string", "]", "*", "list", ".", "Element", ")", ",", "capacity", ":", "capacity", ",", "}", "\n", "}" ]
// NewLRUCache creates a new empty cache with the given capacity.
[ "NewLRUCache", "creates", "a", "new", "empty", "cache", "with", "the", "given", "capacity", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L70-L76
train
vitessio/vitess
go/cache/lru_cache.go
Get
func (lru *LRUCache) Get(key string) (v Value, ok bool) { lru.mu.Lock() defer lru.mu.Unlock() element := lru.table[key] if element == nil { return nil, false } lru.moveToFront(element) return element.Value.(*entry).value, true }
go
func (lru *LRUCache) Get(key string) (v Value, ok bool) { lru.mu.Lock() defer lru.mu.Unlock() element := lru.table[key] if element == nil { return nil, false } lru.moveToFront(element) return element.Value.(*entry).value, true }
[ "func", "(", "lru", "*", "LRUCache", ")", "Get", "(", "key", "string", ")", "(", "v", "Value", ",", "ok", "bool", ")", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "element", ":=", "lru", ".", "table", "[", "key", "]", "\n", "if", "element", "==", "nil", "{", "return", "nil", ",", "false", "\n", "}", "\n", "lru", ".", "moveToFront", "(", "element", ")", "\n", "return", "element", ".", "Value", ".", "(", "*", "entry", ")", ".", "value", ",", "true", "\n", "}" ]
// Get returns a value from the cache, and marks the entry as most // recently used.
[ "Get", "returns", "a", "value", "from", "the", "cache", "and", "marks", "the", "entry", "as", "most", "recently", "used", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L80-L90
train
vitessio/vitess
go/cache/lru_cache.go
Set
func (lru *LRUCache) Set(key string, value Value) { lru.mu.Lock() defer lru.mu.Unlock() if element := lru.table[key]; element != nil { lru.updateInplace(element, value) } else { lru.addNew(key, value) } }
go
func (lru *LRUCache) Set(key string, value Value) { lru.mu.Lock() defer lru.mu.Unlock() if element := lru.table[key]; element != nil { lru.updateInplace(element, value) } else { lru.addNew(key, value) } }
[ "func", "(", "lru", "*", "LRUCache", ")", "Set", "(", "key", "string", ",", "value", "Value", ")", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "element", ":=", "lru", ".", "table", "[", "key", "]", ";", "element", "!=", "nil", "{", "lru", ".", "updateInplace", "(", "element", ",", "value", ")", "\n", "}", "else", "{", "lru", ".", "addNew", "(", "key", ",", "value", ")", "\n", "}", "\n", "}" ]
// Set sets a value in the cache.
[ "Set", "sets", "a", "value", "in", "the", "cache", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L105-L114
train
vitessio/vitess
go/cache/lru_cache.go
SetIfAbsent
func (lru *LRUCache) SetIfAbsent(key string, value Value) { lru.mu.Lock() defer lru.mu.Unlock() if element := lru.table[key]; element != nil { lru.moveToFront(element) } else { lru.addNew(key, value) } }
go
func (lru *LRUCache) SetIfAbsent(key string, value Value) { lru.mu.Lock() defer lru.mu.Unlock() if element := lru.table[key]; element != nil { lru.moveToFront(element) } else { lru.addNew(key, value) } }
[ "func", "(", "lru", "*", "LRUCache", ")", "SetIfAbsent", "(", "key", "string", ",", "value", "Value", ")", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "element", ":=", "lru", ".", "table", "[", "key", "]", ";", "element", "!=", "nil", "{", "lru", ".", "moveToFront", "(", "element", ")", "\n", "}", "else", "{", "lru", ".", "addNew", "(", "key", ",", "value", ")", "\n", "}", "\n", "}" ]
// SetIfAbsent will set the value in the cache if not present. If the // value exists in the cache, we don't set it.
[ "SetIfAbsent", "will", "set", "the", "value", "in", "the", "cache", "if", "not", "present", ".", "If", "the", "value", "exists", "in", "the", "cache", "we", "don", "t", "set", "it", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L118-L127
train
vitessio/vitess
go/cache/lru_cache.go
Delete
func (lru *LRUCache) Delete(key string) bool { lru.mu.Lock() defer lru.mu.Unlock() element := lru.table[key] if element == nil { return false } lru.list.Remove(element) delete(lru.table, key) lru.size -= element.Value.(*entry).size return true }
go
func (lru *LRUCache) Delete(key string) bool { lru.mu.Lock() defer lru.mu.Unlock() element := lru.table[key] if element == nil { return false } lru.list.Remove(element) delete(lru.table, key) lru.size -= element.Value.(*entry).size return true }
[ "func", "(", "lru", "*", "LRUCache", ")", "Delete", "(", "key", "string", ")", "bool", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "element", ":=", "lru", ".", "table", "[", "key", "]", "\n", "if", "element", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "lru", ".", "list", ".", "Remove", "(", "element", ")", "\n", "delete", "(", "lru", ".", "table", ",", "key", ")", "\n", "lru", ".", "size", "-=", "element", ".", "Value", ".", "(", "*", "entry", ")", ".", "size", "\n", "return", "true", "\n", "}" ]
// Delete removes an entry from the cache, and returns if the entry existed.
[ "Delete", "removes", "an", "entry", "from", "the", "cache", "and", "returns", "if", "the", "entry", "existed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L130-L143
train
vitessio/vitess
go/cache/lru_cache.go
Clear
func (lru *LRUCache) Clear() { lru.mu.Lock() defer lru.mu.Unlock() lru.list.Init() lru.table = make(map[string]*list.Element) lru.size = 0 }
go
func (lru *LRUCache) Clear() { lru.mu.Lock() defer lru.mu.Unlock() lru.list.Init() lru.table = make(map[string]*list.Element) lru.size = 0 }
[ "func", "(", "lru", "*", "LRUCache", ")", "Clear", "(", ")", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "lru", ".", "list", ".", "Init", "(", ")", "\n", "lru", ".", "table", "=", "make", "(", "map", "[", "string", "]", "*", "list", ".", "Element", ")", "\n", "lru", ".", "size", "=", "0", "\n", "}" ]
// Clear will clear the entire cache.
[ "Clear", "will", "clear", "the", "entire", "cache", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L146-L153
train
vitessio/vitess
go/cache/lru_cache.go
SetCapacity
func (lru *LRUCache) SetCapacity(capacity int64) { lru.mu.Lock() defer lru.mu.Unlock() lru.capacity = capacity lru.checkCapacity() }
go
func (lru *LRUCache) SetCapacity(capacity int64) { lru.mu.Lock() defer lru.mu.Unlock() lru.capacity = capacity lru.checkCapacity() }
[ "func", "(", "lru", "*", "LRUCache", ")", "SetCapacity", "(", "capacity", "int64", ")", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "lru", ".", "capacity", "=", "capacity", "\n", "lru", ".", "checkCapacity", "(", ")", "\n", "}" ]
// SetCapacity will set the capacity of the cache. If the capacity is // smaller, and the current cache size exceed that capacity, the cache // will be shrank.
[ "SetCapacity", "will", "set", "the", "capacity", "of", "the", "cache", ".", "If", "the", "capacity", "is", "smaller", "and", "the", "current", "cache", "size", "exceed", "that", "capacity", "the", "cache", "will", "be", "shrank", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L158-L164
train
vitessio/vitess
go/cache/lru_cache.go
Stats
func (lru *LRUCache) Stats() (length, size, capacity, evictions int64, oldest time.Time) { lru.mu.Lock() defer lru.mu.Unlock() if lastElem := lru.list.Back(); lastElem != nil { oldest = lastElem.Value.(*entry).timeAccessed } return int64(lru.list.Len()), lru.size, lru.capacity, lru.evictions, oldest }
go
func (lru *LRUCache) Stats() (length, size, capacity, evictions int64, oldest time.Time) { lru.mu.Lock() defer lru.mu.Unlock() if lastElem := lru.list.Back(); lastElem != nil { oldest = lastElem.Value.(*entry).timeAccessed } return int64(lru.list.Len()), lru.size, lru.capacity, lru.evictions, oldest }
[ "func", "(", "lru", "*", "LRUCache", ")", "Stats", "(", ")", "(", "length", ",", "size", ",", "capacity", ",", "evictions", "int64", ",", "oldest", "time", ".", "Time", ")", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "lastElem", ":=", "lru", ".", "list", ".", "Back", "(", ")", ";", "lastElem", "!=", "nil", "{", "oldest", "=", "lastElem", ".", "Value", ".", "(", "*", "entry", ")", ".", "timeAccessed", "\n", "}", "\n", "return", "int64", "(", "lru", ".", "list", ".", "Len", "(", ")", ")", ",", "lru", ".", "size", ",", "lru", ".", "capacity", ",", "lru", ".", "evictions", ",", "oldest", "\n", "}" ]
// Stats returns a few stats on the cache.
[ "Stats", "returns", "a", "few", "stats", "on", "the", "cache", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L167-L174
train
vitessio/vitess
go/cache/lru_cache.go
StatsJSON
func (lru *LRUCache) StatsJSON() string { if lru == nil { return "{}" } l, s, c, e, o := lru.Stats() return fmt.Sprintf("{\"Length\": %v, \"Size\": %v, \"Capacity\": %v, \"Evictions\": %v, \"OldestAccess\": \"%v\"}", l, s, c, e, o) }
go
func (lru *LRUCache) StatsJSON() string { if lru == nil { return "{}" } l, s, c, e, o := lru.Stats() return fmt.Sprintf("{\"Length\": %v, \"Size\": %v, \"Capacity\": %v, \"Evictions\": %v, \"OldestAccess\": \"%v\"}", l, s, c, e, o) }
[ "func", "(", "lru", "*", "LRUCache", ")", "StatsJSON", "(", ")", "string", "{", "if", "lru", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "l", ",", "s", ",", "c", ",", "e", ",", "o", ":=", "lru", ".", "Stats", "(", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "l", ",", "s", ",", "c", ",", "e", ",", "o", ")", "\n", "}" ]
// StatsJSON returns stats as a JSON object in a string.
[ "StatsJSON", "returns", "stats", "as", "a", "JSON", "object", "in", "a", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L177-L183
train
vitessio/vitess
go/cache/lru_cache.go
Length
func (lru *LRUCache) Length() int64 { lru.mu.Lock() defer lru.mu.Unlock() return int64(lru.list.Len()) }
go
func (lru *LRUCache) Length() int64 { lru.mu.Lock() defer lru.mu.Unlock() return int64(lru.list.Len()) }
[ "func", "(", "lru", "*", "LRUCache", ")", "Length", "(", ")", "int64", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "int64", "(", "lru", ".", "list", ".", "Len", "(", ")", ")", "\n", "}" ]
// Length returns how many elements are in the cache
[ "Length", "returns", "how", "many", "elements", "are", "in", "the", "cache" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L186-L190
train
vitessio/vitess
go/cache/lru_cache.go
Capacity
func (lru *LRUCache) Capacity() int64 { lru.mu.Lock() defer lru.mu.Unlock() return lru.capacity }
go
func (lru *LRUCache) Capacity() int64 { lru.mu.Lock() defer lru.mu.Unlock() return lru.capacity }
[ "func", "(", "lru", "*", "LRUCache", ")", "Capacity", "(", ")", "int64", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "lru", ".", "capacity", "\n", "}" ]
// Capacity returns the cache maximum capacity.
[ "Capacity", "returns", "the", "cache", "maximum", "capacity", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L200-L204
train
vitessio/vitess
go/cache/lru_cache.go
Evictions
func (lru *LRUCache) Evictions() int64 { lru.mu.Lock() defer lru.mu.Unlock() return lru.evictions }
go
func (lru *LRUCache) Evictions() int64 { lru.mu.Lock() defer lru.mu.Unlock() return lru.evictions }
[ "func", "(", "lru", "*", "LRUCache", ")", "Evictions", "(", ")", "int64", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "lru", ".", "evictions", "\n", "}" ]
// Evictions returns the eviction count.
[ "Evictions", "returns", "the", "eviction", "count", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L207-L211
train
vitessio/vitess
go/cache/lru_cache.go
Keys
func (lru *LRUCache) Keys() []string { lru.mu.Lock() defer lru.mu.Unlock() keys := make([]string, 0, lru.list.Len()) for e := lru.list.Front(); e != nil; e = e.Next() { keys = append(keys, e.Value.(*entry).key) } return keys }
go
func (lru *LRUCache) Keys() []string { lru.mu.Lock() defer lru.mu.Unlock() keys := make([]string, 0, lru.list.Len()) for e := lru.list.Front(); e != nil; e = e.Next() { keys = append(keys, e.Value.(*entry).key) } return keys }
[ "func", "(", "lru", "*", "LRUCache", ")", "Keys", "(", ")", "[", "]", "string", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "lru", ".", "list", ".", "Len", "(", ")", ")", "\n", "for", "e", ":=", "lru", ".", "list", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "keys", "=", "append", "(", "keys", ",", "e", ".", "Value", ".", "(", "*", "entry", ")", ".", "key", ")", "\n", "}", "\n", "return", "keys", "\n", "}" ]
// Keys returns all the keys for the cache, ordered from most recently // used to last recently used.
[ "Keys", "returns", "all", "the", "keys", "for", "the", "cache", "ordered", "from", "most", "recently", "used", "to", "last", "recently", "used", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L226-L235
train
vitessio/vitess
go/cache/lru_cache.go
Items
func (lru *LRUCache) Items() []Item { lru.mu.Lock() defer lru.mu.Unlock() items := make([]Item, 0, lru.list.Len()) for e := lru.list.Front(); e != nil; e = e.Next() { v := e.Value.(*entry) items = append(items, Item{Key: v.key, Value: v.value}) } return items }
go
func (lru *LRUCache) Items() []Item { lru.mu.Lock() defer lru.mu.Unlock() items := make([]Item, 0, lru.list.Len()) for e := lru.list.Front(); e != nil; e = e.Next() { v := e.Value.(*entry) items = append(items, Item{Key: v.key, Value: v.value}) } return items }
[ "func", "(", "lru", "*", "LRUCache", ")", "Items", "(", ")", "[", "]", "Item", "{", "lru", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "lru", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "items", ":=", "make", "(", "[", "]", "Item", ",", "0", ",", "lru", ".", "list", ".", "Len", "(", ")", ")", "\n", "for", "e", ":=", "lru", ".", "list", ".", "Front", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "e", ".", "Next", "(", ")", "{", "v", ":=", "e", ".", "Value", ".", "(", "*", "entry", ")", "\n", "items", "=", "append", "(", "items", ",", "Item", "{", "Key", ":", "v", ".", "key", ",", "Value", ":", "v", ".", "value", "}", ")", "\n", "}", "\n", "return", "items", "\n", "}" ]
// Items returns all the values for the cache, ordered from most recently // used to last recently used.
[ "Items", "returns", "all", "the", "values", "for", "the", "cache", "ordered", "from", "most", "recently", "used", "to", "last", "recently", "used", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cache/lru_cache.go#L239-L249
train
vitessio/vitess
go/vt/throttler/result.go
add
func (rr *resultRing) add(r result) { rr.mu.Lock() defer rr.mu.Unlock() rr.values[rr.position] = r rr.position++ if rr.position == len(rr.values) { rr.position = 0 rr.wrapped = true } }
go
func (rr *resultRing) add(r result) { rr.mu.Lock() defer rr.mu.Unlock() rr.values[rr.position] = r rr.position++ if rr.position == len(rr.values) { rr.position = 0 rr.wrapped = true } }
[ "func", "(", "rr", "*", "resultRing", ")", "add", "(", "r", "result", ")", "{", "rr", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "rr", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "rr", ".", "values", "[", "rr", ".", "position", "]", "=", "r", "\n", "rr", ".", "position", "++", "\n", "if", "rr", ".", "position", "==", "len", "(", "rr", ".", "values", ")", "{", "rr", ".", "position", "=", "0", "\n", "rr", ".", "wrapped", "=", "true", "\n", "}", "\n", "}" ]
// add inserts a new result into the ring buffer.
[ "add", "inserts", "a", "new", "result", "into", "the", "ring", "buffer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/result.go#L137-L147
train
vitessio/vitess
go/vt/throttler/replication_lag_cache.go
add
func (c *replicationLagCache) add(r replicationLagRecord) { if !r.Up { // Tablet is down. Do no longer track it. delete(c.entries, r.Key) delete(c.ignoredSlowReplicasInARow, r.Key) return } entry, ok := c.entries[r.Key] if !ok { entry = newReplicationLagHistory(c.historyCapacityPerReplica) c.entries[r.Key] = entry } entry.add(r) }
go
func (c *replicationLagCache) add(r replicationLagRecord) { if !r.Up { // Tablet is down. Do no longer track it. delete(c.entries, r.Key) delete(c.ignoredSlowReplicasInARow, r.Key) return } entry, ok := c.entries[r.Key] if !ok { entry = newReplicationLagHistory(c.historyCapacityPerReplica) c.entries[r.Key] = entry } entry.add(r) }
[ "func", "(", "c", "*", "replicationLagCache", ")", "add", "(", "r", "replicationLagRecord", ")", "{", "if", "!", "r", ".", "Up", "{", "// Tablet is down. Do no longer track it.", "delete", "(", "c", ".", "entries", ",", "r", ".", "Key", ")", "\n", "delete", "(", "c", ".", "ignoredSlowReplicasInARow", ",", "r", ".", "Key", ")", "\n", "return", "\n", "}", "\n\n", "entry", ",", "ok", ":=", "c", ".", "entries", "[", "r", ".", "Key", "]", "\n", "if", "!", "ok", "{", "entry", "=", "newReplicationLagHistory", "(", "c", ".", "historyCapacityPerReplica", ")", "\n", "c", ".", "entries", "[", "r", ".", "Key", "]", "=", "entry", "\n", "}", "\n\n", "entry", ".", "add", "(", "r", ")", "\n", "}" ]
// add inserts or updates "r" in the cache for the replica with the key "r.Key".
[ "add", "inserts", "or", "updates", "r", "in", "the", "cache", "for", "the", "replica", "with", "the", "key", "r", ".", "Key", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/replication_lag_cache.go#L62-L77
train
vitessio/vitess
go/vt/throttler/replication_lag_cache.go
sortByLag
func (c *replicationLagCache) sortByLag(ignoreNSlowestReplicas int, minimumReplicationLag int64) { // Reset the current list of ignored replicas. c.slowReplicas = make(map[string]bool) if ignoreNSlowestReplicas >= len(c.entries) { // Do not ignore slow replicas if all would get ignored. return } // Turn the map of replicas into a list and then sort it. var list byLagAndTabletUID i := 0 for _, v := range c.entries { record := v.latest() if int64(record.Stats.SecondsBehindMaster) >= minimumReplicationLag { list = append(list, record.TabletStats) i++ } } sort.Sort(list) // Now remember the N slowest replicas. for i := len(list) - 1; len(list) > 0 && i >= len(list)-ignoreNSlowestReplicas; i-- { c.slowReplicas[list[i].Key] = true } }
go
func (c *replicationLagCache) sortByLag(ignoreNSlowestReplicas int, minimumReplicationLag int64) { // Reset the current list of ignored replicas. c.slowReplicas = make(map[string]bool) if ignoreNSlowestReplicas >= len(c.entries) { // Do not ignore slow replicas if all would get ignored. return } // Turn the map of replicas into a list and then sort it. var list byLagAndTabletUID i := 0 for _, v := range c.entries { record := v.latest() if int64(record.Stats.SecondsBehindMaster) >= minimumReplicationLag { list = append(list, record.TabletStats) i++ } } sort.Sort(list) // Now remember the N slowest replicas. for i := len(list) - 1; len(list) > 0 && i >= len(list)-ignoreNSlowestReplicas; i-- { c.slowReplicas[list[i].Key] = true } }
[ "func", "(", "c", "*", "replicationLagCache", ")", "sortByLag", "(", "ignoreNSlowestReplicas", "int", ",", "minimumReplicationLag", "int64", ")", "{", "// Reset the current list of ignored replicas.", "c", ".", "slowReplicas", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "if", "ignoreNSlowestReplicas", ">=", "len", "(", "c", ".", "entries", ")", "{", "// Do not ignore slow replicas if all would get ignored.", "return", "\n", "}", "\n\n", "// Turn the map of replicas into a list and then sort it.", "var", "list", "byLagAndTabletUID", "\n", "i", ":=", "0", "\n", "for", "_", ",", "v", ":=", "range", "c", ".", "entries", "{", "record", ":=", "v", ".", "latest", "(", ")", "\n", "if", "int64", "(", "record", ".", "Stats", ".", "SecondsBehindMaster", ")", ">=", "minimumReplicationLag", "{", "list", "=", "append", "(", "list", ",", "record", ".", "TabletStats", ")", "\n", "i", "++", "\n", "}", "\n", "}", "\n", "sort", ".", "Sort", "(", "list", ")", "\n\n", "// Now remember the N slowest replicas.", "for", "i", ":=", "len", "(", "list", ")", "-", "1", ";", "len", "(", "list", ")", ">", "0", "&&", "i", ">=", "len", "(", "list", ")", "-", "ignoreNSlowestReplicas", ";", "i", "--", "{", "c", ".", "slowReplicas", "[", "list", "[", "i", "]", ".", "Key", "]", "=", "true", "\n", "}", "\n", "}" ]
// sortByLag sorts all replicas by their latest replication lag value and // tablet uid and updates the c.slowReplicas set.
[ "sortByLag", "sorts", "all", "replicas", "by", "their", "latest", "replication", "lag", "value", "and", "tablet", "uid", "and", "updates", "the", "c", ".", "slowReplicas", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/replication_lag_cache.go#L102-L127
train
vitessio/vitess
go/vt/throttler/replication_lag_cache.go
ignoreSlowReplica
func (c *replicationLagCache) ignoreSlowReplica(key string) bool { if len(c.slowReplicas) == 0 { // No slow replicas at all. return false } slow := c.slowReplicas[key] if slow { // Record that we're ignoring this replica. c.ignoredSlowReplicasInARow[key] = true if len(c.ignoredSlowReplicasInARow) == len(c.entries) { // All but this replica have been ignored in a row. Break this cycle now. slow = false } } if !slow { // Replica is not slow. if len(c.ignoredSlowReplicasInARow) != 0 { // Reset the set of replicas which have been slow in a row so far. c.ignoredSlowReplicasInARow = make(map[string]bool) } } return slow }
go
func (c *replicationLagCache) ignoreSlowReplica(key string) bool { if len(c.slowReplicas) == 0 { // No slow replicas at all. return false } slow := c.slowReplicas[key] if slow { // Record that we're ignoring this replica. c.ignoredSlowReplicasInARow[key] = true if len(c.ignoredSlowReplicasInARow) == len(c.entries) { // All but this replica have been ignored in a row. Break this cycle now. slow = false } } if !slow { // Replica is not slow. if len(c.ignoredSlowReplicasInARow) != 0 { // Reset the set of replicas which have been slow in a row so far. c.ignoredSlowReplicasInARow = make(map[string]bool) } } return slow }
[ "func", "(", "c", "*", "replicationLagCache", ")", "ignoreSlowReplica", "(", "key", "string", ")", "bool", "{", "if", "len", "(", "c", ".", "slowReplicas", ")", "==", "0", "{", "// No slow replicas at all.", "return", "false", "\n", "}", "\n\n", "slow", ":=", "c", ".", "slowReplicas", "[", "key", "]", "\n", "if", "slow", "{", "// Record that we're ignoring this replica.", "c", ".", "ignoredSlowReplicasInARow", "[", "key", "]", "=", "true", "\n\n", "if", "len", "(", "c", ".", "ignoredSlowReplicasInARow", ")", "==", "len", "(", "c", ".", "entries", ")", "{", "// All but this replica have been ignored in a row. Break this cycle now.", "slow", "=", "false", "\n", "}", "\n", "}", "\n\n", "if", "!", "slow", "{", "// Replica is not slow.", "if", "len", "(", "c", ".", "ignoredSlowReplicasInARow", ")", "!=", "0", "{", "// Reset the set of replicas which have been slow in a row so far.", "c", ".", "ignoredSlowReplicasInARow", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "}", "\n", "}", "\n", "return", "slow", "\n", "}" ]
// ignoreSlowReplica returns true if the MaxReplicationLagModule should ignore // this slow replica. // "key" refers to ReplicationLagRecord.TabletStats.Key.
[ "ignoreSlowReplica", "returns", "true", "if", "the", "MaxReplicationLagModule", "should", "ignore", "this", "slow", "replica", ".", "key", "refers", "to", "ReplicationLagRecord", ".", "TabletStats", ".", "Key", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/replication_lag_cache.go#L144-L169
train
vitessio/vitess
go/vt/tableacl/simpleacl/simpleacl.go
IsMember
func (sacl SimpleACL) IsMember(principal *querypb.VTGateCallerID) bool { if sacl[principal.Username] { return true } for _, grp := range principal.Groups { if sacl[grp] { return true } } return false }
go
func (sacl SimpleACL) IsMember(principal *querypb.VTGateCallerID) bool { if sacl[principal.Username] { return true } for _, grp := range principal.Groups { if sacl[grp] { return true } } return false }
[ "func", "(", "sacl", "SimpleACL", ")", "IsMember", "(", "principal", "*", "querypb", ".", "VTGateCallerID", ")", "bool", "{", "if", "sacl", "[", "principal", ".", "Username", "]", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "grp", ":=", "range", "principal", ".", "Groups", "{", "if", "sacl", "[", "grp", "]", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsMember checks the membership of a principal in this ACL
[ "IsMember", "checks", "the", "membership", "of", "a", "principal", "in", "this", "ACL" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/tableacl/simpleacl/simpleacl.go#L28-L38
train
vitessio/vitess
go/vt/tableacl/simpleacl/simpleacl.go
New
func (factory *Factory) New(entries []string) (acl.ACL, error) { acl := SimpleACL(map[string]bool{}) for _, e := range entries { acl[e] = true } return acl, nil }
go
func (factory *Factory) New(entries []string) (acl.ACL, error) { acl := SimpleACL(map[string]bool{}) for _, e := range entries { acl[e] = true } return acl, nil }
[ "func", "(", "factory", "*", "Factory", ")", "New", "(", "entries", "[", "]", "string", ")", "(", "acl", ".", "ACL", ",", "error", ")", "{", "acl", ":=", "SimpleACL", "(", "map", "[", "string", "]", "bool", "{", "}", ")", "\n", "for", "_", ",", "e", ":=", "range", "entries", "{", "acl", "[", "e", "]", "=", "true", "\n", "}", "\n", "return", "acl", ",", "nil", "\n", "}" ]
// New creates a new ACL instance.
[ "New", "creates", "a", "new", "ACL", "instance", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/tableacl/simpleacl/simpleacl.go#L44-L50
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
Done
func (ta *Table) Done() { if !ta.HasPrimary() { return } pkIndex := ta.Indexes[0] ta.PKColumns = make([]int, len(pkIndex.Columns)) for i, pkCol := range pkIndex.Columns { ta.PKColumns[i] = ta.FindColumn(pkCol) } }
go
func (ta *Table) Done() { if !ta.HasPrimary() { return } pkIndex := ta.Indexes[0] ta.PKColumns = make([]int, len(pkIndex.Columns)) for i, pkCol := range pkIndex.Columns { ta.PKColumns[i] = ta.FindColumn(pkCol) } }
[ "func", "(", "ta", "*", "Table", ")", "Done", "(", ")", "{", "if", "!", "ta", ".", "HasPrimary", "(", ")", "{", "return", "\n", "}", "\n", "pkIndex", ":=", "ta", ".", "Indexes", "[", "0", "]", "\n", "ta", ".", "PKColumns", "=", "make", "(", "[", "]", "int", ",", "len", "(", "pkIndex", ".", "Columns", ")", ")", "\n", "for", "i", ",", "pkCol", ":=", "range", "pkIndex", ".", "Columns", "{", "ta", ".", "PKColumns", "[", "i", "]", "=", "ta", ".", "FindColumn", "(", "pkCol", ")", "\n", "}", "\n", "}" ]
// Done must be called after columns and indexes are added to // the table. It will build additional metadata like PKColumns.
[ "Done", "must", "be", "called", "after", "columns", "and", "indexes", "are", "added", "to", "the", "table", ".", "It", "will", "build", "additional", "metadata", "like", "PKColumns", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L134-L143
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
AddColumn
func (ta *Table) AddColumn(name string, columnType querypb.Type, defval sqltypes.Value, extra string) { index := len(ta.Columns) ta.Columns = append(ta.Columns, TableColumn{Name: sqlparser.NewColIdent(name)}) ta.Columns[index].Type = columnType if extra == "auto_increment" { ta.Columns[index].IsAuto = true // Ignore default value, if any return } if defval.IsNull() { return } // Schema values are trusted. ta.Columns[index].Default = sqltypes.MakeTrusted(ta.Columns[index].Type, defval.Raw()) }
go
func (ta *Table) AddColumn(name string, columnType querypb.Type, defval sqltypes.Value, extra string) { index := len(ta.Columns) ta.Columns = append(ta.Columns, TableColumn{Name: sqlparser.NewColIdent(name)}) ta.Columns[index].Type = columnType if extra == "auto_increment" { ta.Columns[index].IsAuto = true // Ignore default value, if any return } if defval.IsNull() { return } // Schema values are trusted. ta.Columns[index].Default = sqltypes.MakeTrusted(ta.Columns[index].Type, defval.Raw()) }
[ "func", "(", "ta", "*", "Table", ")", "AddColumn", "(", "name", "string", ",", "columnType", "querypb", ".", "Type", ",", "defval", "sqltypes", ".", "Value", ",", "extra", "string", ")", "{", "index", ":=", "len", "(", "ta", ".", "Columns", ")", "\n", "ta", ".", "Columns", "=", "append", "(", "ta", ".", "Columns", ",", "TableColumn", "{", "Name", ":", "sqlparser", ".", "NewColIdent", "(", "name", ")", "}", ")", "\n", "ta", ".", "Columns", "[", "index", "]", ".", "Type", "=", "columnType", "\n", "if", "extra", "==", "\"", "\"", "{", "ta", ".", "Columns", "[", "index", "]", ".", "IsAuto", "=", "true", "\n", "// Ignore default value, if any", "return", "\n", "}", "\n", "if", "defval", ".", "IsNull", "(", ")", "{", "return", "\n", "}", "\n", "// Schema values are trusted.", "ta", ".", "Columns", "[", "index", "]", ".", "Default", "=", "sqltypes", ".", "MakeTrusted", "(", "ta", ".", "Columns", "[", "index", "]", ".", "Type", ",", "defval", ".", "Raw", "(", ")", ")", "\n", "}" ]
// AddColumn adds a column to the Table.
[ "AddColumn", "adds", "a", "column", "to", "the", "Table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L146-L160
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
FindColumn
func (ta *Table) FindColumn(name sqlparser.ColIdent) int { for i, col := range ta.Columns { if col.Name.Equal(name) { return i } } return -1 }
go
func (ta *Table) FindColumn(name sqlparser.ColIdent) int { for i, col := range ta.Columns { if col.Name.Equal(name) { return i } } return -1 }
[ "func", "(", "ta", "*", "Table", ")", "FindColumn", "(", "name", "sqlparser", ".", "ColIdent", ")", "int", "{", "for", "i", ",", "col", ":=", "range", "ta", ".", "Columns", "{", "if", "col", ".", "Name", ".", "Equal", "(", "name", ")", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// FindColumn finds a column in the table. It returns the index if found. // Otherwise, it returns -1.
[ "FindColumn", "finds", "a", "column", "in", "the", "table", ".", "It", "returns", "the", "index", "if", "found", ".", "Otherwise", "it", "returns", "-", "1", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L164-L171
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
GetPKColumn
func (ta *Table) GetPKColumn(index int) *TableColumn { return &ta.Columns[ta.PKColumns[index]] }
go
func (ta *Table) GetPKColumn(index int) *TableColumn { return &ta.Columns[ta.PKColumns[index]] }
[ "func", "(", "ta", "*", "Table", ")", "GetPKColumn", "(", "index", "int", ")", "*", "TableColumn", "{", "return", "&", "ta", ".", "Columns", "[", "ta", ".", "PKColumns", "[", "index", "]", "]", "\n", "}" ]
// GetPKColumn returns the pk column specified by the index.
[ "GetPKColumn", "returns", "the", "pk", "column", "specified", "by", "the", "index", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L174-L176
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
AddIndex
func (ta *Table) AddIndex(name string, unique bool) (index *Index) { index = NewIndex(name, unique) ta.Indexes = append(ta.Indexes, index) return index }
go
func (ta *Table) AddIndex(name string, unique bool) (index *Index) { index = NewIndex(name, unique) ta.Indexes = append(ta.Indexes, index) return index }
[ "func", "(", "ta", "*", "Table", ")", "AddIndex", "(", "name", "string", ",", "unique", "bool", ")", "(", "index", "*", "Index", ")", "{", "index", "=", "NewIndex", "(", "name", ",", "unique", ")", "\n", "ta", ".", "Indexes", "=", "append", "(", "ta", ".", "Indexes", ",", "index", ")", "\n", "return", "index", "\n", "}" ]
// AddIndex adds an index to the table.
[ "AddIndex", "adds", "an", "index", "to", "the", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L179-L183
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
SetMysqlStats
func (ta *Table) SetMysqlStats(tr, dl, il, df, mdl sqltypes.Value) { v, _ := sqltypes.ToInt64(tr) ta.TableRows.Set(v) v, _ = sqltypes.ToInt64(dl) ta.DataLength.Set(v) v, _ = sqltypes.ToInt64(il) ta.IndexLength.Set(v) v, _ = sqltypes.ToInt64(df) ta.DataFree.Set(v) v, _ = sqltypes.ToInt64(mdl) ta.MaxDataLength.Set(v) }
go
func (ta *Table) SetMysqlStats(tr, dl, il, df, mdl sqltypes.Value) { v, _ := sqltypes.ToInt64(tr) ta.TableRows.Set(v) v, _ = sqltypes.ToInt64(dl) ta.DataLength.Set(v) v, _ = sqltypes.ToInt64(il) ta.IndexLength.Set(v) v, _ = sqltypes.ToInt64(df) ta.DataFree.Set(v) v, _ = sqltypes.ToInt64(mdl) ta.MaxDataLength.Set(v) }
[ "func", "(", "ta", "*", "Table", ")", "SetMysqlStats", "(", "tr", ",", "dl", ",", "il", ",", "df", ",", "mdl", "sqltypes", ".", "Value", ")", "{", "v", ",", "_", ":=", "sqltypes", ".", "ToInt64", "(", "tr", ")", "\n", "ta", ".", "TableRows", ".", "Set", "(", "v", ")", "\n", "v", ",", "_", "=", "sqltypes", ".", "ToInt64", "(", "dl", ")", "\n", "ta", ".", "DataLength", ".", "Set", "(", "v", ")", "\n", "v", ",", "_", "=", "sqltypes", ".", "ToInt64", "(", "il", ")", "\n", "ta", ".", "IndexLength", ".", "Set", "(", "v", ")", "\n", "v", ",", "_", "=", "sqltypes", ".", "ToInt64", "(", "df", ")", "\n", "ta", ".", "DataFree", ".", "Set", "(", "v", ")", "\n", "v", ",", "_", "=", "sqltypes", ".", "ToInt64", "(", "mdl", ")", "\n", "ta", ".", "MaxDataLength", ".", "Set", "(", "v", ")", "\n", "}" ]
// SetMysqlStats receives the values found in the mysql information_schema.tables table
[ "SetMysqlStats", "receives", "the", "values", "found", "in", "the", "mysql", "information_schema", ".", "tables", "table" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L186-L197
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
HasPrimary
func (ta *Table) HasPrimary() bool { return len(ta.Indexes) != 0 && ta.Indexes[0].Name.EqualString("primary") }
go
func (ta *Table) HasPrimary() bool { return len(ta.Indexes) != 0 && ta.Indexes[0].Name.EqualString("primary") }
[ "func", "(", "ta", "*", "Table", ")", "HasPrimary", "(", ")", "bool", "{", "return", "len", "(", "ta", ".", "Indexes", ")", "!=", "0", "&&", "ta", ".", "Indexes", "[", "0", "]", ".", "Name", ".", "EqualString", "(", "\"", "\"", ")", "\n", "}" ]
// HasPrimary returns true if the table has a primary key.
[ "HasPrimary", "returns", "true", "if", "the", "table", "has", "a", "primary", "key", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L200-L202
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
UniqueIndexes
func (ta *Table) UniqueIndexes() int { unique := 0 for _, idx := range ta.Indexes { if idx.Unique { unique++ } } return unique }
go
func (ta *Table) UniqueIndexes() int { unique := 0 for _, idx := range ta.Indexes { if idx.Unique { unique++ } } return unique }
[ "func", "(", "ta", "*", "Table", ")", "UniqueIndexes", "(", ")", "int", "{", "unique", ":=", "0", "\n", "for", "_", ",", "idx", ":=", "range", "ta", ".", "Indexes", "{", "if", "idx", ".", "Unique", "{", "unique", "++", "\n", "}", "\n", "}", "\n", "return", "unique", "\n", "}" ]
// UniqueIndexes returns the number of unique indexes on the table
[ "UniqueIndexes", "returns", "the", "number", "of", "unique", "indexes", "on", "the", "table" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L205-L213
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
NewIndex
func NewIndex(name string, unique bool) *Index { return &Index{Name: sqlparser.NewColIdent(name), Unique: unique} }
go
func NewIndex(name string, unique bool) *Index { return &Index{Name: sqlparser.NewColIdent(name), Unique: unique} }
[ "func", "NewIndex", "(", "name", "string", ",", "unique", "bool", ")", "*", "Index", "{", "return", "&", "Index", "{", "Name", ":", "sqlparser", ".", "NewColIdent", "(", "name", ")", ",", "Unique", ":", "unique", "}", "\n", "}" ]
// NewIndex creates a new Index.
[ "NewIndex", "creates", "a", "new", "Index", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L227-L229
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
AddColumn
func (idx *Index) AddColumn(name string, cardinality uint64) { idx.Columns = append(idx.Columns, sqlparser.NewColIdent(name)) if cardinality == 0 { cardinality = uint64(len(idx.Cardinality) + 1) } idx.Cardinality = append(idx.Cardinality, cardinality) }
go
func (idx *Index) AddColumn(name string, cardinality uint64) { idx.Columns = append(idx.Columns, sqlparser.NewColIdent(name)) if cardinality == 0 { cardinality = uint64(len(idx.Cardinality) + 1) } idx.Cardinality = append(idx.Cardinality, cardinality) }
[ "func", "(", "idx", "*", "Index", ")", "AddColumn", "(", "name", "string", ",", "cardinality", "uint64", ")", "{", "idx", ".", "Columns", "=", "append", "(", "idx", ".", "Columns", ",", "sqlparser", ".", "NewColIdent", "(", "name", ")", ")", "\n", "if", "cardinality", "==", "0", "{", "cardinality", "=", "uint64", "(", "len", "(", "idx", ".", "Cardinality", ")", "+", "1", ")", "\n", "}", "\n", "idx", ".", "Cardinality", "=", "append", "(", "idx", ".", "Cardinality", ",", "cardinality", ")", "\n", "}" ]
// AddColumn adds a column to the index.
[ "AddColumn", "adds", "a", "column", "to", "the", "index", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L232-L238
train
vitessio/vitess
go/vt/vttablet/tabletserver/schema/schema.go
FindColumn
func (idx *Index) FindColumn(name sqlparser.ColIdent) int { for i, colName := range idx.Columns { if colName.Equal(name) { return i } } return -1 }
go
func (idx *Index) FindColumn(name sqlparser.ColIdent) int { for i, colName := range idx.Columns { if colName.Equal(name) { return i } } return -1 }
[ "func", "(", "idx", "*", "Index", ")", "FindColumn", "(", "name", "sqlparser", ".", "ColIdent", ")", "int", "{", "for", "i", ",", "colName", ":=", "range", "idx", ".", "Columns", "{", "if", "colName", ".", "Equal", "(", "name", ")", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// FindColumn finds a column in the index. It returns the index if found. // Otherwise, it returns -1.
[ "FindColumn", "finds", "a", "column", "in", "the", "index", ".", "It", "returns", "the", "index", "if", "found", ".", "Otherwise", "it", "returns", "-", "1", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/schema/schema.go#L242-L249
train
vitessio/vitess
go/vt/vttablet/tabletmanager/heartbeat_reporter.go
registerHeartbeatReporter
func registerHeartbeatReporter(controller tabletserver.Controller) { if !tabletenv.Config.HeartbeatEnable { return } reporter := &Reporter{controller} health.DefaultAggregator.Register("heartbeat_reporter", reporter) }
go
func registerHeartbeatReporter(controller tabletserver.Controller) { if !tabletenv.Config.HeartbeatEnable { return } reporter := &Reporter{controller} health.DefaultAggregator.Register("heartbeat_reporter", reporter) }
[ "func", "registerHeartbeatReporter", "(", "controller", "tabletserver", ".", "Controller", ")", "{", "if", "!", "tabletenv", ".", "Config", ".", "HeartbeatEnable", "{", "return", "\n", "}", "\n\n", "reporter", ":=", "&", "Reporter", "{", "controller", "}", "\n", "health", ".", "DefaultAggregator", ".", "Register", "(", "\"", "\"", ",", "reporter", ")", "\n", "}" ]
// RegisterReporter registers the heartbeat reader as a healthcheck reporter so that its // measurements will be picked up in healthchecks.
[ "RegisterReporter", "registers", "the", "heartbeat", "reader", "as", "a", "healthcheck", "reporter", "so", "that", "its", "measurements", "will", "be", "picked", "up", "in", "healthchecks", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/heartbeat_reporter.go#L36-L43
train
vitessio/vitess
go/vt/vttablet/tabletmanager/heartbeat_reporter.go
Report
func (r *Reporter) Report(isSlaveType, shouldQueryServiceBeRunning bool) (time.Duration, error) { if !isSlaveType { return 0, nil } return r.controller.HeartbeatLag() }
go
func (r *Reporter) Report(isSlaveType, shouldQueryServiceBeRunning bool) (time.Duration, error) { if !isSlaveType { return 0, nil } return r.controller.HeartbeatLag() }
[ "func", "(", "r", "*", "Reporter", ")", "Report", "(", "isSlaveType", ",", "shouldQueryServiceBeRunning", "bool", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "!", "isSlaveType", "{", "return", "0", ",", "nil", "\n", "}", "\n", "return", "r", ".", "controller", ".", "HeartbeatLag", "(", ")", "\n", "}" ]
// Report is part of the health.Reporter interface. It returns the last reported value // written by the watchHeartbeat goroutine. If we're the master, it just returns 0.
[ "Report", "is", "part", "of", "the", "health", ".", "Reporter", "interface", ".", "It", "returns", "the", "last", "reported", "value", "written", "by", "the", "watchHeartbeat", "goroutine", ".", "If", "we", "re", "the", "master", "it", "just", "returns", "0", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/heartbeat_reporter.go#L52-L57
train
vitessio/vitess
go/vt/wrangler/keyspace.go
SetKeyspaceShardingInfo
func (wr *Wrangler) SetKeyspaceShardingInfo(ctx context.Context, keyspace, shardingColumnName string, shardingColumnType topodatapb.KeyspaceIdType, force bool) (err error) { // Lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "SetKeyspaceShardingInfo") if lockErr != nil { return lockErr } defer unlock(&err) // and change it ki, err := wr.ts.GetKeyspace(ctx, keyspace) if err != nil { return err } if ki.ShardingColumnName != "" && ki.ShardingColumnName != shardingColumnName { if force { wr.Logger().Warningf("Forcing keyspace ShardingColumnName change from %v to %v", ki.ShardingColumnName, shardingColumnName) } else { return fmt.Errorf("cannot change ShardingColumnName from %v to %v (use -force to override)", ki.ShardingColumnName, shardingColumnName) } } if ki.ShardingColumnType != topodatapb.KeyspaceIdType_UNSET && ki.ShardingColumnType != shardingColumnType { if force { wr.Logger().Warningf("Forcing keyspace ShardingColumnType change from %v to %v", ki.ShardingColumnType, shardingColumnType) } else { return fmt.Errorf("cannot change ShardingColumnType from %v to %v (use -force to override)", ki.ShardingColumnType, shardingColumnType) } } ki.ShardingColumnName = shardingColumnName ki.ShardingColumnType = shardingColumnType return wr.ts.UpdateKeyspace(ctx, ki) }
go
func (wr *Wrangler) SetKeyspaceShardingInfo(ctx context.Context, keyspace, shardingColumnName string, shardingColumnType topodatapb.KeyspaceIdType, force bool) (err error) { // Lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "SetKeyspaceShardingInfo") if lockErr != nil { return lockErr } defer unlock(&err) // and change it ki, err := wr.ts.GetKeyspace(ctx, keyspace) if err != nil { return err } if ki.ShardingColumnName != "" && ki.ShardingColumnName != shardingColumnName { if force { wr.Logger().Warningf("Forcing keyspace ShardingColumnName change from %v to %v", ki.ShardingColumnName, shardingColumnName) } else { return fmt.Errorf("cannot change ShardingColumnName from %v to %v (use -force to override)", ki.ShardingColumnName, shardingColumnName) } } if ki.ShardingColumnType != topodatapb.KeyspaceIdType_UNSET && ki.ShardingColumnType != shardingColumnType { if force { wr.Logger().Warningf("Forcing keyspace ShardingColumnType change from %v to %v", ki.ShardingColumnType, shardingColumnType) } else { return fmt.Errorf("cannot change ShardingColumnType from %v to %v (use -force to override)", ki.ShardingColumnType, shardingColumnType) } } ki.ShardingColumnName = shardingColumnName ki.ShardingColumnType = shardingColumnType return wr.ts.UpdateKeyspace(ctx, ki) }
[ "func", "(", "wr", "*", "Wrangler", ")", "SetKeyspaceShardingInfo", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shardingColumnName", "string", ",", "shardingColumnType", "topodatapb", ".", "KeyspaceIdType", ",", "force", "bool", ")", "(", "err", "error", ")", "{", "// Lock the keyspace", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "\"", "\"", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// and change it", "ki", ",", "err", ":=", "wr", ".", "ts", ".", "GetKeyspace", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "ki", ".", "ShardingColumnName", "!=", "\"", "\"", "&&", "ki", ".", "ShardingColumnName", "!=", "shardingColumnName", "{", "if", "force", "{", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "ki", ".", "ShardingColumnName", ",", "shardingColumnName", ")", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ki", ".", "ShardingColumnName", ",", "shardingColumnName", ")", "\n", "}", "\n", "}", "\n\n", "if", "ki", ".", "ShardingColumnType", "!=", "topodatapb", ".", "KeyspaceIdType_UNSET", "&&", "ki", ".", "ShardingColumnType", "!=", "shardingColumnType", "{", "if", "force", "{", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "ki", ".", "ShardingColumnType", ",", "shardingColumnType", ")", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ki", ".", "ShardingColumnType", ",", "shardingColumnType", ")", "\n", "}", "\n", "}", "\n\n", "ki", ".", "ShardingColumnName", "=", "shardingColumnName", "\n", "ki", ".", "ShardingColumnType", "=", "shardingColumnType", "\n", "return", "wr", ".", "ts", ".", "UpdateKeyspace", "(", "ctx", ",", "ki", ")", "\n", "}" ]
// keyspace related methods for Wrangler // SetKeyspaceShardingInfo locks a keyspace and sets its ShardingColumnName // and ShardingColumnType
[ "keyspace", "related", "methods", "for", "Wrangler", "SetKeyspaceShardingInfo", "locks", "a", "keyspace", "and", "sets", "its", "ShardingColumnName", "and", "ShardingColumnType" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L59-L92
train
vitessio/vitess
go/vt/wrangler/keyspace.go
SplitClone
func (wr *Wrangler) SplitClone(ctx context.Context, keyspace string, from, to []string) error { var fromShards, toShards []*topo.ShardInfo for _, shard := range from { si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return vterrors.Wrapf(err, "GetShard(%s) failed", shard) } fromShards = append(fromShards, si) } for _, shard := range to { si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return vterrors.Wrapf(err, "GetShard(%s) failed", shard) } toShards = append(toShards, si) } // TODO(sougou): validate from and to shards. for _, dest := range toShards { master, err := wr.ts.GetTablet(ctx, dest.MasterAlias) if err != nil { return vterrors.Wrapf(err, "GetTablet(%v) failed", dest.MasterAlias) } var ids []uint64 for _, source := range fromShards { filter := &binlogdatapb.Filter{ Rules: []*binlogdatapb.Rule{{ Match: "/.*", Filter: key.KeyRangeString(dest.KeyRange), }}, } bls := &binlogdatapb.BinlogSource{ Keyspace: keyspace, Shard: source.ShardName(), Filter: filter, } cmd := binlogplayer.CreateVReplicationState("VSplitClone", bls, "", binlogplayer.BlpStopped, master.DbName()) qr, err := wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd) if err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } if err := wr.SourceShardAdd(ctx, keyspace, dest.ShardName(), uint32(qr.InsertId), keyspace, source.ShardName(), source.Shard.KeyRange, nil); err != nil { return vterrors.Wrapf(err, "SourceShardAdd(%s, %s) failed", dest.ShardName(), source.ShardName()) } ids = append(ids, qr.InsertId) } // Start vreplication only if all metadata was successfully created. for _, id := range ids { cmd := fmt.Sprintf("update _vt.vreplication set state='%s' where id=%d", binlogplayer.VReplicationInit, id) if _, err = wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd); err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } } } return wr.refreshMasters(ctx, toShards) }
go
func (wr *Wrangler) SplitClone(ctx context.Context, keyspace string, from, to []string) error { var fromShards, toShards []*topo.ShardInfo for _, shard := range from { si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return vterrors.Wrapf(err, "GetShard(%s) failed", shard) } fromShards = append(fromShards, si) } for _, shard := range to { si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return vterrors.Wrapf(err, "GetShard(%s) failed", shard) } toShards = append(toShards, si) } // TODO(sougou): validate from and to shards. for _, dest := range toShards { master, err := wr.ts.GetTablet(ctx, dest.MasterAlias) if err != nil { return vterrors.Wrapf(err, "GetTablet(%v) failed", dest.MasterAlias) } var ids []uint64 for _, source := range fromShards { filter := &binlogdatapb.Filter{ Rules: []*binlogdatapb.Rule{{ Match: "/.*", Filter: key.KeyRangeString(dest.KeyRange), }}, } bls := &binlogdatapb.BinlogSource{ Keyspace: keyspace, Shard: source.ShardName(), Filter: filter, } cmd := binlogplayer.CreateVReplicationState("VSplitClone", bls, "", binlogplayer.BlpStopped, master.DbName()) qr, err := wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd) if err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } if err := wr.SourceShardAdd(ctx, keyspace, dest.ShardName(), uint32(qr.InsertId), keyspace, source.ShardName(), source.Shard.KeyRange, nil); err != nil { return vterrors.Wrapf(err, "SourceShardAdd(%s, %s) failed", dest.ShardName(), source.ShardName()) } ids = append(ids, qr.InsertId) } // Start vreplication only if all metadata was successfully created. for _, id := range ids { cmd := fmt.Sprintf("update _vt.vreplication set state='%s' where id=%d", binlogplayer.VReplicationInit, id) if _, err = wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd); err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } } } return wr.refreshMasters(ctx, toShards) }
[ "func", "(", "wr", "*", "Wrangler", ")", "SplitClone", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "from", ",", "to", "[", "]", "string", ")", "error", "{", "var", "fromShards", ",", "toShards", "[", "]", "*", "topo", ".", "ShardInfo", "\n", "for", "_", ",", "shard", ":=", "range", "from", "{", "si", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "shard", ")", "\n", "}", "\n", "fromShards", "=", "append", "(", "fromShards", ",", "si", ")", "\n", "}", "\n", "for", "_", ",", "shard", ":=", "range", "to", "{", "si", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "shard", ")", "\n", "}", "\n", "toShards", "=", "append", "(", "toShards", ",", "si", ")", "\n", "}", "\n", "// TODO(sougou): validate from and to shards.", "for", "_", ",", "dest", ":=", "range", "toShards", "{", "master", ",", "err", ":=", "wr", ".", "ts", ".", "GetTablet", "(", "ctx", ",", "dest", ".", "MasterAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "MasterAlias", ")", "\n", "}", "\n", "var", "ids", "[", "]", "uint64", "\n", "for", "_", ",", "source", ":=", "range", "fromShards", "{", "filter", ":=", "&", "binlogdatapb", ".", "Filter", "{", "Rules", ":", "[", "]", "*", "binlogdatapb", ".", "Rule", "{", "{", "Match", ":", "\"", "\"", ",", "Filter", ":", "key", ".", "KeyRangeString", "(", "dest", ".", "KeyRange", ")", ",", "}", "}", ",", "}", "\n", "bls", ":=", "&", "binlogdatapb", ".", "BinlogSource", "{", "Keyspace", ":", "keyspace", ",", "Shard", ":", "source", ".", "ShardName", "(", ")", ",", "Filter", ":", "filter", ",", "}", "\n", "cmd", ":=", "binlogplayer", ".", "CreateVReplicationState", "(", "\"", "\"", ",", "bls", ",", "\"", "\"", ",", "binlogplayer", ".", "BlpStopped", ",", "master", ".", "DbName", "(", ")", ")", "\n", "qr", ",", "err", ":=", "wr", ".", "TabletManagerClient", "(", ")", ".", "VReplicationExec", "(", "ctx", ",", "master", ".", "Tablet", ",", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "MasterAlias", ",", "cmd", ")", "\n", "}", "\n", "if", "err", ":=", "wr", ".", "SourceShardAdd", "(", "ctx", ",", "keyspace", ",", "dest", ".", "ShardName", "(", ")", ",", "uint32", "(", "qr", ".", "InsertId", ")", ",", "keyspace", ",", "source", ".", "ShardName", "(", ")", ",", "source", ".", "Shard", ".", "KeyRange", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "ShardName", "(", ")", ",", "source", ".", "ShardName", "(", ")", ")", "\n", "}", "\n", "ids", "=", "append", "(", "ids", ",", "qr", ".", "InsertId", ")", "\n", "}", "\n", "// Start vreplication only if all metadata was successfully created.", "for", "_", ",", "id", ":=", "range", "ids", "{", "cmd", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "binlogplayer", ".", "VReplicationInit", ",", "id", ")", "\n", "if", "_", ",", "err", "=", "wr", ".", "TabletManagerClient", "(", ")", ".", "VReplicationExec", "(", "ctx", ",", "master", ".", "Tablet", ",", "cmd", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "MasterAlias", ",", "cmd", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "wr", ".", "refreshMasters", "(", "ctx", ",", "toShards", ")", "\n", "}" ]
// SplitClone initiates a SplitClone workflow.
[ "SplitClone", "initiates", "a", "SplitClone", "workflow", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L95-L150
train
vitessio/vitess
go/vt/wrangler/keyspace.go
VerticalSplitClone
func (wr *Wrangler) VerticalSplitClone(ctx context.Context, fromKeyspace, toKeyspace string, tables []string) error { source, err := wr.ts.GetOnlyShard(ctx, fromKeyspace) if err != nil { return vterrors.Wrapf(err, "GetOnlyShard(%s) failed", fromKeyspace) } dest, err := wr.ts.GetOnlyShard(ctx, toKeyspace) if err != nil { return vterrors.Wrapf(err, "GetOnlyShard(%s) failed", toKeyspace) } // TODO(sougou): validate from and to shards. master, err := wr.ts.GetTablet(ctx, dest.MasterAlias) if err != nil { return vterrors.Wrapf(err, "GetTablet(%v) failed", dest.MasterAlias) } filter := &binlogdatapb.Filter{} for _, table := range tables { filter.Rules = append(filter.Rules, &binlogdatapb.Rule{ Match: table, }) } bls := &binlogdatapb.BinlogSource{ Keyspace: fromKeyspace, Shard: source.ShardName(), Filter: filter, } cmd := binlogplayer.CreateVReplicationState("VSplitClone", bls, "", binlogplayer.BlpStopped, master.DbName()) qr, err := wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd) if err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } if err := wr.SourceShardAdd(ctx, toKeyspace, dest.ShardName(), uint32(qr.InsertId), fromKeyspace, source.ShardName(), nil, tables); err != nil { return vterrors.Wrapf(err, "SourceShardAdd(%s, %s) failed", dest.ShardName(), source.ShardName()) } // Start vreplication only if metadata was successfully created. cmd = fmt.Sprintf("update _vt.vreplication set state='%s' where id=%d", binlogplayer.VReplicationInit, qr.InsertId) if _, err = wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd); err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } return wr.refreshMasters(ctx, []*topo.ShardInfo{dest}) }
go
func (wr *Wrangler) VerticalSplitClone(ctx context.Context, fromKeyspace, toKeyspace string, tables []string) error { source, err := wr.ts.GetOnlyShard(ctx, fromKeyspace) if err != nil { return vterrors.Wrapf(err, "GetOnlyShard(%s) failed", fromKeyspace) } dest, err := wr.ts.GetOnlyShard(ctx, toKeyspace) if err != nil { return vterrors.Wrapf(err, "GetOnlyShard(%s) failed", toKeyspace) } // TODO(sougou): validate from and to shards. master, err := wr.ts.GetTablet(ctx, dest.MasterAlias) if err != nil { return vterrors.Wrapf(err, "GetTablet(%v) failed", dest.MasterAlias) } filter := &binlogdatapb.Filter{} for _, table := range tables { filter.Rules = append(filter.Rules, &binlogdatapb.Rule{ Match: table, }) } bls := &binlogdatapb.BinlogSource{ Keyspace: fromKeyspace, Shard: source.ShardName(), Filter: filter, } cmd := binlogplayer.CreateVReplicationState("VSplitClone", bls, "", binlogplayer.BlpStopped, master.DbName()) qr, err := wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd) if err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } if err := wr.SourceShardAdd(ctx, toKeyspace, dest.ShardName(), uint32(qr.InsertId), fromKeyspace, source.ShardName(), nil, tables); err != nil { return vterrors.Wrapf(err, "SourceShardAdd(%s, %s) failed", dest.ShardName(), source.ShardName()) } // Start vreplication only if metadata was successfully created. cmd = fmt.Sprintf("update _vt.vreplication set state='%s' where id=%d", binlogplayer.VReplicationInit, qr.InsertId) if _, err = wr.TabletManagerClient().VReplicationExec(ctx, master.Tablet, cmd); err != nil { return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.MasterAlias, cmd) } return wr.refreshMasters(ctx, []*topo.ShardInfo{dest}) }
[ "func", "(", "wr", "*", "Wrangler", ")", "VerticalSplitClone", "(", "ctx", "context", ".", "Context", ",", "fromKeyspace", ",", "toKeyspace", "string", ",", "tables", "[", "]", "string", ")", "error", "{", "source", ",", "err", ":=", "wr", ".", "ts", ".", "GetOnlyShard", "(", "ctx", ",", "fromKeyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "fromKeyspace", ")", "\n", "}", "\n", "dest", ",", "err", ":=", "wr", ".", "ts", ".", "GetOnlyShard", "(", "ctx", ",", "toKeyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "toKeyspace", ")", "\n", "}", "\n", "// TODO(sougou): validate from and to shards.", "master", ",", "err", ":=", "wr", ".", "ts", ".", "GetTablet", "(", "ctx", ",", "dest", ".", "MasterAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "MasterAlias", ")", "\n", "}", "\n", "filter", ":=", "&", "binlogdatapb", ".", "Filter", "{", "}", "\n", "for", "_", ",", "table", ":=", "range", "tables", "{", "filter", ".", "Rules", "=", "append", "(", "filter", ".", "Rules", ",", "&", "binlogdatapb", ".", "Rule", "{", "Match", ":", "table", ",", "}", ")", "\n", "}", "\n", "bls", ":=", "&", "binlogdatapb", ".", "BinlogSource", "{", "Keyspace", ":", "fromKeyspace", ",", "Shard", ":", "source", ".", "ShardName", "(", ")", ",", "Filter", ":", "filter", ",", "}", "\n", "cmd", ":=", "binlogplayer", ".", "CreateVReplicationState", "(", "\"", "\"", ",", "bls", ",", "\"", "\"", ",", "binlogplayer", ".", "BlpStopped", ",", "master", ".", "DbName", "(", ")", ")", "\n", "qr", ",", "err", ":=", "wr", ".", "TabletManagerClient", "(", ")", ".", "VReplicationExec", "(", "ctx", ",", "master", ".", "Tablet", ",", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "MasterAlias", ",", "cmd", ")", "\n", "}", "\n", "if", "err", ":=", "wr", ".", "SourceShardAdd", "(", "ctx", ",", "toKeyspace", ",", "dest", ".", "ShardName", "(", ")", ",", "uint32", "(", "qr", ".", "InsertId", ")", ",", "fromKeyspace", ",", "source", ".", "ShardName", "(", ")", ",", "nil", ",", "tables", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "ShardName", "(", ")", ",", "source", ".", "ShardName", "(", ")", ")", "\n", "}", "\n", "// Start vreplication only if metadata was successfully created.", "cmd", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "binlogplayer", ".", "VReplicationInit", ",", "qr", ".", "InsertId", ")", "\n", "if", "_", ",", "err", "=", "wr", ".", "TabletManagerClient", "(", ")", ".", "VReplicationExec", "(", "ctx", ",", "master", ".", "Tablet", ",", "cmd", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dest", ".", "MasterAlias", ",", "cmd", ")", "\n", "}", "\n", "return", "wr", ".", "refreshMasters", "(", "ctx", ",", "[", "]", "*", "topo", ".", "ShardInfo", "{", "dest", "}", ")", "\n", "}" ]
// VerticalSplitClone initiates a VerticalSplitClone workflow.
[ "VerticalSplitClone", "initiates", "a", "VerticalSplitClone", "workflow", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L153-L193
train
vitessio/vitess
go/vt/wrangler/keyspace.go
MigrateServedTypes
func (wr *Wrangler) MigrateServedTypes(ctx context.Context, keyspace, shard string, cells []string, servedType topodatapb.TabletType, reverse, skipReFreshState bool, filteredReplicationWaitTime time.Duration, reverseReplication bool) (err error) { // check input parameters if servedType == topodatapb.TabletType_MASTER { // we cannot migrate a master back, since when master migration // is done, the source shards are dead if reverse { return fmt.Errorf("cannot migrate master back to %v/%v", keyspace, shard) } // we cannot skip refresh state for a master if skipReFreshState { return fmt.Errorf("cannot skip refresh state for master migration on %v/%v", keyspace, shard) } if cells != nil { return fmt.Errorf("cannot specify cells for master migration on %v/%v", keyspace, shard) } } // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("MigrateServedTypes(%v)", servedType)) if lockErr != nil { return lockErr } defer unlock(&err) // find overlapping shards in this keyspace wr.Logger().Infof("Finding the overlapping shards in keyspace %v", keyspace) osList, err := topotools.FindOverlappingShards(ctx, wr.ts, keyspace) if err != nil { return fmt.Errorf("FindOverlappingShards failed: %v", err) } // find our shard in there os := topotools.OverlappingShardsForShard(osList, shard) if os == nil { return fmt.Errorf("shard %v is not involved in any overlapping shards", shard) } sourceShards, destinationShards, err := wr.findSourceDest(ctx, os) if err != nil { return err } // execute the migration if servedType == topodatapb.TabletType_MASTER { if err = wr.masterMigrateServedType(ctx, keyspace, sourceShards, destinationShards, filteredReplicationWaitTime, reverseReplication); err != nil { return err } } else { if err = wr.replicaMigrateServedType(ctx, keyspace, sourceShards, destinationShards, cells, servedType, reverse); err != nil { return err } } // Master migrate performs its own refresh. // Otherwise, honor skipRefreshState if requested. if servedType == topodatapb.TabletType_MASTER || skipReFreshState { return nil } // refresh // TODO(b/26388813): Integrate vtctl WaitForDrain here instead of just sleeping. // Anything that's not a replica will use the RDONLY sleep time. waitForDrainSleep := *waitForDrainSleepRdonly if servedType == topodatapb.TabletType_REPLICA { waitForDrainSleep = *waitForDrainSleepReplica } wr.Logger().Infof("WaitForDrain: Sleeping for %.0f seconds before shutting down query service on old tablets...", waitForDrainSleep.Seconds()) time.Sleep(waitForDrainSleep) wr.Logger().Infof("WaitForDrain: Sleeping finished. Shutting down queryservice on old tablets now.") rec := concurrency.AllErrorRecorder{} refreshShards := sourceShards if reverse { // For a backwards migration, we should refresh (disable) destination shards instead. refreshShards = destinationShards } for _, si := range refreshShards { rec.RecordError(wr.RefreshTabletsByShard(ctx, si, []topodatapb.TabletType{servedType}, cells)) } return rec.Error() }
go
func (wr *Wrangler) MigrateServedTypes(ctx context.Context, keyspace, shard string, cells []string, servedType topodatapb.TabletType, reverse, skipReFreshState bool, filteredReplicationWaitTime time.Duration, reverseReplication bool) (err error) { // check input parameters if servedType == topodatapb.TabletType_MASTER { // we cannot migrate a master back, since when master migration // is done, the source shards are dead if reverse { return fmt.Errorf("cannot migrate master back to %v/%v", keyspace, shard) } // we cannot skip refresh state for a master if skipReFreshState { return fmt.Errorf("cannot skip refresh state for master migration on %v/%v", keyspace, shard) } if cells != nil { return fmt.Errorf("cannot specify cells for master migration on %v/%v", keyspace, shard) } } // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("MigrateServedTypes(%v)", servedType)) if lockErr != nil { return lockErr } defer unlock(&err) // find overlapping shards in this keyspace wr.Logger().Infof("Finding the overlapping shards in keyspace %v", keyspace) osList, err := topotools.FindOverlappingShards(ctx, wr.ts, keyspace) if err != nil { return fmt.Errorf("FindOverlappingShards failed: %v", err) } // find our shard in there os := topotools.OverlappingShardsForShard(osList, shard) if os == nil { return fmt.Errorf("shard %v is not involved in any overlapping shards", shard) } sourceShards, destinationShards, err := wr.findSourceDest(ctx, os) if err != nil { return err } // execute the migration if servedType == topodatapb.TabletType_MASTER { if err = wr.masterMigrateServedType(ctx, keyspace, sourceShards, destinationShards, filteredReplicationWaitTime, reverseReplication); err != nil { return err } } else { if err = wr.replicaMigrateServedType(ctx, keyspace, sourceShards, destinationShards, cells, servedType, reverse); err != nil { return err } } // Master migrate performs its own refresh. // Otherwise, honor skipRefreshState if requested. if servedType == topodatapb.TabletType_MASTER || skipReFreshState { return nil } // refresh // TODO(b/26388813): Integrate vtctl WaitForDrain here instead of just sleeping. // Anything that's not a replica will use the RDONLY sleep time. waitForDrainSleep := *waitForDrainSleepRdonly if servedType == topodatapb.TabletType_REPLICA { waitForDrainSleep = *waitForDrainSleepReplica } wr.Logger().Infof("WaitForDrain: Sleeping for %.0f seconds before shutting down query service on old tablets...", waitForDrainSleep.Seconds()) time.Sleep(waitForDrainSleep) wr.Logger().Infof("WaitForDrain: Sleeping finished. Shutting down queryservice on old tablets now.") rec := concurrency.AllErrorRecorder{} refreshShards := sourceShards if reverse { // For a backwards migration, we should refresh (disable) destination shards instead. refreshShards = destinationShards } for _, si := range refreshShards { rec.RecordError(wr.RefreshTabletsByShard(ctx, si, []topodatapb.TabletType{servedType}, cells)) } return rec.Error() }
[ "func", "(", "wr", "*", "Wrangler", ")", "MigrateServedTypes", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "cells", "[", "]", "string", ",", "servedType", "topodatapb", ".", "TabletType", ",", "reverse", ",", "skipReFreshState", "bool", ",", "filteredReplicationWaitTime", "time", ".", "Duration", ",", "reverseReplication", "bool", ")", "(", "err", "error", ")", "{", "// check input parameters", "if", "servedType", "==", "topodatapb", ".", "TabletType_MASTER", "{", "// we cannot migrate a master back, since when master migration", "// is done, the source shards are dead", "if", "reverse", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "}", "\n", "// we cannot skip refresh state for a master", "if", "skipReFreshState", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "}", "\n", "if", "cells", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "}", "\n", "}", "\n\n", "// lock the keyspace", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "servedType", ")", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// find overlapping shards in this keyspace", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "keyspace", ")", "\n", "osList", ",", "err", ":=", "topotools", ".", "FindOverlappingShards", "(", "ctx", ",", "wr", ".", "ts", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// find our shard in there", "os", ":=", "topotools", ".", "OverlappingShardsForShard", "(", "osList", ",", "shard", ")", "\n", "if", "os", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "shard", ")", "\n", "}", "\n\n", "sourceShards", ",", "destinationShards", ",", "err", ":=", "wr", ".", "findSourceDest", "(", "ctx", ",", "os", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// execute the migration", "if", "servedType", "==", "topodatapb", ".", "TabletType_MASTER", "{", "if", "err", "=", "wr", ".", "masterMigrateServedType", "(", "ctx", ",", "keyspace", ",", "sourceShards", ",", "destinationShards", ",", "filteredReplicationWaitTime", ",", "reverseReplication", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "if", "err", "=", "wr", ".", "replicaMigrateServedType", "(", "ctx", ",", "keyspace", ",", "sourceShards", ",", "destinationShards", ",", "cells", ",", "servedType", ",", "reverse", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Master migrate performs its own refresh.", "// Otherwise, honor skipRefreshState if requested.", "if", "servedType", "==", "topodatapb", ".", "TabletType_MASTER", "||", "skipReFreshState", "{", "return", "nil", "\n", "}", "\n\n", "// refresh", "// TODO(b/26388813): Integrate vtctl WaitForDrain here instead of just sleeping.", "// Anything that's not a replica will use the RDONLY sleep time.", "waitForDrainSleep", ":=", "*", "waitForDrainSleepRdonly", "\n", "if", "servedType", "==", "topodatapb", ".", "TabletType_REPLICA", "{", "waitForDrainSleep", "=", "*", "waitForDrainSleepReplica", "\n", "}", "\n", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "waitForDrainSleep", ".", "Seconds", "(", ")", ")", "\n", "time", ".", "Sleep", "(", "waitForDrainSleep", ")", "\n", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ")", "\n\n", "rec", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "refreshShards", ":=", "sourceShards", "\n", "if", "reverse", "{", "// For a backwards migration, we should refresh (disable) destination shards instead.", "refreshShards", "=", "destinationShards", "\n", "}", "\n", "for", "_", ",", "si", ":=", "range", "refreshShards", "{", "rec", ".", "RecordError", "(", "wr", ".", "RefreshTabletsByShard", "(", "ctx", ",", "si", ",", "[", "]", "topodatapb", ".", "TabletType", "{", "servedType", "}", ",", "cells", ")", ")", "\n", "}", "\n", "return", "rec", ".", "Error", "(", ")", "\n", "}" ]
// MigrateServedTypes is used during horizontal splits to migrate a // served type from a list of shards to another.
[ "MigrateServedTypes", "is", "used", "during", "horizontal", "splits", "to", "migrate", "a", "served", "type", "from", "a", "list", "of", "shards", "to", "another", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L340-L420
train
vitessio/vitess
go/vt/wrangler/keyspace.go
findSourceDest
func (wr *Wrangler) findSourceDest(ctx context.Context, os *topotools.OverlappingShards) (sourceShards, destinationShards []*topo.ShardInfo, err error) { // It's possible that both source and destination have source shards because of reversible replication. // If so, the Frozen flag in the tablet control record dictates the direction. // So, check that first. for _, left := range os.Left { tc := left.GetTabletControl(topodatapb.TabletType_MASTER) if tc == nil { continue } if tc.Frozen { return os.Left, os.Right, nil } } for _, right := range os.Right { tc := right.GetTabletControl(topodatapb.TabletType_MASTER) if tc == nil { continue } if tc.Frozen { return os.Right, os.Left, nil } } for _, left := range os.Left { if len(left.SourceShards) != 0 { return os.Right, os.Left, nil } } for _, right := range os.Right { if len(right.SourceShards) != 0 { return os.Left, os.Right, nil } } return nil, nil, fmt.Errorf("neither Shard '%v' nor Shard '%v' have a 'SourceShards' entry. Did you successfully run vtworker SplitClone before? Or did you already migrate the MASTER type?", os.Left[0].ShardName(), os.Right[0].ShardName()) }
go
func (wr *Wrangler) findSourceDest(ctx context.Context, os *topotools.OverlappingShards) (sourceShards, destinationShards []*topo.ShardInfo, err error) { // It's possible that both source and destination have source shards because of reversible replication. // If so, the Frozen flag in the tablet control record dictates the direction. // So, check that first. for _, left := range os.Left { tc := left.GetTabletControl(topodatapb.TabletType_MASTER) if tc == nil { continue } if tc.Frozen { return os.Left, os.Right, nil } } for _, right := range os.Right { tc := right.GetTabletControl(topodatapb.TabletType_MASTER) if tc == nil { continue } if tc.Frozen { return os.Right, os.Left, nil } } for _, left := range os.Left { if len(left.SourceShards) != 0 { return os.Right, os.Left, nil } } for _, right := range os.Right { if len(right.SourceShards) != 0 { return os.Left, os.Right, nil } } return nil, nil, fmt.Errorf("neither Shard '%v' nor Shard '%v' have a 'SourceShards' entry. Did you successfully run vtworker SplitClone before? Or did you already migrate the MASTER type?", os.Left[0].ShardName(), os.Right[0].ShardName()) }
[ "func", "(", "wr", "*", "Wrangler", ")", "findSourceDest", "(", "ctx", "context", ".", "Context", ",", "os", "*", "topotools", ".", "OverlappingShards", ")", "(", "sourceShards", ",", "destinationShards", "[", "]", "*", "topo", ".", "ShardInfo", ",", "err", "error", ")", "{", "// It's possible that both source and destination have source shards because of reversible replication.", "// If so, the Frozen flag in the tablet control record dictates the direction.", "// So, check that first.", "for", "_", ",", "left", ":=", "range", "os", ".", "Left", "{", "tc", ":=", "left", ".", "GetTabletControl", "(", "topodatapb", ".", "TabletType_MASTER", ")", "\n", "if", "tc", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "tc", ".", "Frozen", "{", "return", "os", ".", "Left", ",", "os", ".", "Right", ",", "nil", "\n", "}", "\n", "}", "\n", "for", "_", ",", "right", ":=", "range", "os", ".", "Right", "{", "tc", ":=", "right", ".", "GetTabletControl", "(", "topodatapb", ".", "TabletType_MASTER", ")", "\n", "if", "tc", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "tc", ".", "Frozen", "{", "return", "os", ".", "Right", ",", "os", ".", "Left", ",", "nil", "\n", "}", "\n", "}", "\n", "for", "_", ",", "left", ":=", "range", "os", ".", "Left", "{", "if", "len", "(", "left", ".", "SourceShards", ")", "!=", "0", "{", "return", "os", ".", "Right", ",", "os", ".", "Left", ",", "nil", "\n", "}", "\n", "}", "\n", "for", "_", ",", "right", ":=", "range", "os", ".", "Right", "{", "if", "len", "(", "right", ".", "SourceShards", ")", "!=", "0", "{", "return", "os", ".", "Left", ",", "os", ".", "Right", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "os", ".", "Left", "[", "0", "]", ".", "ShardName", "(", ")", ",", "os", ".", "Right", "[", "0", "]", ".", "ShardName", "(", ")", ")", "\n", "}" ]
// findSourceDest derives the source and destination from the overlapping shards. // Whichever side has SourceShards is a destination.
[ "findSourceDest", "derives", "the", "source", "and", "destination", "from", "the", "overlapping", "shards", ".", "Whichever", "side", "has", "SourceShards", "is", "a", "destination", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L424-L457
train
vitessio/vitess
go/vt/wrangler/keyspace.go
refreshMasters
func (wr *Wrangler) refreshMasters(ctx context.Context, shards []*topo.ShardInfo) error { wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} for _, si := range shards { wg.Add(1) go func(si *topo.ShardInfo) { defer wg.Done() wr.Logger().Infof("RefreshState master %v", topoproto.TabletAliasString(si.MasterAlias)) ti, err := wr.ts.GetTablet(ctx, si.MasterAlias) if err != nil { rec.RecordError(err) return } if err := wr.tmc.RefreshState(ctx, ti.Tablet); err != nil { rec.RecordError(err) } else { wr.Logger().Infof("%v responded", topoproto.TabletAliasString(si.MasterAlias)) } }(si) } wg.Wait() return rec.Error() }
go
func (wr *Wrangler) refreshMasters(ctx context.Context, shards []*topo.ShardInfo) error { wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} for _, si := range shards { wg.Add(1) go func(si *topo.ShardInfo) { defer wg.Done() wr.Logger().Infof("RefreshState master %v", topoproto.TabletAliasString(si.MasterAlias)) ti, err := wr.ts.GetTablet(ctx, si.MasterAlias) if err != nil { rec.RecordError(err) return } if err := wr.tmc.RefreshState(ctx, ti.Tablet); err != nil { rec.RecordError(err) } else { wr.Logger().Infof("%v responded", topoproto.TabletAliasString(si.MasterAlias)) } }(si) } wg.Wait() return rec.Error() }
[ "func", "(", "wr", "*", "Wrangler", ")", "refreshMasters", "(", "ctx", "context", ".", "Context", ",", "shards", "[", "]", "*", "topo", ".", "ShardInfo", ")", "error", "{", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "rec", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "for", "_", ",", "si", ":=", "range", "shards", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "si", "*", "topo", ".", "ShardInfo", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "si", ".", "MasterAlias", ")", ")", "\n", "ti", ",", "err", ":=", "wr", ".", "ts", ".", "GetTablet", "(", "ctx", ",", "si", ".", "MasterAlias", ")", "\n", "if", "err", "!=", "nil", "{", "rec", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", ":=", "wr", ".", "tmc", ".", "RefreshState", "(", "ctx", ",", "ti", ".", "Tablet", ")", ";", "err", "!=", "nil", "{", "rec", ".", "RecordError", "(", "err", ")", "\n", "}", "else", "{", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "si", ".", "MasterAlias", ")", ")", "\n", "}", "\n", "}", "(", "si", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "rec", ".", "Error", "(", ")", "\n", "}" ]
// refreshMasters will just RPC-ping all the masters with RefreshState
[ "refreshMasters", "will", "just", "RPC", "-", "ping", "all", "the", "masters", "with", "RefreshState" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L537-L560
train
vitessio/vitess
go/vt/wrangler/keyspace.go
replicaMigrateServedType
func (wr *Wrangler) replicaMigrateServedType(ctx context.Context, keyspace string, sourceShards, destinationShards []*topo.ShardInfo, cells []string, servedType topodatapb.TabletType, reverse bool) (err error) { ev := &events.MigrateServedTypes{ KeyspaceName: keyspace, SourceShards: sourceShards, DestinationShards: destinationShards, ServedType: servedType, Reverse: reverse, } event.DispatchUpdate(ev, "start") defer func() { if err != nil { event.DispatchUpdate(ev, "failed: "+err.Error()) } }() fromShards, toShards := sourceShards, destinationShards if reverse { fromShards, toShards = toShards, fromShards } // Check and update all source shard records. // Enable query service if needed event.DispatchUpdate(ev, "updating shards to migrate from") if err = wr.updateShardRecords(ctx, keyspace, fromShards, cells, servedType, true /* isFrom */, false /* clearSourceShards */); err != nil { return err } // Do the same for destination shards event.DispatchUpdate(ev, "updating shards to migrate to") if err = wr.updateShardRecords(ctx, keyspace, toShards, cells, servedType, false, false); err != nil { return err } // Now update serving keyspace if err = wr.ts.MigrateServedType(ctx, keyspace, toShards, fromShards, servedType, cells); err != nil { return err } event.DispatchUpdate(ev, "finished") return nil }
go
func (wr *Wrangler) replicaMigrateServedType(ctx context.Context, keyspace string, sourceShards, destinationShards []*topo.ShardInfo, cells []string, servedType topodatapb.TabletType, reverse bool) (err error) { ev := &events.MigrateServedTypes{ KeyspaceName: keyspace, SourceShards: sourceShards, DestinationShards: destinationShards, ServedType: servedType, Reverse: reverse, } event.DispatchUpdate(ev, "start") defer func() { if err != nil { event.DispatchUpdate(ev, "failed: "+err.Error()) } }() fromShards, toShards := sourceShards, destinationShards if reverse { fromShards, toShards = toShards, fromShards } // Check and update all source shard records. // Enable query service if needed event.DispatchUpdate(ev, "updating shards to migrate from") if err = wr.updateShardRecords(ctx, keyspace, fromShards, cells, servedType, true /* isFrom */, false /* clearSourceShards */); err != nil { return err } // Do the same for destination shards event.DispatchUpdate(ev, "updating shards to migrate to") if err = wr.updateShardRecords(ctx, keyspace, toShards, cells, servedType, false, false); err != nil { return err } // Now update serving keyspace if err = wr.ts.MigrateServedType(ctx, keyspace, toShards, fromShards, servedType, cells); err != nil { return err } event.DispatchUpdate(ev, "finished") return nil }
[ "func", "(", "wr", "*", "Wrangler", ")", "replicaMigrateServedType", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "sourceShards", ",", "destinationShards", "[", "]", "*", "topo", ".", "ShardInfo", ",", "cells", "[", "]", "string", ",", "servedType", "topodatapb", ".", "TabletType", ",", "reverse", "bool", ")", "(", "err", "error", ")", "{", "ev", ":=", "&", "events", ".", "MigrateServedTypes", "{", "KeyspaceName", ":", "keyspace", ",", "SourceShards", ":", "sourceShards", ",", "DestinationShards", ":", "destinationShards", ",", "ServedType", ":", "servedType", ",", "Reverse", ":", "reverse", ",", "}", "\n", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "fromShards", ",", "toShards", ":=", "sourceShards", ",", "destinationShards", "\n", "if", "reverse", "{", "fromShards", ",", "toShards", "=", "toShards", ",", "fromShards", "\n", "}", "\n\n", "// Check and update all source shard records.", "// Enable query service if needed", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", ")", "\n", "if", "err", "=", "wr", ".", "updateShardRecords", "(", "ctx", ",", "keyspace", ",", "fromShards", ",", "cells", ",", "servedType", ",", "true", "/* isFrom */", ",", "false", "/* clearSourceShards */", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Do the same for destination shards", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", ")", "\n", "if", "err", "=", "wr", ".", "updateShardRecords", "(", "ctx", ",", "keyspace", ",", "toShards", ",", "cells", ",", "servedType", ",", "false", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Now update serving keyspace", "if", "err", "=", "wr", ".", "ts", ".", "MigrateServedType", "(", "ctx", ",", "keyspace", ",", "toShards", ",", "fromShards", ",", "servedType", ",", "cells", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// replicaMigrateServedType operates with the keyspace locked
[ "replicaMigrateServedType", "operates", "with", "the", "keyspace", "locked" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L563-L604
train
vitessio/vitess
go/vt/wrangler/keyspace.go
updateShardRecords
func (wr *Wrangler) updateShardRecords(ctx context.Context, keyspace string, shards []*topo.ShardInfo, cells []string, servedType topodatapb.TabletType, isFrom bool, clearSourceShards bool) (err error) { err = wr.ts.UpdateDisableQueryService(ctx, keyspace, shards, servedType, cells, isFrom /* disable */) if err != nil { return err } for i, si := range shards { updatedShard, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error { if clearSourceShards { si.SourceShards = nil } return nil }) if err != nil { return err } shards[i] = updatedShard // For 'to' shards, refresh to make them serve. // The 'from' shards will be refreshed after traffic has migrated. if !isFrom { wr.RefreshTabletsByShard(ctx, si, []topodatapb.TabletType{servedType}, cells) } } return nil }
go
func (wr *Wrangler) updateShardRecords(ctx context.Context, keyspace string, shards []*topo.ShardInfo, cells []string, servedType topodatapb.TabletType, isFrom bool, clearSourceShards bool) (err error) { err = wr.ts.UpdateDisableQueryService(ctx, keyspace, shards, servedType, cells, isFrom /* disable */) if err != nil { return err } for i, si := range shards { updatedShard, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error { if clearSourceShards { si.SourceShards = nil } return nil }) if err != nil { return err } shards[i] = updatedShard // For 'to' shards, refresh to make them serve. // The 'from' shards will be refreshed after traffic has migrated. if !isFrom { wr.RefreshTabletsByShard(ctx, si, []topodatapb.TabletType{servedType}, cells) } } return nil }
[ "func", "(", "wr", "*", "Wrangler", ")", "updateShardRecords", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "shards", "[", "]", "*", "topo", ".", "ShardInfo", ",", "cells", "[", "]", "string", ",", "servedType", "topodatapb", ".", "TabletType", ",", "isFrom", "bool", ",", "clearSourceShards", "bool", ")", "(", "err", "error", ")", "{", "err", "=", "wr", ".", "ts", ".", "UpdateDisableQueryService", "(", "ctx", ",", "keyspace", ",", "shards", ",", "servedType", ",", "cells", ",", "isFrom", "/* disable */", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "i", ",", "si", ":=", "range", "shards", "{", "updatedShard", ",", "err", ":=", "wr", ".", "ts", ".", "UpdateShardFields", "(", "ctx", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "func", "(", "si", "*", "topo", ".", "ShardInfo", ")", "error", "{", "if", "clearSourceShards", "{", "si", ".", "SourceShards", "=", "nil", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "shards", "[", "i", "]", "=", "updatedShard", "\n\n", "// For 'to' shards, refresh to make them serve.", "// The 'from' shards will be refreshed after traffic has migrated.", "if", "!", "isFrom", "{", "wr", ".", "RefreshTabletsByShard", "(", "ctx", ",", "si", ",", "[", "]", "topodatapb", ".", "TabletType", "{", "servedType", "}", ",", "cells", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updateShardRecords updates the shard records based on 'from' or 'to' direction.
[ "updateShardRecords", "updates", "the", "shard", "records", "based", "on", "from", "or", "to", "direction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L850-L877
train
vitessio/vitess
go/vt/wrangler/keyspace.go
updateFrozenFlag
func (wr *Wrangler) updateFrozenFlag(ctx context.Context, shards []*topo.ShardInfo, value bool) (err error) { for i, si := range shards { updatedShard, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error { tc := si.GetTabletControl(topodatapb.TabletType_MASTER) if tc != nil { tc.Frozen = value return nil } // This shard does not have a tablet control record, adding one to set frozen flag tc = &topodatapb.Shard_TabletControl{ TabletType: topodatapb.TabletType_MASTER, Frozen: value, } si.TabletControls = append(si.TabletControls, tc) return nil }) if err != nil { return err } shards[i] = updatedShard } return nil }
go
func (wr *Wrangler) updateFrozenFlag(ctx context.Context, shards []*topo.ShardInfo, value bool) (err error) { for i, si := range shards { updatedShard, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error { tc := si.GetTabletControl(topodatapb.TabletType_MASTER) if tc != nil { tc.Frozen = value return nil } // This shard does not have a tablet control record, adding one to set frozen flag tc = &topodatapb.Shard_TabletControl{ TabletType: topodatapb.TabletType_MASTER, Frozen: value, } si.TabletControls = append(si.TabletControls, tc) return nil }) if err != nil { return err } shards[i] = updatedShard } return nil }
[ "func", "(", "wr", "*", "Wrangler", ")", "updateFrozenFlag", "(", "ctx", "context", ".", "Context", ",", "shards", "[", "]", "*", "topo", ".", "ShardInfo", ",", "value", "bool", ")", "(", "err", "error", ")", "{", "for", "i", ",", "si", ":=", "range", "shards", "{", "updatedShard", ",", "err", ":=", "wr", ".", "ts", ".", "UpdateShardFields", "(", "ctx", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "func", "(", "si", "*", "topo", ".", "ShardInfo", ")", "error", "{", "tc", ":=", "si", ".", "GetTabletControl", "(", "topodatapb", ".", "TabletType_MASTER", ")", "\n", "if", "tc", "!=", "nil", "{", "tc", ".", "Frozen", "=", "value", "\n", "return", "nil", "\n", "}", "\n", "// This shard does not have a tablet control record, adding one to set frozen flag", "tc", "=", "&", "topodatapb", ".", "Shard_TabletControl", "{", "TabletType", ":", "topodatapb", ".", "TabletType_MASTER", ",", "Frozen", ":", "value", ",", "}", "\n", "si", ".", "TabletControls", "=", "append", "(", "si", ".", "TabletControls", ",", "tc", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "shards", "[", "i", "]", "=", "updatedShard", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updateFrozenFlag sets or unsets the Frozen flag for master migration. This is performed // for all master tablet control records.
[ "updateFrozenFlag", "sets", "or", "unsets", "the", "Frozen", "flag", "for", "master", "migration", ".", "This", "is", "performed", "for", "all", "master", "tablet", "control", "records", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L881-L904
train
vitessio/vitess
go/vt/wrangler/keyspace.go
MigrateServedFrom
func (wr *Wrangler) MigrateServedFrom(ctx context.Context, keyspace, shard string, servedType topodatapb.TabletType, cells []string, reverse bool, filteredReplicationWaitTime time.Duration) (err error) { // read the destination keyspace, check it ki, err := wr.ts.GetKeyspace(ctx, keyspace) if err != nil { return err } if len(ki.ServedFroms) == 0 { return fmt.Errorf("destination keyspace %v is not a vertical split target", keyspace) } // read the destination shard, check it si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } if len(si.SourceShards) != 1 || len(si.SourceShards[0].Tables) == 0 { return fmt.Errorf("destination shard %v/%v is not a vertical split target", keyspace, shard) } // check the migration is valid before locking (will also be checked // after locking to be sure) sourceKeyspace := si.SourceShards[0].Keyspace if err := ki.CheckServedFromMigration(servedType, cells, sourceKeyspace, !reverse); err != nil { return err } // lock the keyspaces, source first. ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, sourceKeyspace, fmt.Sprintf("MigrateServedFrom(%v)", servedType)) if lockErr != nil { return lockErr } defer unlock(&err) ctx, unlock, lockErr = wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("MigrateServedFrom(%v)", servedType)) if lockErr != nil { return lockErr } defer unlock(&err) // execute the migration err = wr.migrateServedFromLocked(ctx, ki, si, servedType, cells, reverse, filteredReplicationWaitTime) // rebuild the keyspace serving graph if there was no error if err == nil { err = topotools.RebuildKeyspaceLocked(ctx, wr.logger, wr.ts, keyspace, cells) } return err }
go
func (wr *Wrangler) MigrateServedFrom(ctx context.Context, keyspace, shard string, servedType topodatapb.TabletType, cells []string, reverse bool, filteredReplicationWaitTime time.Duration) (err error) { // read the destination keyspace, check it ki, err := wr.ts.GetKeyspace(ctx, keyspace) if err != nil { return err } if len(ki.ServedFroms) == 0 { return fmt.Errorf("destination keyspace %v is not a vertical split target", keyspace) } // read the destination shard, check it si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } if len(si.SourceShards) != 1 || len(si.SourceShards[0].Tables) == 0 { return fmt.Errorf("destination shard %v/%v is not a vertical split target", keyspace, shard) } // check the migration is valid before locking (will also be checked // after locking to be sure) sourceKeyspace := si.SourceShards[0].Keyspace if err := ki.CheckServedFromMigration(servedType, cells, sourceKeyspace, !reverse); err != nil { return err } // lock the keyspaces, source first. ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, sourceKeyspace, fmt.Sprintf("MigrateServedFrom(%v)", servedType)) if lockErr != nil { return lockErr } defer unlock(&err) ctx, unlock, lockErr = wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("MigrateServedFrom(%v)", servedType)) if lockErr != nil { return lockErr } defer unlock(&err) // execute the migration err = wr.migrateServedFromLocked(ctx, ki, si, servedType, cells, reverse, filteredReplicationWaitTime) // rebuild the keyspace serving graph if there was no error if err == nil { err = topotools.RebuildKeyspaceLocked(ctx, wr.logger, wr.ts, keyspace, cells) } return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "MigrateServedFrom", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "servedType", "topodatapb", ".", "TabletType", ",", "cells", "[", "]", "string", ",", "reverse", "bool", ",", "filteredReplicationWaitTime", "time", ".", "Duration", ")", "(", "err", "error", ")", "{", "// read the destination keyspace, check it", "ki", ",", "err", ":=", "wr", ".", "ts", ".", "GetKeyspace", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "ki", ".", "ServedFroms", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ")", "\n", "}", "\n\n", "// read the destination shard, check it", "si", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "si", ".", "SourceShards", ")", "!=", "1", "||", "len", "(", "si", ".", "SourceShards", "[", "0", "]", ".", "Tables", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "}", "\n\n", "// check the migration is valid before locking (will also be checked", "// after locking to be sure)", "sourceKeyspace", ":=", "si", ".", "SourceShards", "[", "0", "]", ".", "Keyspace", "\n", "if", "err", ":=", "ki", ".", "CheckServedFromMigration", "(", "servedType", ",", "cells", ",", "sourceKeyspace", ",", "!", "reverse", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// lock the keyspaces, source first.", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "sourceKeyspace", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "servedType", ")", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n", "ctx", ",", "unlock", ",", "lockErr", "=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "servedType", ")", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// execute the migration", "err", "=", "wr", ".", "migrateServedFromLocked", "(", "ctx", ",", "ki", ",", "si", ",", "servedType", ",", "cells", ",", "reverse", ",", "filteredReplicationWaitTime", ")", "\n\n", "// rebuild the keyspace serving graph if there was no error", "if", "err", "==", "nil", "{", "err", "=", "topotools", ".", "RebuildKeyspaceLocked", "(", "ctx", ",", "wr", ".", "logger", ",", "wr", ".", "ts", ",", "keyspace", ",", "cells", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// MigrateServedFrom is used during vertical splits to migrate a // served type from a keyspace to another.
[ "MigrateServedFrom", "is", "used", "during", "vertical", "splits", "to", "migrate", "a", "served", "type", "from", "a", "keyspace", "to", "another", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L1083-L1130
train
vitessio/vitess
go/vt/wrangler/keyspace.go
SetKeyspaceServedFrom
func (wr *Wrangler) SetKeyspaceServedFrom(ctx context.Context, keyspace string, servedType topodatapb.TabletType, cells []string, sourceKeyspace string, remove bool) (err error) { // Lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "SetKeyspaceServedFrom") if lockErr != nil { return lockErr } defer unlock(&err) // and update it ki, err := wr.ts.GetKeyspace(ctx, keyspace) if err != nil { return err } if err := ki.UpdateServedFromMap(servedType, cells, sourceKeyspace, remove, nil); err != nil { return err } return wr.ts.UpdateKeyspace(ctx, ki) }
go
func (wr *Wrangler) SetKeyspaceServedFrom(ctx context.Context, keyspace string, servedType topodatapb.TabletType, cells []string, sourceKeyspace string, remove bool) (err error) { // Lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "SetKeyspaceServedFrom") if lockErr != nil { return lockErr } defer unlock(&err) // and update it ki, err := wr.ts.GetKeyspace(ctx, keyspace) if err != nil { return err } if err := ki.UpdateServedFromMap(servedType, cells, sourceKeyspace, remove, nil); err != nil { return err } return wr.ts.UpdateKeyspace(ctx, ki) }
[ "func", "(", "wr", "*", "Wrangler", ")", "SetKeyspaceServedFrom", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "servedType", "topodatapb", ".", "TabletType", ",", "cells", "[", "]", "string", ",", "sourceKeyspace", "string", ",", "remove", "bool", ")", "(", "err", "error", ")", "{", "// Lock the keyspace", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "\"", "\"", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// and update it", "ki", ",", "err", ":=", "wr", ".", "ts", ".", "GetKeyspace", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ki", ".", "UpdateServedFromMap", "(", "servedType", ",", "cells", ",", "sourceKeyspace", ",", "remove", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "wr", ".", "ts", ".", "UpdateKeyspace", "(", "ctx", ",", "ki", ")", "\n", "}" ]
// SetKeyspaceServedFrom locks a keyspace and changes its ServerFromMap
[ "SetKeyspaceServedFrom", "locks", "a", "keyspace", "and", "changes", "its", "ServerFromMap" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L1296-L1313
train
vitessio/vitess
go/vt/wrangler/keyspace.go
RefreshTabletsByShard
func (wr *Wrangler) RefreshTabletsByShard(ctx context.Context, si *topo.ShardInfo, tabletTypes []topodatapb.TabletType, cells []string) error { wr.Logger().Infof("RefreshTabletsByShard called on shard %v/%v", si.Keyspace(), si.ShardName()) tabletMap, err := wr.ts.GetTabletMapForShardByCell(ctx, si.Keyspace(), si.ShardName(), cells) switch { case err == nil: // keep going case topo.IsErrType(err, topo.PartialResult): wr.Logger().Warningf("RefreshTabletsByShard: got partial result for shard %v/%v, may not refresh all tablets everywhere", si.Keyspace(), si.ShardName()) default: return err } // ignore errors in this phase wg := sync.WaitGroup{} for _, ti := range tabletMap { if tabletTypes != nil && !topoproto.IsTypeInList(ti.Type, tabletTypes) { continue } if ti.Hostname == "" { // The tablet is not running, we don't have the host // name to connect to, so we just skip this tablet. wr.Logger().Infof("Tablet %v has no hostname, skipping its RefreshState", ti.AliasString()) continue } wg.Add(1) go func(ti *topo.TabletInfo) { wr.Logger().Infof("Calling RefreshState on tablet %v", ti.AliasString()) // Setting an upper bound timeout to fail faster in case of an error. // Using 60 seconds because RefreshState should not take more than 30 seconds. // (RefreshState will restart the tablet's QueryService and most time will be spent on the shutdown, i.e. waiting up to 30 seconds on transactions (see Config.TransactionTimeout)). ctx, cancel := context.WithTimeout(ctx, 60*time.Second) if err := wr.tmc.RefreshState(ctx, ti.Tablet); err != nil { wr.Logger().Warningf("RefreshTabletsByShard: failed to refresh %v: %v", ti.AliasString(), err) } cancel() wg.Done() }(ti) } wg.Wait() return nil }
go
func (wr *Wrangler) RefreshTabletsByShard(ctx context.Context, si *topo.ShardInfo, tabletTypes []topodatapb.TabletType, cells []string) error { wr.Logger().Infof("RefreshTabletsByShard called on shard %v/%v", si.Keyspace(), si.ShardName()) tabletMap, err := wr.ts.GetTabletMapForShardByCell(ctx, si.Keyspace(), si.ShardName(), cells) switch { case err == nil: // keep going case topo.IsErrType(err, topo.PartialResult): wr.Logger().Warningf("RefreshTabletsByShard: got partial result for shard %v/%v, may not refresh all tablets everywhere", si.Keyspace(), si.ShardName()) default: return err } // ignore errors in this phase wg := sync.WaitGroup{} for _, ti := range tabletMap { if tabletTypes != nil && !topoproto.IsTypeInList(ti.Type, tabletTypes) { continue } if ti.Hostname == "" { // The tablet is not running, we don't have the host // name to connect to, so we just skip this tablet. wr.Logger().Infof("Tablet %v has no hostname, skipping its RefreshState", ti.AliasString()) continue } wg.Add(1) go func(ti *topo.TabletInfo) { wr.Logger().Infof("Calling RefreshState on tablet %v", ti.AliasString()) // Setting an upper bound timeout to fail faster in case of an error. // Using 60 seconds because RefreshState should not take more than 30 seconds. // (RefreshState will restart the tablet's QueryService and most time will be spent on the shutdown, i.e. waiting up to 30 seconds on transactions (see Config.TransactionTimeout)). ctx, cancel := context.WithTimeout(ctx, 60*time.Second) if err := wr.tmc.RefreshState(ctx, ti.Tablet); err != nil { wr.Logger().Warningf("RefreshTabletsByShard: failed to refresh %v: %v", ti.AliasString(), err) } cancel() wg.Done() }(ti) } wg.Wait() return nil }
[ "func", "(", "wr", "*", "Wrangler", ")", "RefreshTabletsByShard", "(", "ctx", "context", ".", "Context", ",", "si", "*", "topo", ".", "ShardInfo", ",", "tabletTypes", "[", "]", "topodatapb", ".", "TabletType", ",", "cells", "[", "]", "string", ")", "error", "{", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ")", "\n", "tabletMap", ",", "err", ":=", "wr", ".", "ts", ".", "GetTabletMapForShardByCell", "(", "ctx", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "cells", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "// keep going", "case", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "PartialResult", ")", ":", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ")", "\n", "default", ":", "return", "err", "\n", "}", "\n\n", "// ignore errors in this phase", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "for", "_", ",", "ti", ":=", "range", "tabletMap", "{", "if", "tabletTypes", "!=", "nil", "&&", "!", "topoproto", ".", "IsTypeInList", "(", "ti", ".", "Type", ",", "tabletTypes", ")", "{", "continue", "\n", "}", "\n", "if", "ti", ".", "Hostname", "==", "\"", "\"", "{", "// The tablet is not running, we don't have the host", "// name to connect to, so we just skip this tablet.", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "ti", ".", "AliasString", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "ti", "*", "topo", ".", "TabletInfo", ")", "{", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "ti", ".", "AliasString", "(", ")", ")", "\n", "// Setting an upper bound timeout to fail faster in case of an error.", "// Using 60 seconds because RefreshState should not take more than 30 seconds.", "// (RefreshState will restart the tablet's QueryService and most time will be spent on the shutdown, i.e. waiting up to 30 seconds on transactions (see Config.TransactionTimeout)).", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "60", "*", "time", ".", "Second", ")", "\n", "if", "err", ":=", "wr", ".", "tmc", ".", "RefreshState", "(", "ctx", ",", "ti", ".", "Tablet", ")", ";", "err", "!=", "nil", "{", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "ti", ".", "AliasString", "(", ")", ",", "err", ")", "\n", "}", "\n", "cancel", "(", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", "ti", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// RefreshTabletsByShard calls RefreshState on all the tables of a // given type in a shard. It would work for the master, but the // discovery wouldn't be very efficient.
[ "RefreshTabletsByShard", "calls", "RefreshState", "on", "all", "the", "tables", "of", "a", "given", "type", "in", "a", "shard", ".", "It", "would", "work", "for", "the", "master", "but", "the", "discovery", "wouldn", "t", "be", "very", "efficient", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L1318-L1360
train
vitessio/vitess
go/vt/wrangler/keyspace.go
DeleteKeyspace
func (wr *Wrangler) DeleteKeyspace(ctx context.Context, keyspace string, recursive bool) error { shards, err := wr.ts.GetShardNames(ctx, keyspace) if err != nil { return err } if recursive { wr.Logger().Infof("Deleting all shards (and their tablets) in keyspace %v", keyspace) for _, shard := range shards { wr.Logger().Infof("Recursively deleting shard %v/%v", keyspace, shard) if err := wr.DeleteShard(ctx, keyspace, shard, true /* recursive */, true /* evenIfServing */); err != nil && !topo.IsErrType(err, topo.NoNode) { // Unlike the errors below in non-recursive steps, we don't want to // continue if a DeleteShard fails. If we continue and delete the // keyspace, the tablet records will be orphaned, since we'll // no longer know how to list out the shard they belong to. // // If the problem is temporary, or resolved externally, re-running // DeleteKeyspace will skip over shards that were already deleted. return fmt.Errorf("can't delete shard %v/%v: %v", keyspace, shard, err) } } } else if len(shards) > 0 { return fmt.Errorf("keyspace %v still has %v shards; use -recursive or remove them manually", keyspace, len(shards)) } // Delete the cell-local keyspace entries. cells, err := wr.ts.GetKnownCells(ctx) if err != nil { return err } for _, cell := range cells { if err := wr.ts.DeleteKeyspaceReplication(ctx, cell, keyspace); err != nil && !topo.IsErrType(err, topo.NoNode) { wr.Logger().Warningf("Cannot delete KeyspaceReplication in cell %v for %v: %v", cell, keyspace, err) } if err := wr.ts.DeleteSrvKeyspace(ctx, cell, keyspace); err != nil && !topo.IsErrType(err, topo.NoNode) { wr.Logger().Warningf("Cannot delete SrvKeyspace in cell %v for %v: %v", cell, keyspace, err) } } // Delete the cell-global VSchema path // If not remove this, vtctld web page Dashboard will Display Error vschema := &vschemapb.Keyspace{} if err := wr.ts.SaveVSchema(ctx, keyspace, vschema); err != nil && !topo.IsErrType(err, topo.NoNode) { return err } return wr.ts.DeleteKeyspace(ctx, keyspace) }
go
func (wr *Wrangler) DeleteKeyspace(ctx context.Context, keyspace string, recursive bool) error { shards, err := wr.ts.GetShardNames(ctx, keyspace) if err != nil { return err } if recursive { wr.Logger().Infof("Deleting all shards (and their tablets) in keyspace %v", keyspace) for _, shard := range shards { wr.Logger().Infof("Recursively deleting shard %v/%v", keyspace, shard) if err := wr.DeleteShard(ctx, keyspace, shard, true /* recursive */, true /* evenIfServing */); err != nil && !topo.IsErrType(err, topo.NoNode) { // Unlike the errors below in non-recursive steps, we don't want to // continue if a DeleteShard fails. If we continue and delete the // keyspace, the tablet records will be orphaned, since we'll // no longer know how to list out the shard they belong to. // // If the problem is temporary, or resolved externally, re-running // DeleteKeyspace will skip over shards that were already deleted. return fmt.Errorf("can't delete shard %v/%v: %v", keyspace, shard, err) } } } else if len(shards) > 0 { return fmt.Errorf("keyspace %v still has %v shards; use -recursive or remove them manually", keyspace, len(shards)) } // Delete the cell-local keyspace entries. cells, err := wr.ts.GetKnownCells(ctx) if err != nil { return err } for _, cell := range cells { if err := wr.ts.DeleteKeyspaceReplication(ctx, cell, keyspace); err != nil && !topo.IsErrType(err, topo.NoNode) { wr.Logger().Warningf("Cannot delete KeyspaceReplication in cell %v for %v: %v", cell, keyspace, err) } if err := wr.ts.DeleteSrvKeyspace(ctx, cell, keyspace); err != nil && !topo.IsErrType(err, topo.NoNode) { wr.Logger().Warningf("Cannot delete SrvKeyspace in cell %v for %v: %v", cell, keyspace, err) } } // Delete the cell-global VSchema path // If not remove this, vtctld web page Dashboard will Display Error vschema := &vschemapb.Keyspace{} if err := wr.ts.SaveVSchema(ctx, keyspace, vschema); err != nil && !topo.IsErrType(err, topo.NoNode) { return err } return wr.ts.DeleteKeyspace(ctx, keyspace) }
[ "func", "(", "wr", "*", "Wrangler", ")", "DeleteKeyspace", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "recursive", "bool", ")", "error", "{", "shards", ",", "err", ":=", "wr", ".", "ts", ".", "GetShardNames", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "recursive", "{", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "keyspace", ")", "\n", "for", "_", ",", "shard", ":=", "range", "shards", "{", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", ":=", "wr", ".", "DeleteShard", "(", "ctx", ",", "keyspace", ",", "shard", ",", "true", "/* recursive */", ",", "true", "/* evenIfServing */", ")", ";", "err", "!=", "nil", "&&", "!", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NoNode", ")", "{", "// Unlike the errors below in non-recursive steps, we don't want to", "// continue if a DeleteShard fails. If we continue and delete the", "// keyspace, the tablet records will be orphaned, since we'll", "// no longer know how to list out the shard they belong to.", "//", "// If the problem is temporary, or resolved externally, re-running", "// DeleteKeyspace will skip over shards that were already deleted.", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "else", "if", "len", "(", "shards", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "len", "(", "shards", ")", ")", "\n", "}", "\n\n", "// Delete the cell-local keyspace entries.", "cells", ",", "err", ":=", "wr", ".", "ts", ".", "GetKnownCells", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "cell", ":=", "range", "cells", "{", "if", "err", ":=", "wr", ".", "ts", ".", "DeleteKeyspaceReplication", "(", "ctx", ",", "cell", ",", "keyspace", ")", ";", "err", "!=", "nil", "&&", "!", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NoNode", ")", "{", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "cell", ",", "keyspace", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "wr", ".", "ts", ".", "DeleteSrvKeyspace", "(", "ctx", ",", "cell", ",", "keyspace", ")", ";", "err", "!=", "nil", "&&", "!", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NoNode", ")", "{", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "cell", ",", "keyspace", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Delete the cell-global VSchema path", "// If not remove this, vtctld web page Dashboard will Display Error", "vschema", ":=", "&", "vschemapb", ".", "Keyspace", "{", "}", "\n", "if", "err", ":=", "wr", ".", "ts", ".", "SaveVSchema", "(", "ctx", ",", "keyspace", ",", "vschema", ")", ";", "err", "!=", "nil", "&&", "!", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NoNode", ")", "{", "return", "err", "\n", "}", "\n\n", "return", "wr", ".", "ts", ".", "DeleteKeyspace", "(", "ctx", ",", "keyspace", ")", "\n", "}" ]
// DeleteKeyspace will do all the necessary changes in the topology server // to entirely remove a keyspace.
[ "DeleteKeyspace", "will", "do", "all", "the", "necessary", "changes", "in", "the", "topology", "server", "to", "entirely", "remove", "a", "keyspace", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/keyspace.go#L1364-L1411
train
vitessio/vitess
go/mysql/fakesqldb/server.go
New
func New(t *testing.T) *DB { // Pick a path for our socket. socketDir, err := ioutil.TempDir("", "fakesqldb") if err != nil { t.Fatalf("ioutil.TempDir failed: %v", err) } socketFile := path.Join(socketDir, "fakesqldb.sock") // Create our DB. db := &DB{ t: t, socketFile: socketFile, name: "fakesqldb", data: make(map[string]*ExpectedResult), rejectedData: make(map[string]error), queryCalled: make(map[string]int), connections: make(map[uint32]*mysql.Conn), } db.Handler = db authServer := &mysql.AuthServerNone{} // Start listening. db.listener, err = mysql.NewListener("unix", socketFile, authServer, db, 0, 0) if err != nil { t.Fatalf("NewListener failed: %v", err) } db.acceptWG.Add(1) go func() { defer db.acceptWG.Done() db.listener.Accept() }() // Return the db. return db }
go
func New(t *testing.T) *DB { // Pick a path for our socket. socketDir, err := ioutil.TempDir("", "fakesqldb") if err != nil { t.Fatalf("ioutil.TempDir failed: %v", err) } socketFile := path.Join(socketDir, "fakesqldb.sock") // Create our DB. db := &DB{ t: t, socketFile: socketFile, name: "fakesqldb", data: make(map[string]*ExpectedResult), rejectedData: make(map[string]error), queryCalled: make(map[string]int), connections: make(map[uint32]*mysql.Conn), } db.Handler = db authServer := &mysql.AuthServerNone{} // Start listening. db.listener, err = mysql.NewListener("unix", socketFile, authServer, db, 0, 0) if err != nil { t.Fatalf("NewListener failed: %v", err) } db.acceptWG.Add(1) go func() { defer db.acceptWG.Done() db.listener.Accept() }() // Return the db. return db }
[ "func", "New", "(", "t", "*", "testing", ".", "T", ")", "*", "DB", "{", "// Pick a path for our socket.", "socketDir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "socketFile", ":=", "path", ".", "Join", "(", "socketDir", ",", "\"", "\"", ")", "\n\n", "// Create our DB.", "db", ":=", "&", "DB", "{", "t", ":", "t", ",", "socketFile", ":", "socketFile", ",", "name", ":", "\"", "\"", ",", "data", ":", "make", "(", "map", "[", "string", "]", "*", "ExpectedResult", ")", ",", "rejectedData", ":", "make", "(", "map", "[", "string", "]", "error", ")", ",", "queryCalled", ":", "make", "(", "map", "[", "string", "]", "int", ")", ",", "connections", ":", "make", "(", "map", "[", "uint32", "]", "*", "mysql", ".", "Conn", ")", ",", "}", "\n\n", "db", ".", "Handler", "=", "db", "\n\n", "authServer", ":=", "&", "mysql", ".", "AuthServerNone", "{", "}", "\n\n", "// Start listening.", "db", ".", "listener", ",", "err", "=", "mysql", ".", "NewListener", "(", "\"", "\"", ",", "socketFile", ",", "authServer", ",", "db", ",", "0", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "db", ".", "acceptWG", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "db", ".", "acceptWG", ".", "Done", "(", ")", "\n", "db", ".", "listener", ".", "Accept", "(", ")", "\n", "}", "(", ")", "\n\n", "// Return the db.", "return", "db", "\n", "}" ]
// New creates a server, and starts listening.
[ "New", "creates", "a", "server", "and", "starts", "listening", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L143-L180
train
vitessio/vitess
go/mysql/fakesqldb/server.go
SetName
func (db *DB) SetName(name string) *DB { db.mu.Lock() defer db.mu.Unlock() db.name = name return db }
go
func (db *DB) SetName(name string) *DB { db.mu.Lock() defer db.mu.Unlock() db.name = name return db }
[ "func", "(", "db", "*", "DB", ")", "SetName", "(", "name", "string", ")", "*", "DB", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "db", ".", "name", "=", "name", "\n", "return", "db", "\n", "}" ]
// SetName sets the name of the DB. to differentiate them in tests if needed.
[ "SetName", "sets", "the", "name", "of", "the", "DB", ".", "to", "differentiate", "them", "in", "tests", "if", "needed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L183-L189
train
vitessio/vitess
go/mysql/fakesqldb/server.go
OrderMatters
func (db *DB) OrderMatters() *DB { db.mu.Lock() defer db.mu.Unlock() db.orderMatters = true return db }
go
func (db *DB) OrderMatters() *DB { db.mu.Lock() defer db.mu.Unlock() db.orderMatters = true return db }
[ "func", "(", "db", "*", "DB", ")", "OrderMatters", "(", ")", "*", "DB", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "db", ".", "orderMatters", "=", "true", "\n", "return", "db", "\n", "}" ]
// OrderMatters sets the orderMatters flag.
[ "OrderMatters", "sets", "the", "orderMatters", "flag", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L192-L198
train
vitessio/vitess
go/mysql/fakesqldb/server.go
Close
func (db *DB) Close() { db.listener.Close() db.acceptWG.Wait() db.CloseAllConnections() tmpDir := path.Dir(db.socketFile) os.RemoveAll(tmpDir) }
go
func (db *DB) Close() { db.listener.Close() db.acceptWG.Wait() db.CloseAllConnections() tmpDir := path.Dir(db.socketFile) os.RemoveAll(tmpDir) }
[ "func", "(", "db", "*", "DB", ")", "Close", "(", ")", "{", "db", ".", "listener", ".", "Close", "(", ")", "\n", "db", ".", "acceptWG", ".", "Wait", "(", ")", "\n\n", "db", ".", "CloseAllConnections", "(", ")", "\n\n", "tmpDir", ":=", "path", ".", "Dir", "(", "db", ".", "socketFile", ")", "\n", "os", ".", "RemoveAll", "(", "tmpDir", ")", "\n", "}" ]
// Close closes the Listener and waits for it to stop accepting. // It then closes all connections, and cleans up the temporary directory.
[ "Close", "closes", "the", "Listener", "and", "waits", "for", "it", "to", "stop", "accepting", ".", "It", "then", "closes", "all", "connections", "and", "cleans", "up", "the", "temporary", "directory", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L202-L210
train
vitessio/vitess
go/mysql/fakesqldb/server.go
ConnParams
func (db *DB) ConnParams() *mysql.ConnParams { return &mysql.ConnParams{ UnixSocket: db.socketFile, Uname: "user1", Pass: "password1", Charset: "utf8", } }
go
func (db *DB) ConnParams() *mysql.ConnParams { return &mysql.ConnParams{ UnixSocket: db.socketFile, Uname: "user1", Pass: "password1", Charset: "utf8", } }
[ "func", "(", "db", "*", "DB", ")", "ConnParams", "(", ")", "*", "mysql", ".", "ConnParams", "{", "return", "&", "mysql", ".", "ConnParams", "{", "UnixSocket", ":", "db", ".", "socketFile", ",", "Uname", ":", "\"", "\"", ",", "Pass", ":", "\"", "\"", ",", "Charset", ":", "\"", "\"", ",", "}", "\n", "}" ]
// ConnParams returns the ConnParams to connect to the DB.
[ "ConnParams", "returns", "the", "ConnParams", "to", "connect", "to", "the", "DB", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L257-L264
train
vitessio/vitess
go/mysql/fakesqldb/server.go
ConnParamsWithUname
func (db *DB) ConnParamsWithUname(uname string) *mysql.ConnParams { return &mysql.ConnParams{ UnixSocket: db.socketFile, Uname: uname, Pass: "password1", Charset: "utf8", } }
go
func (db *DB) ConnParamsWithUname(uname string) *mysql.ConnParams { return &mysql.ConnParams{ UnixSocket: db.socketFile, Uname: uname, Pass: "password1", Charset: "utf8", } }
[ "func", "(", "db", "*", "DB", ")", "ConnParamsWithUname", "(", "uname", "string", ")", "*", "mysql", ".", "ConnParams", "{", "return", "&", "mysql", ".", "ConnParams", "{", "UnixSocket", ":", "db", ".", "socketFile", ",", "Uname", ":", "uname", ",", "Pass", ":", "\"", "\"", ",", "Charset", ":", "\"", "\"", ",", "}", "\n", "}" ]
// ConnParamsWithUname returns ConnParams to connect to the DB with the Uname set to the provided value.
[ "ConnParamsWithUname", "returns", "ConnParams", "to", "connect", "to", "the", "DB", "with", "the", "Uname", "set", "to", "the", "provided", "value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L267-L274
train
vitessio/vitess
go/mysql/fakesqldb/server.go
NewConnection
func (db *DB) NewConnection(c *mysql.Conn) { db.mu.Lock() defer db.mu.Unlock() if db.t != nil { db.t.Logf("NewConnection(%v): client %v", db.name, c.ConnectionID) } if db.isConnFail { panic(fmt.Errorf("simulating a connection failure")) } if db.connDelay != 0 { time.Sleep(db.connDelay) } if conn, ok := db.connections[c.ConnectionID]; ok { db.t.Fatalf("BUG: connection with id: %v is already active. existing conn: %v new conn: %v", c.ConnectionID, conn, c) } db.connections[c.ConnectionID] = c }
go
func (db *DB) NewConnection(c *mysql.Conn) { db.mu.Lock() defer db.mu.Unlock() if db.t != nil { db.t.Logf("NewConnection(%v): client %v", db.name, c.ConnectionID) } if db.isConnFail { panic(fmt.Errorf("simulating a connection failure")) } if db.connDelay != 0 { time.Sleep(db.connDelay) } if conn, ok := db.connections[c.ConnectionID]; ok { db.t.Fatalf("BUG: connection with id: %v is already active. existing conn: %v new conn: %v", c.ConnectionID, conn, c) } db.connections[c.ConnectionID] = c }
[ "func", "(", "db", "*", "DB", ")", "NewConnection", "(", "c", "*", "mysql", ".", "Conn", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "db", ".", "t", "!=", "nil", "{", "db", ".", "t", ".", "Logf", "(", "\"", "\"", ",", "db", ".", "name", ",", "c", ".", "ConnectionID", ")", "\n", "}", "\n\n", "if", "db", ".", "isConnFail", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "db", ".", "connDelay", "!=", "0", "{", "time", ".", "Sleep", "(", "db", ".", "connDelay", ")", "\n", "}", "\n\n", "if", "conn", ",", "ok", ":=", "db", ".", "connections", "[", "c", ".", "ConnectionID", "]", ";", "ok", "{", "db", ".", "t", ".", "Fatalf", "(", "\"", "\"", ",", "c", ".", "ConnectionID", ",", "conn", ",", "c", ")", "\n", "}", "\n", "db", ".", "connections", "[", "c", ".", "ConnectionID", "]", "=", "c", "\n", "}" ]
// // mysql.Handler interface // // NewConnection is part of the mysql.Handler interface.
[ "mysql", ".", "Handler", "interface", "NewConnection", "is", "part", "of", "the", "mysql", ".", "Handler", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L281-L301
train
vitessio/vitess
go/mysql/fakesqldb/server.go
ConnectionClosed
func (db *DB) ConnectionClosed(c *mysql.Conn) { db.mu.Lock() defer db.mu.Unlock() if db.t != nil { db.t.Logf("ConnectionClosed(%v): client %v", db.name, c.ConnectionID) } if _, ok := db.connections[c.ConnectionID]; !ok { db.t.Fatalf("BUG: Cannot delete connection from list of open connections because it is not registered. ID: %v Conn: %v", c.ConnectionID, c) } delete(db.connections, c.ConnectionID) }
go
func (db *DB) ConnectionClosed(c *mysql.Conn) { db.mu.Lock() defer db.mu.Unlock() if db.t != nil { db.t.Logf("ConnectionClosed(%v): client %v", db.name, c.ConnectionID) } if _, ok := db.connections[c.ConnectionID]; !ok { db.t.Fatalf("BUG: Cannot delete connection from list of open connections because it is not registered. ID: %v Conn: %v", c.ConnectionID, c) } delete(db.connections, c.ConnectionID) }
[ "func", "(", "db", "*", "DB", ")", "ConnectionClosed", "(", "c", "*", "mysql", ".", "Conn", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "db", ".", "t", "!=", "nil", "{", "db", ".", "t", ".", "Logf", "(", "\"", "\"", ",", "db", ".", "name", ",", "c", ".", "ConnectionID", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "db", ".", "connections", "[", "c", ".", "ConnectionID", "]", ";", "!", "ok", "{", "db", ".", "t", ".", "Fatalf", "(", "\"", "\"", ",", "c", ".", "ConnectionID", ",", "c", ")", "\n", "}", "\n", "delete", "(", "db", ".", "connections", ",", "c", ".", "ConnectionID", ")", "\n", "}" ]
// ConnectionClosed is part of the mysql.Handler interface.
[ "ConnectionClosed", "is", "part", "of", "the", "mysql", ".", "Handler", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L304-L316
train
vitessio/vitess
go/mysql/fakesqldb/server.go
ComQuery
func (db *DB) ComQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error { return db.Handler.HandleQuery(c, query, callback) }
go
func (db *DB) ComQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error { return db.Handler.HandleQuery(c, query, callback) }
[ "func", "(", "db", "*", "DB", ")", "ComQuery", "(", "c", "*", "mysql", ".", "Conn", ",", "query", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "return", "db", ".", "Handler", ".", "HandleQuery", "(", "c", ",", "query", ",", "callback", ")", "\n", "}" ]
// ComQuery is part of the mysql.Handler interface.
[ "ComQuery", "is", "part", "of", "the", "mysql", ".", "Handler", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L319-L321
train
vitessio/vitess
go/mysql/fakesqldb/server.go
HandleQuery
func (db *DB) HandleQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error { if db.AllowAll { return callback(&sqltypes.Result{}) } if db.t != nil { db.t.Logf("ComQuery(%v): client %v: %v", db.name, c.ConnectionID, query) } if db.orderMatters { result, err := db.comQueryOrdered(query) if err != nil { return err } return callback(result) } key := strings.ToLower(query) db.mu.Lock() defer db.mu.Unlock() db.queryCalled[key]++ // Check if we should close the connection and provoke errno 2013. if db.shouldClose { c.Close() callback(&sqltypes.Result{}) return nil } // Using special handling for 'SET NAMES utf8'. The driver // may send this at connection time, and we don't want it to // interfere. if key == "set names utf8" { callback(&sqltypes.Result{}) return nil } // check if we should reject it. if err, ok := db.rejectedData[key]; ok { return err } // Check explicit queries from AddQuery(). result, ok := db.data[key] if ok { if f := result.BeforeFunc; f != nil { f() } return callback(result.Result) } // Check query patterns from AddQueryPattern(). for _, pat := range db.patternData { if pat.expr.MatchString(query) { return callback(pat.result) } } // Nothing matched. return fmt.Errorf("query: '%s' is not supported on %v", query, db.name) }
go
func (db *DB) HandleQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error { if db.AllowAll { return callback(&sqltypes.Result{}) } if db.t != nil { db.t.Logf("ComQuery(%v): client %v: %v", db.name, c.ConnectionID, query) } if db.orderMatters { result, err := db.comQueryOrdered(query) if err != nil { return err } return callback(result) } key := strings.ToLower(query) db.mu.Lock() defer db.mu.Unlock() db.queryCalled[key]++ // Check if we should close the connection and provoke errno 2013. if db.shouldClose { c.Close() callback(&sqltypes.Result{}) return nil } // Using special handling for 'SET NAMES utf8'. The driver // may send this at connection time, and we don't want it to // interfere. if key == "set names utf8" { callback(&sqltypes.Result{}) return nil } // check if we should reject it. if err, ok := db.rejectedData[key]; ok { return err } // Check explicit queries from AddQuery(). result, ok := db.data[key] if ok { if f := result.BeforeFunc; f != nil { f() } return callback(result.Result) } // Check query patterns from AddQueryPattern(). for _, pat := range db.patternData { if pat.expr.MatchString(query) { return callback(pat.result) } } // Nothing matched. return fmt.Errorf("query: '%s' is not supported on %v", query, db.name) }
[ "func", "(", "db", "*", "DB", ")", "HandleQuery", "(", "c", "*", "mysql", ".", "Conn", ",", "query", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "if", "db", ".", "AllowAll", "{", "return", "callback", "(", "&", "sqltypes", ".", "Result", "{", "}", ")", "\n", "}", "\n\n", "if", "db", ".", "t", "!=", "nil", "{", "db", ".", "t", ".", "Logf", "(", "\"", "\"", ",", "db", ".", "name", ",", "c", ".", "ConnectionID", ",", "query", ")", "\n", "}", "\n", "if", "db", ".", "orderMatters", "{", "result", ",", "err", ":=", "db", ".", "comQueryOrdered", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "callback", "(", "result", ")", "\n", "}", "\n\n", "key", ":=", "strings", ".", "ToLower", "(", "query", ")", "\n", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "db", ".", "queryCalled", "[", "key", "]", "++", "\n\n", "// Check if we should close the connection and provoke errno 2013.", "if", "db", ".", "shouldClose", "{", "c", ".", "Close", "(", ")", "\n", "callback", "(", "&", "sqltypes", ".", "Result", "{", "}", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Using special handling for 'SET NAMES utf8'. The driver", "// may send this at connection time, and we don't want it to", "// interfere.", "if", "key", "==", "\"", "\"", "{", "callback", "(", "&", "sqltypes", ".", "Result", "{", "}", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// check if we should reject it.", "if", "err", ",", "ok", ":=", "db", ".", "rejectedData", "[", "key", "]", ";", "ok", "{", "return", "err", "\n", "}", "\n\n", "// Check explicit queries from AddQuery().", "result", ",", "ok", ":=", "db", ".", "data", "[", "key", "]", "\n", "if", "ok", "{", "if", "f", ":=", "result", ".", "BeforeFunc", ";", "f", "!=", "nil", "{", "f", "(", ")", "\n", "}", "\n", "return", "callback", "(", "result", ".", "Result", ")", "\n", "}", "\n\n", "// Check query patterns from AddQueryPattern().", "for", "_", ",", "pat", ":=", "range", "db", ".", "patternData", "{", "if", "pat", ".", "expr", ".", "MatchString", "(", "query", ")", "{", "return", "callback", "(", "pat", ".", "result", ")", "\n", "}", "\n", "}", "\n\n", "// Nothing matched.", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "query", ",", "db", ".", "name", ")", "\n", "}" ]
// HandleQuery is the default implementation of the QueryHandler interface
[ "HandleQuery", "is", "the", "default", "implementation", "of", "the", "QueryHandler", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L329-L388
train
vitessio/vitess
go/mysql/fakesqldb/server.go
AddQuery
func (db *DB) AddQuery(query string, expectedResult *sqltypes.Result) *ExpectedResult { if len(expectedResult.Rows) > 0 && len(expectedResult.Fields) == 0 { panic(fmt.Errorf("please add Fields to this Result so it's valid: %v", query)) } resultCopy := &sqltypes.Result{} *resultCopy = *expectedResult db.mu.Lock() defer db.mu.Unlock() key := strings.ToLower(query) r := &ExpectedResult{resultCopy, nil} db.data[key] = r db.queryCalled[key] = 0 return r }
go
func (db *DB) AddQuery(query string, expectedResult *sqltypes.Result) *ExpectedResult { if len(expectedResult.Rows) > 0 && len(expectedResult.Fields) == 0 { panic(fmt.Errorf("please add Fields to this Result so it's valid: %v", query)) } resultCopy := &sqltypes.Result{} *resultCopy = *expectedResult db.mu.Lock() defer db.mu.Unlock() key := strings.ToLower(query) r := &ExpectedResult{resultCopy, nil} db.data[key] = r db.queryCalled[key] = 0 return r }
[ "func", "(", "db", "*", "DB", ")", "AddQuery", "(", "query", "string", ",", "expectedResult", "*", "sqltypes", ".", "Result", ")", "*", "ExpectedResult", "{", "if", "len", "(", "expectedResult", ".", "Rows", ")", ">", "0", "&&", "len", "(", "expectedResult", ".", "Fields", ")", "==", "0", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "query", ")", ")", "\n", "}", "\n", "resultCopy", ":=", "&", "sqltypes", ".", "Result", "{", "}", "\n", "*", "resultCopy", "=", "*", "expectedResult", "\n", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "key", ":=", "strings", ".", "ToLower", "(", "query", ")", "\n", "r", ":=", "&", "ExpectedResult", "{", "resultCopy", ",", "nil", "}", "\n", "db", ".", "data", "[", "key", "]", "=", "r", "\n", "db", ".", "queryCalled", "[", "key", "]", "=", "0", "\n", "return", "r", "\n", "}" ]
// // Methods to add expected queries and results. // // AddQuery adds a query and its expected result.
[ "Methods", "to", "add", "expected", "queries", "and", "results", ".", "AddQuery", "adds", "a", "query", "and", "its", "expected", "result", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L440-L453
train
vitessio/vitess
go/mysql/fakesqldb/server.go
SetBeforeFunc
func (db *DB) SetBeforeFunc(query string, f func()) { db.mu.Lock() defer db.mu.Unlock() key := strings.ToLower(query) r, ok := db.data[key] if !ok { db.t.Fatalf("BUG: no query registered for: %v", query) } r.BeforeFunc = f }
go
func (db *DB) SetBeforeFunc(query string, f func()) { db.mu.Lock() defer db.mu.Unlock() key := strings.ToLower(query) r, ok := db.data[key] if !ok { db.t.Fatalf("BUG: no query registered for: %v", query) } r.BeforeFunc = f }
[ "func", "(", "db", "*", "DB", ")", "SetBeforeFunc", "(", "query", "string", ",", "f", "func", "(", ")", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "key", ":=", "strings", ".", "ToLower", "(", "query", ")", "\n", "r", ",", "ok", ":=", "db", ".", "data", "[", "key", "]", "\n", "if", "!", "ok", "{", "db", ".", "t", ".", "Fatalf", "(", "\"", "\"", ",", "query", ")", "\n", "}", "\n\n", "r", ".", "BeforeFunc", "=", "f", "\n", "}" ]
// SetBeforeFunc sets the BeforeFunc field for the previously registered "query".
[ "SetBeforeFunc", "sets", "the", "BeforeFunc", "field", "for", "the", "previously", "registered", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L456-L466
train
vitessio/vitess
go/mysql/fakesqldb/server.go
DeleteQuery
func (db *DB) DeleteQuery(query string) { db.mu.Lock() defer db.mu.Unlock() key := strings.ToLower(query) delete(db.data, key) delete(db.queryCalled, key) }
go
func (db *DB) DeleteQuery(query string) { db.mu.Lock() defer db.mu.Unlock() key := strings.ToLower(query) delete(db.data, key) delete(db.queryCalled, key) }
[ "func", "(", "db", "*", "DB", ")", "DeleteQuery", "(", "query", "string", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "key", ":=", "strings", ".", "ToLower", "(", "query", ")", "\n", "delete", "(", "db", ".", "data", ",", "key", ")", "\n", "delete", "(", "db", ".", "queryCalled", ",", "key", ")", "\n", "}" ]
// DeleteQuery deletes query from the fake DB.
[ "DeleteQuery", "deletes", "query", "from", "the", "fake", "DB", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L484-L490
train
vitessio/vitess
go/mysql/fakesqldb/server.go
AddRejectedQuery
func (db *DB) AddRejectedQuery(query string, err error) { db.mu.Lock() defer db.mu.Unlock() db.rejectedData[strings.ToLower(query)] = err }
go
func (db *DB) AddRejectedQuery(query string, err error) { db.mu.Lock() defer db.mu.Unlock() db.rejectedData[strings.ToLower(query)] = err }
[ "func", "(", "db", "*", "DB", ")", "AddRejectedQuery", "(", "query", "string", ",", "err", "error", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "db", ".", "rejectedData", "[", "strings", ".", "ToLower", "(", "query", ")", "]", "=", "err", "\n", "}" ]
// AddRejectedQuery adds a query which will be rejected at execution time.
[ "AddRejectedQuery", "adds", "a", "query", "which", "will", "be", "rejected", "at", "execution", "time", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L493-L497
train
vitessio/vitess
go/mysql/fakesqldb/server.go
DeleteRejectedQuery
func (db *DB) DeleteRejectedQuery(query string) { db.mu.Lock() defer db.mu.Unlock() delete(db.rejectedData, strings.ToLower(query)) }
go
func (db *DB) DeleteRejectedQuery(query string) { db.mu.Lock() defer db.mu.Unlock() delete(db.rejectedData, strings.ToLower(query)) }
[ "func", "(", "db", "*", "DB", ")", "DeleteRejectedQuery", "(", "query", "string", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "delete", "(", "db", ".", "rejectedData", ",", "strings", ".", "ToLower", "(", "query", ")", ")", "\n", "}" ]
// DeleteRejectedQuery deletes query from the fake DB.
[ "DeleteRejectedQuery", "deletes", "query", "from", "the", "fake", "DB", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L500-L504
train
vitessio/vitess
go/mysql/fakesqldb/server.go
GetQueryCalledNum
func (db *DB) GetQueryCalledNum(query string) int { db.mu.Lock() defer db.mu.Unlock() num, ok := db.queryCalled[strings.ToLower(query)] if !ok { return 0 } return num }
go
func (db *DB) GetQueryCalledNum(query string) int { db.mu.Lock() defer db.mu.Unlock() num, ok := db.queryCalled[strings.ToLower(query)] if !ok { return 0 } return num }
[ "func", "(", "db", "*", "DB", ")", "GetQueryCalledNum", "(", "query", "string", ")", "int", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "num", ",", "ok", ":=", "db", ".", "queryCalled", "[", "strings", ".", "ToLower", "(", "query", ")", "]", "\n", "if", "!", "ok", "{", "return", "0", "\n", "}", "\n", "return", "num", "\n", "}" ]
// GetQueryCalledNum returns how many times db executes a certain query.
[ "GetQueryCalledNum", "returns", "how", "many", "times", "db", "executes", "a", "certain", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L507-L515
train
vitessio/vitess
go/mysql/fakesqldb/server.go
EnableConnFail
func (db *DB) EnableConnFail() { db.mu.Lock() defer db.mu.Unlock() db.isConnFail = true }
go
func (db *DB) EnableConnFail() { db.mu.Lock() defer db.mu.Unlock() db.isConnFail = true }
[ "func", "(", "db", "*", "DB", ")", "EnableConnFail", "(", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "db", ".", "isConnFail", "=", "true", "\n", "}" ]
// EnableConnFail makes connection to this fake DB fail.
[ "EnableConnFail", "makes", "connection", "to", "this", "fake", "DB", "fail", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L518-L522
train
vitessio/vitess
go/mysql/fakesqldb/server.go
DisableConnFail
func (db *DB) DisableConnFail() { db.mu.Lock() defer db.mu.Unlock() db.isConnFail = false }
go
func (db *DB) DisableConnFail() { db.mu.Lock() defer db.mu.Unlock() db.isConnFail = false }
[ "func", "(", "db", "*", "DB", ")", "DisableConnFail", "(", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "db", ".", "isConnFail", "=", "false", "\n", "}" ]
// DisableConnFail makes connection to this fake DB success.
[ "DisableConnFail", "makes", "connection", "to", "this", "fake", "DB", "success", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L525-L529
train
vitessio/vitess
go/mysql/fakesqldb/server.go
SetConnDelay
func (db *DB) SetConnDelay(d time.Duration) { db.mu.Lock() defer db.mu.Unlock() db.connDelay = d }
go
func (db *DB) SetConnDelay(d time.Duration) { db.mu.Lock() defer db.mu.Unlock() db.connDelay = d }
[ "func", "(", "db", "*", "DB", ")", "SetConnDelay", "(", "d", "time", ".", "Duration", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "db", ".", "connDelay", "=", "d", "\n", "}" ]
// SetConnDelay delays connections to this fake DB for the given duration
[ "SetConnDelay", "delays", "connections", "to", "this", "fake", "DB", "for", "the", "given", "duration" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L532-L536
train
vitessio/vitess
go/mysql/fakesqldb/server.go
EnableShouldClose
func (db *DB) EnableShouldClose() { db.mu.Lock() defer db.mu.Unlock() db.shouldClose = true }
go
func (db *DB) EnableShouldClose() { db.mu.Lock() defer db.mu.Unlock() db.shouldClose = true }
[ "func", "(", "db", "*", "DB", ")", "EnableShouldClose", "(", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n", "db", ".", "shouldClose", "=", "true", "\n", "}" ]
// EnableShouldClose closes the connection when processing the next query.
[ "EnableShouldClose", "closes", "the", "connection", "when", "processing", "the", "next", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L539-L543
train
vitessio/vitess
go/mysql/fakesqldb/server.go
AddExpectedExecuteFetchAtIndex
func (db *DB) AddExpectedExecuteFetchAtIndex(index int, entry ExpectedExecuteFetch) { db.mu.Lock() defer db.mu.Unlock() if db.expectedExecuteFetch == nil || index < 0 || index >= len(db.expectedExecuteFetch) { index = appendEntry } if index == appendEntry { db.expectedExecuteFetch = append(db.expectedExecuteFetch, entry) } else { // Grow the slice by one element. if cap(db.expectedExecuteFetch) == len(db.expectedExecuteFetch) { db.expectedExecuteFetch = append(db.expectedExecuteFetch, make([]ExpectedExecuteFetch, 1)...) } else { db.expectedExecuteFetch = db.expectedExecuteFetch[0 : len(db.expectedExecuteFetch)+1] } // Use copy to move the upper part of the slice out of the way and open a hole. copy(db.expectedExecuteFetch[index+1:], db.expectedExecuteFetch[index:]) // Store the new value. db.expectedExecuteFetch[index] = entry } }
go
func (db *DB) AddExpectedExecuteFetchAtIndex(index int, entry ExpectedExecuteFetch) { db.mu.Lock() defer db.mu.Unlock() if db.expectedExecuteFetch == nil || index < 0 || index >= len(db.expectedExecuteFetch) { index = appendEntry } if index == appendEntry { db.expectedExecuteFetch = append(db.expectedExecuteFetch, entry) } else { // Grow the slice by one element. if cap(db.expectedExecuteFetch) == len(db.expectedExecuteFetch) { db.expectedExecuteFetch = append(db.expectedExecuteFetch, make([]ExpectedExecuteFetch, 1)...) } else { db.expectedExecuteFetch = db.expectedExecuteFetch[0 : len(db.expectedExecuteFetch)+1] } // Use copy to move the upper part of the slice out of the way and open a hole. copy(db.expectedExecuteFetch[index+1:], db.expectedExecuteFetch[index:]) // Store the new value. db.expectedExecuteFetch[index] = entry } }
[ "func", "(", "db", "*", "DB", ")", "AddExpectedExecuteFetchAtIndex", "(", "index", "int", ",", "entry", "ExpectedExecuteFetch", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "db", ".", "expectedExecuteFetch", "==", "nil", "||", "index", "<", "0", "||", "index", ">=", "len", "(", "db", ".", "expectedExecuteFetch", ")", "{", "index", "=", "appendEntry", "\n", "}", "\n", "if", "index", "==", "appendEntry", "{", "db", ".", "expectedExecuteFetch", "=", "append", "(", "db", ".", "expectedExecuteFetch", ",", "entry", ")", "\n", "}", "else", "{", "// Grow the slice by one element.", "if", "cap", "(", "db", ".", "expectedExecuteFetch", ")", "==", "len", "(", "db", ".", "expectedExecuteFetch", ")", "{", "db", ".", "expectedExecuteFetch", "=", "append", "(", "db", ".", "expectedExecuteFetch", ",", "make", "(", "[", "]", "ExpectedExecuteFetch", ",", "1", ")", "...", ")", "\n", "}", "else", "{", "db", ".", "expectedExecuteFetch", "=", "db", ".", "expectedExecuteFetch", "[", "0", ":", "len", "(", "db", ".", "expectedExecuteFetch", ")", "+", "1", "]", "\n", "}", "\n", "// Use copy to move the upper part of the slice out of the way and open a hole.", "copy", "(", "db", ".", "expectedExecuteFetch", "[", "index", "+", "1", ":", "]", ",", "db", ".", "expectedExecuteFetch", "[", "index", ":", "]", ")", "\n", "// Store the new value.", "db", ".", "expectedExecuteFetch", "[", "index", "]", "=", "entry", "\n", "}", "\n", "}" ]
// AddExpectedExecuteFetchAtIndex inserts a new entry at index. // index values start at 0.
[ "AddExpectedExecuteFetchAtIndex", "inserts", "a", "new", "entry", "at", "index", ".", "index", "values", "start", "at", "0", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L564-L585
train
vitessio/vitess
go/mysql/fakesqldb/server.go
AddExpectedQuery
func (db *DB) AddExpectedQuery(query string, err error) { db.AddExpectedExecuteFetch(ExpectedExecuteFetch{ Query: query, QueryResult: &sqltypes.Result{}, Error: err, }) }
go
func (db *DB) AddExpectedQuery(query string, err error) { db.AddExpectedExecuteFetch(ExpectedExecuteFetch{ Query: query, QueryResult: &sqltypes.Result{}, Error: err, }) }
[ "func", "(", "db", "*", "DB", ")", "AddExpectedQuery", "(", "query", "string", ",", "err", "error", ")", "{", "db", ".", "AddExpectedExecuteFetch", "(", "ExpectedExecuteFetch", "{", "Query", ":", "query", ",", "QueryResult", ":", "&", "sqltypes", ".", "Result", "{", "}", ",", "Error", ":", "err", ",", "}", ")", "\n", "}" ]
// AddExpectedQuery adds a single query with no result.
[ "AddExpectedQuery", "adds", "a", "single", "query", "with", "no", "result", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L588-L594
train
vitessio/vitess
go/mysql/fakesqldb/server.go
AddExpectedQueryAtIndex
func (db *DB) AddExpectedQueryAtIndex(index int, query string, err error) { db.AddExpectedExecuteFetchAtIndex(index, ExpectedExecuteFetch{ Query: query, QueryResult: &sqltypes.Result{}, Error: err, }) }
go
func (db *DB) AddExpectedQueryAtIndex(index int, query string, err error) { db.AddExpectedExecuteFetchAtIndex(index, ExpectedExecuteFetch{ Query: query, QueryResult: &sqltypes.Result{}, Error: err, }) }
[ "func", "(", "db", "*", "DB", ")", "AddExpectedQueryAtIndex", "(", "index", "int", ",", "query", "string", ",", "err", "error", ")", "{", "db", ".", "AddExpectedExecuteFetchAtIndex", "(", "index", ",", "ExpectedExecuteFetch", "{", "Query", ":", "query", ",", "QueryResult", ":", "&", "sqltypes", ".", "Result", "{", "}", ",", "Error", ":", "err", ",", "}", ")", "\n", "}" ]
// AddExpectedQueryAtIndex adds an expected ordered query at an index.
[ "AddExpectedQueryAtIndex", "adds", "an", "expected", "ordered", "query", "at", "an", "index", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L597-L603
train
vitessio/vitess
go/mysql/fakesqldb/server.go
GetEntry
func (db *DB) GetEntry(index int) *ExpectedExecuteFetch { db.mu.Lock() defer db.mu.Unlock() if index < 0 || index >= len(db.expectedExecuteFetch) { panic(fmt.Sprintf("index out of range. current length: %v", len(db.expectedExecuteFetch))) } return &db.expectedExecuteFetch[index] }
go
func (db *DB) GetEntry(index int) *ExpectedExecuteFetch { db.mu.Lock() defer db.mu.Unlock() if index < 0 || index >= len(db.expectedExecuteFetch) { panic(fmt.Sprintf("index out of range. current length: %v", len(db.expectedExecuteFetch))) } return &db.expectedExecuteFetch[index] }
[ "func", "(", "db", "*", "DB", ")", "GetEntry", "(", "index", "int", ")", "*", "ExpectedExecuteFetch", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "index", "<", "0", "||", "index", ">=", "len", "(", "db", ".", "expectedExecuteFetch", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "db", ".", "expectedExecuteFetch", ")", ")", ")", "\n", "}", "\n\n", "return", "&", "db", ".", "expectedExecuteFetch", "[", "index", "]", "\n", "}" ]
// GetEntry returns the expected entry at "index". If index is out of bounds, // the return value will be nil.
[ "GetEntry", "returns", "the", "expected", "entry", "at", "index", ".", "If", "index", "is", "out", "of", "bounds", "the", "return", "value", "will", "be", "nil", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L607-L616
train
vitessio/vitess
go/mysql/fakesqldb/server.go
DeleteAllEntries
func (db *DB) DeleteAllEntries() { db.mu.Lock() defer db.mu.Unlock() db.expectedExecuteFetch = make([]ExpectedExecuteFetch, 0) db.expectedExecuteFetchIndex = 0 }
go
func (db *DB) DeleteAllEntries() { db.mu.Lock() defer db.mu.Unlock() db.expectedExecuteFetch = make([]ExpectedExecuteFetch, 0) db.expectedExecuteFetchIndex = 0 }
[ "func", "(", "db", "*", "DB", ")", "DeleteAllEntries", "(", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "db", ".", "expectedExecuteFetch", "=", "make", "(", "[", "]", "ExpectedExecuteFetch", ",", "0", ")", "\n", "db", ".", "expectedExecuteFetchIndex", "=", "0", "\n", "}" ]
// DeleteAllEntries removes all ordered entries.
[ "DeleteAllEntries", "removes", "all", "ordered", "entries", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L619-L625
train
vitessio/vitess
go/mysql/fakesqldb/server.go
DeleteAllEntriesAfterIndex
func (db *DB) DeleteAllEntriesAfterIndex(index int) { db.mu.Lock() defer db.mu.Unlock() if index < 0 || index >= len(db.expectedExecuteFetch) { panic(fmt.Sprintf("index out of range. current length: %v", len(db.expectedExecuteFetch))) } if index+1 < db.expectedExecuteFetchIndex { // Don't delete entries which were already answered. return } db.expectedExecuteFetch = db.expectedExecuteFetch[:index+1] }
go
func (db *DB) DeleteAllEntriesAfterIndex(index int) { db.mu.Lock() defer db.mu.Unlock() if index < 0 || index >= len(db.expectedExecuteFetch) { panic(fmt.Sprintf("index out of range. current length: %v", len(db.expectedExecuteFetch))) } if index+1 < db.expectedExecuteFetchIndex { // Don't delete entries which were already answered. return } db.expectedExecuteFetch = db.expectedExecuteFetch[:index+1] }
[ "func", "(", "db", "*", "DB", ")", "DeleteAllEntriesAfterIndex", "(", "index", "int", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "index", "<", "0", "||", "index", ">=", "len", "(", "db", ".", "expectedExecuteFetch", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "db", ".", "expectedExecuteFetch", ")", ")", ")", "\n", "}", "\n\n", "if", "index", "+", "1", "<", "db", ".", "expectedExecuteFetchIndex", "{", "// Don't delete entries which were already answered.", "return", "\n", "}", "\n\n", "db", ".", "expectedExecuteFetch", "=", "db", ".", "expectedExecuteFetch", "[", ":", "index", "+", "1", "]", "\n", "}" ]
// DeleteAllEntriesAfterIndex removes all queries after the index.
[ "DeleteAllEntriesAfterIndex", "removes", "all", "queries", "after", "the", "index", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L628-L642
train
vitessio/vitess
go/mysql/fakesqldb/server.go
VerifyAllExecutedOrFail
func (db *DB) VerifyAllExecutedOrFail() { db.mu.Lock() defer db.mu.Unlock() if db.expectedExecuteFetchIndex != len(db.expectedExecuteFetch) { db.t.Errorf("%v: not all expected queries were executed. leftovers: %v", db.name, db.expectedExecuteFetch[db.expectedExecuteFetchIndex:]) } }
go
func (db *DB) VerifyAllExecutedOrFail() { db.mu.Lock() defer db.mu.Unlock() if db.expectedExecuteFetchIndex != len(db.expectedExecuteFetch) { db.t.Errorf("%v: not all expected queries were executed. leftovers: %v", db.name, db.expectedExecuteFetch[db.expectedExecuteFetchIndex:]) } }
[ "func", "(", "db", "*", "DB", ")", "VerifyAllExecutedOrFail", "(", ")", "{", "db", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "db", ".", "expectedExecuteFetchIndex", "!=", "len", "(", "db", ".", "expectedExecuteFetch", ")", "{", "db", ".", "t", ".", "Errorf", "(", "\"", "\"", ",", "db", ".", "name", ",", "db", ".", "expectedExecuteFetch", "[", "db", ".", "expectedExecuteFetchIndex", ":", "]", ")", "\n", "}", "\n", "}" ]
// VerifyAllExecutedOrFail checks that all expected queries where actually // received and executed. If not, it will let the test fail.
[ "VerifyAllExecutedOrFail", "checks", "that", "all", "expected", "queries", "where", "actually", "received", "and", "executed", ".", "If", "not", "it", "will", "let", "the", "test", "fail", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/fakesqldb/server.go#L646-L653
train
vitessio/vitess
go/vt/vtgate/engine/limit.go
MarshalJSON
func (l *Limit) MarshalJSON() ([]byte, error) { marshalLimit := struct { Opcode string Count sqltypes.PlanValue Offset sqltypes.PlanValue Input Primitive }{ Opcode: "Limit", Count: l.Count, Offset: l.Offset, Input: l.Input, } return json.Marshal(marshalLimit) }
go
func (l *Limit) MarshalJSON() ([]byte, error) { marshalLimit := struct { Opcode string Count sqltypes.PlanValue Offset sqltypes.PlanValue Input Primitive }{ Opcode: "Limit", Count: l.Count, Offset: l.Offset, Input: l.Input, } return json.Marshal(marshalLimit) }
[ "func", "(", "l", "*", "Limit", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "marshalLimit", ":=", "struct", "{", "Opcode", "string", "\n", "Count", "sqltypes", ".", "PlanValue", "\n", "Offset", "sqltypes", ".", "PlanValue", "\n", "Input", "Primitive", "\n", "}", "{", "Opcode", ":", "\"", "\"", ",", "Count", ":", "l", ".", "Count", ",", "Offset", ":", "l", ".", "Offset", ",", "Input", ":", "l", ".", "Input", ",", "}", "\n", "return", "json", ".", "Marshal", "(", "marshalLimit", ")", "\n", "}" ]
// MarshalJSON serializes the Limit into a JSON representation. // It's used for testing and diagnostics.
[ "MarshalJSON", "serializes", "the", "Limit", "into", "a", "JSON", "representation", ".", "It", "s", "used", "for", "testing", "and", "diagnostics", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/limit.go#L40-L53
train
vitessio/vitess
go/vt/vtgate/engine/limit.go
Execute
func (l *Limit) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) { count, err := l.fetchCount(bindVars) if err != nil { return nil, err } offset, err := l.fetchOffset(bindVars) if err != nil { return nil, err } // When offset is present, we hijack the limit value so we can calculate // the offset in memory from the result of the scatter query with count + offset. bindVars["__upper_limit"] = sqltypes.Int64BindVariable(int64(count + offset)) result, err := l.Input.Execute(vcursor, bindVars, wantfields) if err != nil { return nil, err } // There are more rows in the response than limit + offset if count+offset <= len(result.Rows) { result.Rows = result.Rows[offset : count+offset] result.RowsAffected = uint64(count) return result, nil } // Remove extra rows from response if offset <= len(result.Rows) { result.Rows = result.Rows[offset:] result.RowsAffected = uint64(len(result.Rows)) return result, nil } // offset is beyond the result set result.Rows = nil result.RowsAffected = 0 return result, nil }
go
func (l *Limit) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) { count, err := l.fetchCount(bindVars) if err != nil { return nil, err } offset, err := l.fetchOffset(bindVars) if err != nil { return nil, err } // When offset is present, we hijack the limit value so we can calculate // the offset in memory from the result of the scatter query with count + offset. bindVars["__upper_limit"] = sqltypes.Int64BindVariable(int64(count + offset)) result, err := l.Input.Execute(vcursor, bindVars, wantfields) if err != nil { return nil, err } // There are more rows in the response than limit + offset if count+offset <= len(result.Rows) { result.Rows = result.Rows[offset : count+offset] result.RowsAffected = uint64(count) return result, nil } // Remove extra rows from response if offset <= len(result.Rows) { result.Rows = result.Rows[offset:] result.RowsAffected = uint64(len(result.Rows)) return result, nil } // offset is beyond the result set result.Rows = nil result.RowsAffected = 0 return result, nil }
[ "func", "(", "l", "*", "Limit", ")", "Execute", "(", "vcursor", "VCursor", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "wantfields", "bool", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "count", ",", "err", ":=", "l", ".", "fetchCount", "(", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "offset", ",", "err", ":=", "l", ".", "fetchOffset", "(", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// When offset is present, we hijack the limit value so we can calculate", "// the offset in memory from the result of the scatter query with count + offset.", "bindVars", "[", "\"", "\"", "]", "=", "sqltypes", ".", "Int64BindVariable", "(", "int64", "(", "count", "+", "offset", ")", ")", "\n\n", "result", ",", "err", ":=", "l", ".", "Input", ".", "Execute", "(", "vcursor", ",", "bindVars", ",", "wantfields", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// There are more rows in the response than limit + offset", "if", "count", "+", "offset", "<=", "len", "(", "result", ".", "Rows", ")", "{", "result", ".", "Rows", "=", "result", ".", "Rows", "[", "offset", ":", "count", "+", "offset", "]", "\n", "result", ".", "RowsAffected", "=", "uint64", "(", "count", ")", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "// Remove extra rows from response", "if", "offset", "<=", "len", "(", "result", ".", "Rows", ")", "{", "result", ".", "Rows", "=", "result", ".", "Rows", "[", "offset", ":", "]", "\n", "result", ".", "RowsAffected", "=", "uint64", "(", "len", "(", "result", ".", "Rows", ")", ")", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "// offset is beyond the result set", "result", ".", "Rows", "=", "nil", "\n", "result", ".", "RowsAffected", "=", "0", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Execute satisfies the Primtive interface.
[ "Execute", "satisfies", "the", "Primtive", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/limit.go#L61-L95
train
vitessio/vitess
go/vt/vtgate/engine/limit.go
StreamExecute
func (l *Limit) StreamExecute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error { count, err := l.fetchCount(bindVars) if err != nil { return err } if !l.Offset.IsNull() { return fmt.Errorf("offset not supported for stream execute queries") } bindVars["__upper_limit"] = sqltypes.Int64BindVariable(int64(count)) err = l.Input.StreamExecute(vcursor, bindVars, wantfields, func(qr *sqltypes.Result) error { if len(qr.Fields) != 0 { if err := callback(&sqltypes.Result{Fields: qr.Fields}); err != nil { return err } } if len(qr.Rows) == 0 { return nil } if count == 0 { // Unreachable: this is just a failsafe. return io.EOF } // reduce count till 0. result := &sqltypes.Result{Rows: qr.Rows} if count > len(result.Rows) { count -= len(result.Rows) return callback(result) } result.Rows = result.Rows[:count] count = 0 if err := callback(result); err != nil { return err } return io.EOF }) if err == io.EOF { // We may get back the EOF we returned in the callback. // If so, suppress it. return nil } if err != nil { return err } return nil }
go
func (l *Limit) StreamExecute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error { count, err := l.fetchCount(bindVars) if err != nil { return err } if !l.Offset.IsNull() { return fmt.Errorf("offset not supported for stream execute queries") } bindVars["__upper_limit"] = sqltypes.Int64BindVariable(int64(count)) err = l.Input.StreamExecute(vcursor, bindVars, wantfields, func(qr *sqltypes.Result) error { if len(qr.Fields) != 0 { if err := callback(&sqltypes.Result{Fields: qr.Fields}); err != nil { return err } } if len(qr.Rows) == 0 { return nil } if count == 0 { // Unreachable: this is just a failsafe. return io.EOF } // reduce count till 0. result := &sqltypes.Result{Rows: qr.Rows} if count > len(result.Rows) { count -= len(result.Rows) return callback(result) } result.Rows = result.Rows[:count] count = 0 if err := callback(result); err != nil { return err } return io.EOF }) if err == io.EOF { // We may get back the EOF we returned in the callback. // If so, suppress it. return nil } if err != nil { return err } return nil }
[ "func", "(", "l", "*", "Limit", ")", "StreamExecute", "(", "vcursor", "VCursor", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "wantfields", "bool", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "count", ",", "err", ":=", "l", ".", "fetchCount", "(", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "l", ".", "Offset", ".", "IsNull", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "bindVars", "[", "\"", "\"", "]", "=", "sqltypes", ".", "Int64BindVariable", "(", "int64", "(", "count", ")", ")", "\n\n", "err", "=", "l", ".", "Input", ".", "StreamExecute", "(", "vcursor", ",", "bindVars", ",", "wantfields", ",", "func", "(", "qr", "*", "sqltypes", ".", "Result", ")", "error", "{", "if", "len", "(", "qr", ".", "Fields", ")", "!=", "0", "{", "if", "err", ":=", "callback", "(", "&", "sqltypes", ".", "Result", "{", "Fields", ":", "qr", ".", "Fields", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "len", "(", "qr", ".", "Rows", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "if", "count", "==", "0", "{", "// Unreachable: this is just a failsafe.", "return", "io", ".", "EOF", "\n", "}", "\n\n", "// reduce count till 0.", "result", ":=", "&", "sqltypes", ".", "Result", "{", "Rows", ":", "qr", ".", "Rows", "}", "\n", "if", "count", ">", "len", "(", "result", ".", "Rows", ")", "{", "count", "-=", "len", "(", "result", ".", "Rows", ")", "\n", "return", "callback", "(", "result", ")", "\n", "}", "\n", "result", ".", "Rows", "=", "result", ".", "Rows", "[", ":", "count", "]", "\n", "count", "=", "0", "\n", "if", "err", ":=", "callback", "(", "result", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "io", ".", "EOF", "\n", "}", ")", "\n\n", "if", "err", "==", "io", ".", "EOF", "{", "// We may get back the EOF we returned in the callback.", "// If so, suppress it.", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StreamExecute satisfies the Primtive interface.
[ "StreamExecute", "satisfies", "the", "Primtive", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/limit.go#L98-L147
train
vitessio/vitess
go/vt/vtgate/engine/limit.go
GetFields
func (l *Limit) GetFields(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return l.Input.GetFields(vcursor, bindVars) }
go
func (l *Limit) GetFields(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return l.Input.GetFields(vcursor, bindVars) }
[ "func", "(", "l", "*", "Limit", ")", "GetFields", "(", "vcursor", "VCursor", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "return", "l", ".", "Input", ".", "GetFields", "(", "vcursor", ",", "bindVars", ")", "\n", "}" ]
// GetFields satisfies the Primtive interface.
[ "GetFields", "satisfies", "the", "Primtive", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/limit.go#L150-L152
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
NewFakeMysqlDaemon
func NewFakeMysqlDaemon(db *fakesqldb.DB) *FakeMysqlDaemon { result := &FakeMysqlDaemon{ db: db, Running: true, } if db != nil { result.appPool = dbconnpool.NewConnectionPool("AppConnPool", 5, time.Minute, 0) result.appPool.Open(db.ConnParams(), stats.NewTimings("", "", "")) } return result }
go
func NewFakeMysqlDaemon(db *fakesqldb.DB) *FakeMysqlDaemon { result := &FakeMysqlDaemon{ db: db, Running: true, } if db != nil { result.appPool = dbconnpool.NewConnectionPool("AppConnPool", 5, time.Minute, 0) result.appPool.Open(db.ConnParams(), stats.NewTimings("", "", "")) } return result }
[ "func", "NewFakeMysqlDaemon", "(", "db", "*", "fakesqldb", ".", "DB", ")", "*", "FakeMysqlDaemon", "{", "result", ":=", "&", "FakeMysqlDaemon", "{", "db", ":", "db", ",", "Running", ":", "true", ",", "}", "\n", "if", "db", "!=", "nil", "{", "result", ".", "appPool", "=", "dbconnpool", ".", "NewConnectionPool", "(", "\"", "\"", ",", "5", ",", "time", ".", "Minute", ",", "0", ")", "\n", "result", ".", "appPool", ".", "Open", "(", "db", ".", "ConnParams", "(", ")", ",", "stats", ".", "NewTimings", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// NewFakeMysqlDaemon returns a FakeMysqlDaemon where mysqld appears // to be running, based on a fakesqldb.DB. // 'db' can be nil if the test doesn't use a database at all.
[ "NewFakeMysqlDaemon", "returns", "a", "FakeMysqlDaemon", "where", "mysqld", "appears", "to", "be", "running", "based", "on", "a", "fakesqldb", ".", "DB", ".", "db", "can", "be", "nil", "if", "the", "test", "doesn", "t", "use", "a", "database", "at", "all", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L150-L160
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
Start
func (fmd *FakeMysqlDaemon) Start(ctx context.Context, cnf *mysqlctl.Mycnf, mysqldArgs ...string) error { if fmd.Running { return fmt.Errorf("fake mysql daemon already running") } fmd.Running = true return nil }
go
func (fmd *FakeMysqlDaemon) Start(ctx context.Context, cnf *mysqlctl.Mycnf, mysqldArgs ...string) error { if fmd.Running { return fmt.Errorf("fake mysql daemon already running") } fmd.Running = true return nil }
[ "func", "(", "fmd", "*", "FakeMysqlDaemon", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "cnf", "*", "mysqlctl", ".", "Mycnf", ",", "mysqldArgs", "...", "string", ")", "error", "{", "if", "fmd", ".", "Running", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "fmd", ".", "Running", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Start is part of the MysqlDaemon interface
[ "Start", "is", "part", "of", "the", "MysqlDaemon", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L163-L169
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
Shutdown
func (fmd *FakeMysqlDaemon) Shutdown(ctx context.Context, cnf *mysqlctl.Mycnf, waitForMysqld bool) error { if !fmd.Running { return fmt.Errorf("fake mysql daemon not running") } fmd.Running = false return nil }
go
func (fmd *FakeMysqlDaemon) Shutdown(ctx context.Context, cnf *mysqlctl.Mycnf, waitForMysqld bool) error { if !fmd.Running { return fmt.Errorf("fake mysql daemon not running") } fmd.Running = false return nil }
[ "func", "(", "fmd", "*", "FakeMysqlDaemon", ")", "Shutdown", "(", "ctx", "context", ".", "Context", ",", "cnf", "*", "mysqlctl", ".", "Mycnf", ",", "waitForMysqld", "bool", ")", "error", "{", "if", "!", "fmd", ".", "Running", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "fmd", ".", "Running", "=", "false", "\n", "return", "nil", "\n", "}" ]
// Shutdown is part of the MysqlDaemon interface
[ "Shutdown", "is", "part", "of", "the", "MysqlDaemon", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L172-L178
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
ReinitConfig
func (fmd *FakeMysqlDaemon) ReinitConfig(ctx context.Context, cnf *mysqlctl.Mycnf) error { return nil }
go
func (fmd *FakeMysqlDaemon) ReinitConfig(ctx context.Context, cnf *mysqlctl.Mycnf) error { return nil }
[ "func", "(", "fmd", "*", "FakeMysqlDaemon", ")", "ReinitConfig", "(", "ctx", "context", ".", "Context", ",", "cnf", "*", "mysqlctl", ".", "Mycnf", ")", "error", "{", "return", "nil", "\n", "}" ]
// ReinitConfig is part of the MysqlDaemon interface
[ "ReinitConfig", "is", "part", "of", "the", "MysqlDaemon", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L186-L188
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
GetMysqlPort
func (fmd *FakeMysqlDaemon) GetMysqlPort() (int32, error) { if fmd.MysqlPort == -1 { return 0, fmt.Errorf("FakeMysqlDaemon.GetMysqlPort returns an error") } return fmd.MysqlPort, nil }
go
func (fmd *FakeMysqlDaemon) GetMysqlPort() (int32, error) { if fmd.MysqlPort == -1 { return 0, fmt.Errorf("FakeMysqlDaemon.GetMysqlPort returns an error") } return fmd.MysqlPort, nil }
[ "func", "(", "fmd", "*", "FakeMysqlDaemon", ")", "GetMysqlPort", "(", ")", "(", "int32", ",", "error", ")", "{", "if", "fmd", ".", "MysqlPort", "==", "-", "1", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "fmd", ".", "MysqlPort", ",", "nil", "\n", "}" ]
// GetMysqlPort is part of the MysqlDaemon interface
[ "GetMysqlPort", "is", "part", "of", "the", "MysqlDaemon", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L201-L206
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
SlaveStatus
func (fmd *FakeMysqlDaemon) SlaveStatus() (mysql.SlaveStatus, error) { if fmd.SlaveStatusError != nil { return mysql.SlaveStatus{}, fmd.SlaveStatusError } return mysql.SlaveStatus{ Position: fmd.CurrentMasterPosition, SecondsBehindMaster: fmd.SecondsBehindMaster, SlaveIORunning: fmd.Replicating, SlaveSQLRunning: fmd.Replicating, MasterHost: fmd.CurrentMasterHost, MasterPort: fmd.CurrentMasterPort, }, nil }
go
func (fmd *FakeMysqlDaemon) SlaveStatus() (mysql.SlaveStatus, error) { if fmd.SlaveStatusError != nil { return mysql.SlaveStatus{}, fmd.SlaveStatusError } return mysql.SlaveStatus{ Position: fmd.CurrentMasterPosition, SecondsBehindMaster: fmd.SecondsBehindMaster, SlaveIORunning: fmd.Replicating, SlaveSQLRunning: fmd.Replicating, MasterHost: fmd.CurrentMasterHost, MasterPort: fmd.CurrentMasterPort, }, nil }
[ "func", "(", "fmd", "*", "FakeMysqlDaemon", ")", "SlaveStatus", "(", ")", "(", "mysql", ".", "SlaveStatus", ",", "error", ")", "{", "if", "fmd", ".", "SlaveStatusError", "!=", "nil", "{", "return", "mysql", ".", "SlaveStatus", "{", "}", ",", "fmd", ".", "SlaveStatusError", "\n", "}", "\n", "return", "mysql", ".", "SlaveStatus", "{", "Position", ":", "fmd", ".", "CurrentMasterPosition", ",", "SecondsBehindMaster", ":", "fmd", ".", "SecondsBehindMaster", ",", "SlaveIORunning", ":", "fmd", ".", "Replicating", ",", "SlaveSQLRunning", ":", "fmd", ".", "Replicating", ",", "MasterHost", ":", "fmd", ".", "CurrentMasterHost", ",", "MasterPort", ":", "fmd", ".", "CurrentMasterPort", ",", "}", ",", "nil", "\n", "}" ]
// SlaveStatus is part of the MysqlDaemon interface
[ "SlaveStatus", "is", "part", "of", "the", "MysqlDaemon", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L209-L221
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
ResetReplication
func (fmd *FakeMysqlDaemon) ResetReplication(ctx context.Context) error { return fmd.ExecuteSuperQueryList(ctx, []string{ "FAKE RESET ALL REPLICATION", }) }
go
func (fmd *FakeMysqlDaemon) ResetReplication(ctx context.Context) error { return fmd.ExecuteSuperQueryList(ctx, []string{ "FAKE RESET ALL REPLICATION", }) }
[ "func", "(", "fmd", "*", "FakeMysqlDaemon", ")", "ResetReplication", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "fmd", ".", "ExecuteSuperQueryList", "(", "ctx", ",", "[", "]", "string", "{", "\"", "\"", ",", "}", ")", "\n", "}" ]
// ResetReplication is part of the MysqlDaemon interface.
[ "ResetReplication", "is", "part", "of", "the", "MysqlDaemon", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L224-L228
train
vitessio/vitess
go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go
SetReadOnly
func (fmd *FakeMysqlDaemon) SetReadOnly(on bool) error { fmd.ReadOnly = on return nil }
go
func (fmd *FakeMysqlDaemon) SetReadOnly(on bool) error { fmd.ReadOnly = on return nil }
[ "func", "(", "fmd", "*", "FakeMysqlDaemon", ")", "SetReadOnly", "(", "on", "bool", ")", "error", "{", "fmd", ".", "ReadOnly", "=", "on", "\n", "return", "nil", "\n", "}" ]
// SetReadOnly is part of the MysqlDaemon interface
[ "SetReadOnly", "is", "part", "of", "the", "MysqlDaemon", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/fakemysqldaemon/fakemysqldaemon.go#L241-L244
train