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/discovery/tablet_stats_cache_wait.go
WaitForAnyTablet
func (tc *TabletStatsCache) WaitForAnyTablet(ctx context.Context, cell, keyspace, shard string, tabletTypes []topodatapb.TabletType) error { return tc.waitForAnyTablet(ctx, keyspace, shard, tabletTypes) }
go
func (tc *TabletStatsCache) WaitForAnyTablet(ctx context.Context, cell, keyspace, shard string, tabletTypes []topodatapb.TabletType) error { return tc.waitForAnyTablet(ctx, keyspace, shard, tabletTypes) }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "WaitForAnyTablet", "(", "ctx", "context", ".", "Context", ",", "cell", ",", "keyspace", ",", "shard", "string", ",", "tabletTypes", "[", "]", "topodatapb", ".", "TabletType", ")", "error", "{", "return", "tc", ".", "waitForAnyTablet", "(", "ctx", ",", "keyspace", ",", "shard", ",", "tabletTypes", ")", "\n", "}" ]
// WaitForAnyTablet waits for a single tablet of any of the types. // It doesn't have to be serving.
[ "WaitForAnyTablet", "waits", "for", "a", "single", "tablet", "of", "any", "of", "the", "types", ".", "It", "doesn", "t", "have", "to", "be", "serving", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache_wait.go#L49-L51
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache_wait.go
waitForTablets
func (tc *TabletStatsCache) waitForTablets(ctx context.Context, targets []*querypb.Target, requireServing bool) error { for { // We nil targets as we find them. allPresent := true for i, target := range targets { if target == nil { continue } var stats []TabletStats if requireServing { stats = tc.GetHealthyTabletStats(target.Keyspace, target.Shard, target.TabletType) } else { stats = tc.GetTabletStats(target.Keyspace, target.Shard, target.TabletType) } if len(stats) == 0 { allPresent = false } else { targets[i] = nil } } if allPresent { // we found everything we needed return nil } // Unblock after the sleep or when the context has expired. timer := time.NewTimer(waitAvailableTabletInterval) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } } }
go
func (tc *TabletStatsCache) waitForTablets(ctx context.Context, targets []*querypb.Target, requireServing bool) error { for { // We nil targets as we find them. allPresent := true for i, target := range targets { if target == nil { continue } var stats []TabletStats if requireServing { stats = tc.GetHealthyTabletStats(target.Keyspace, target.Shard, target.TabletType) } else { stats = tc.GetTabletStats(target.Keyspace, target.Shard, target.TabletType) } if len(stats) == 0 { allPresent = false } else { targets[i] = nil } } if allPresent { // we found everything we needed return nil } // Unblock after the sleep or when the context has expired. timer := time.NewTimer(waitAvailableTabletInterval) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } } }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "waitForTablets", "(", "ctx", "context", ".", "Context", ",", "targets", "[", "]", "*", "querypb", ".", "Target", ",", "requireServing", "bool", ")", "error", "{", "for", "{", "// We nil targets as we find them.", "allPresent", ":=", "true", "\n", "for", "i", ",", "target", ":=", "range", "targets", "{", "if", "target", "==", "nil", "{", "continue", "\n", "}", "\n\n", "var", "stats", "[", "]", "TabletStats", "\n", "if", "requireServing", "{", "stats", "=", "tc", ".", "GetHealthyTabletStats", "(", "target", ".", "Keyspace", ",", "target", ".", "Shard", ",", "target", ".", "TabletType", ")", "\n", "}", "else", "{", "stats", "=", "tc", ".", "GetTabletStats", "(", "target", ".", "Keyspace", ",", "target", ".", "Shard", ",", "target", ".", "TabletType", ")", "\n", "}", "\n", "if", "len", "(", "stats", ")", "==", "0", "{", "allPresent", "=", "false", "\n", "}", "else", "{", "targets", "[", "i", "]", "=", "nil", "\n", "}", "\n", "}", "\n\n", "if", "allPresent", "{", "// we found everything we needed", "return", "nil", "\n", "}", "\n\n", "// Unblock after the sleep or when the context has expired.", "timer", ":=", "time", ".", "NewTimer", "(", "waitAvailableTabletInterval", ")", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "timer", ".", "Stop", "(", ")", "\n", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "timer", ".", "C", ":", "}", "\n", "}", "\n", "}" ]
// waitForTablets is the internal method that polls for tablets.
[ "waitForTablets", "is", "the", "internal", "method", "that", "polls", "for", "tablets", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache_wait.go#L62-L98
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache_wait.go
waitForAnyTablet
func (tc *TabletStatsCache) waitForAnyTablet(ctx context.Context, keyspace, shard string, types []topodatapb.TabletType) error { for { for _, tt := range types { stats := tc.GetTabletStats(keyspace, shard, tt) if len(stats) > 0 { return nil } } // Unblock after the sleep or when the context has expired. timer := time.NewTimer(waitAvailableTabletInterval) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } } }
go
func (tc *TabletStatsCache) waitForAnyTablet(ctx context.Context, keyspace, shard string, types []topodatapb.TabletType) error { for { for _, tt := range types { stats := tc.GetTabletStats(keyspace, shard, tt) if len(stats) > 0 { return nil } } // Unblock after the sleep or when the context has expired. timer := time.NewTimer(waitAvailableTabletInterval) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } } }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "waitForAnyTablet", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "types", "[", "]", "topodatapb", ".", "TabletType", ")", "error", "{", "for", "{", "for", "_", ",", "tt", ":=", "range", "types", "{", "stats", ":=", "tc", ".", "GetTabletStats", "(", "keyspace", ",", "shard", ",", "tt", ")", "\n", "if", "len", "(", "stats", ")", ">", "0", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "// Unblock after the sleep or when the context has expired.", "timer", ":=", "time", ".", "NewTimer", "(", "waitAvailableTabletInterval", ")", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "timer", ".", "Stop", "(", ")", "\n", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "timer", ".", "C", ":", "}", "\n", "}", "\n", "}" ]
// waitForAnyTablet is the internal method that polls for any tablet of required type
[ "waitForAnyTablet", "is", "the", "internal", "method", "that", "polls", "for", "any", "tablet", "of", "required", "type" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache_wait.go#L101-L119
train
vitessio/vitess
go/vt/topotools/events/reparent_syslog.go
Syslog
func (r *Reparent) Syslog() (syslog.Priority, string) { return syslog.LOG_INFO, fmt.Sprintf("%s/%s [reparent %v -> %v] %s (%s)", r.ShardInfo.Keyspace(), r.ShardInfo.ShardName(), topoproto.TabletAliasString(r.OldMaster.Alias), topoproto.TabletAliasString(r.NewMaster.Alias), r.Status, r.ExternalID) }
go
func (r *Reparent) Syslog() (syslog.Priority, string) { return syslog.LOG_INFO, fmt.Sprintf("%s/%s [reparent %v -> %v] %s (%s)", r.ShardInfo.Keyspace(), r.ShardInfo.ShardName(), topoproto.TabletAliasString(r.OldMaster.Alias), topoproto.TabletAliasString(r.NewMaster.Alias), r.Status, r.ExternalID) }
[ "func", "(", "r", "*", "Reparent", ")", "Syslog", "(", ")", "(", "syslog", ".", "Priority", ",", "string", ")", "{", "return", "syslog", ".", "LOG_INFO", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "ShardInfo", ".", "Keyspace", "(", ")", ",", "r", ".", "ShardInfo", ".", "ShardName", "(", ")", ",", "topoproto", ".", "TabletAliasString", "(", "r", ".", "OldMaster", ".", "Alias", ")", ",", "topoproto", ".", "TabletAliasString", "(", "r", ".", "NewMaster", ".", "Alias", ")", ",", "r", ".", "Status", ",", "r", ".", "ExternalID", ")", "\n", "}" ]
// Syslog writes a Reparent event to syslog.
[ "Syslog", "writes", "a", "Reparent", "event", "to", "syslog", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/events/reparent_syslog.go#L28-L34
train
vitessio/vitess
go/sqltypes/arithmetic.go
Min
func Min(v1, v2 Value) (Value, error) { return minmax(v1, v2, true) }
go
func Min(v1, v2 Value) (Value, error) { return minmax(v1, v2, true) }
[ "func", "Min", "(", "v1", ",", "v2", "Value", ")", "(", "Value", ",", "error", ")", "{", "return", "minmax", "(", "v1", ",", "v2", ",", "true", ")", "\n", "}" ]
// Min returns the minimum of v1 and v2. If one of the // values is NULL, it returns the other value. If both // are NULL, it returns NULL.
[ "Min", "returns", "the", "minimum", "of", "v1", "and", "v2", ".", "If", "one", "of", "the", "values", "is", "NULL", "it", "returns", "the", "other", "value", ".", "If", "both", "are", "NULL", "it", "returns", "NULL", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L123-L125
train
vitessio/vitess
go/sqltypes/arithmetic.go
Max
func Max(v1, v2 Value) (Value, error) { return minmax(v1, v2, false) }
go
func Max(v1, v2 Value) (Value, error) { return minmax(v1, v2, false) }
[ "func", "Max", "(", "v1", ",", "v2", "Value", ")", "(", "Value", ",", "error", ")", "{", "return", "minmax", "(", "v1", ",", "v2", ",", "false", ")", "\n", "}" ]
// Max returns the maximum of v1 and v2. If one of the // values is NULL, it returns the other value. If both // are NULL, it returns NULL.
[ "Max", "returns", "the", "maximum", "of", "v1", "and", "v2", ".", "If", "one", "of", "the", "values", "is", "NULL", "it", "returns", "the", "other", "value", ".", "If", "both", "are", "NULL", "it", "returns", "NULL", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L130-L132
train
vitessio/vitess
go/sqltypes/arithmetic.go
Cast
func Cast(v Value, typ querypb.Type) (Value, error) { if v.Type() == typ || v.IsNull() { return v, nil } if IsSigned(typ) && v.IsSigned() { return MakeTrusted(typ, v.ToBytes()), nil } if IsUnsigned(typ) && v.IsUnsigned() { return MakeTrusted(typ, v.ToBytes()), nil } if (IsFloat(typ) || typ == Decimal) && (v.IsIntegral() || v.IsFloat() || v.Type() == Decimal) { return MakeTrusted(typ, v.ToBytes()), nil } if IsQuoted(typ) && (v.IsIntegral() || v.IsFloat() || v.Type() == Decimal || v.IsQuoted()) { return MakeTrusted(typ, v.ToBytes()), nil } // Explicitly disallow Expression. if v.Type() == Expression { return NULL, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v cannot be cast to %v", v, typ) } // If the above fast-paths were not possible, // go through full validation. return NewValue(typ, v.ToBytes()) }
go
func Cast(v Value, typ querypb.Type) (Value, error) { if v.Type() == typ || v.IsNull() { return v, nil } if IsSigned(typ) && v.IsSigned() { return MakeTrusted(typ, v.ToBytes()), nil } if IsUnsigned(typ) && v.IsUnsigned() { return MakeTrusted(typ, v.ToBytes()), nil } if (IsFloat(typ) || typ == Decimal) && (v.IsIntegral() || v.IsFloat() || v.Type() == Decimal) { return MakeTrusted(typ, v.ToBytes()), nil } if IsQuoted(typ) && (v.IsIntegral() || v.IsFloat() || v.Type() == Decimal || v.IsQuoted()) { return MakeTrusted(typ, v.ToBytes()), nil } // Explicitly disallow Expression. if v.Type() == Expression { return NULL, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v cannot be cast to %v", v, typ) } // If the above fast-paths were not possible, // go through full validation. return NewValue(typ, v.ToBytes()) }
[ "func", "Cast", "(", "v", "Value", ",", "typ", "querypb", ".", "Type", ")", "(", "Value", ",", "error", ")", "{", "if", "v", ".", "Type", "(", ")", "==", "typ", "||", "v", ".", "IsNull", "(", ")", "{", "return", "v", ",", "nil", "\n", "}", "\n", "if", "IsSigned", "(", "typ", ")", "&&", "v", ".", "IsSigned", "(", ")", "{", "return", "MakeTrusted", "(", "typ", ",", "v", ".", "ToBytes", "(", ")", ")", ",", "nil", "\n", "}", "\n", "if", "IsUnsigned", "(", "typ", ")", "&&", "v", ".", "IsUnsigned", "(", ")", "{", "return", "MakeTrusted", "(", "typ", ",", "v", ".", "ToBytes", "(", ")", ")", ",", "nil", "\n", "}", "\n", "if", "(", "IsFloat", "(", "typ", ")", "||", "typ", "==", "Decimal", ")", "&&", "(", "v", ".", "IsIntegral", "(", ")", "||", "v", ".", "IsFloat", "(", ")", "||", "v", ".", "Type", "(", ")", "==", "Decimal", ")", "{", "return", "MakeTrusted", "(", "typ", ",", "v", ".", "ToBytes", "(", ")", ")", ",", "nil", "\n", "}", "\n", "if", "IsQuoted", "(", "typ", ")", "&&", "(", "v", ".", "IsIntegral", "(", ")", "||", "v", ".", "IsFloat", "(", ")", "||", "v", ".", "Type", "(", ")", "==", "Decimal", "||", "v", ".", "IsQuoted", "(", ")", ")", "{", "return", "MakeTrusted", "(", "typ", ",", "v", ".", "ToBytes", "(", ")", ")", ",", "nil", "\n", "}", "\n\n", "// Explicitly disallow Expression.", "if", "v", ".", "Type", "(", ")", "==", "Expression", "{", "return", "NULL", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "v", ",", "typ", ")", "\n", "}", "\n\n", "// If the above fast-paths were not possible,", "// go through full validation.", "return", "NewValue", "(", "typ", ",", "v", ".", "ToBytes", "(", ")", ")", "\n", "}" ]
// Cast converts a Value to the target type.
[ "Cast", "converts", "a", "Value", "to", "the", "target", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L156-L181
train
vitessio/vitess
go/sqltypes/arithmetic.go
ToUint64
func ToUint64(v Value) (uint64, error) { num, err := newIntegralNumeric(v) if err != nil { return 0, err } switch num.typ { case Int64: if num.ival < 0 { return 0, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "negative number cannot be converted to unsigned: %d", num.ival) } return uint64(num.ival), nil case Uint64: return num.uval, nil } panic("unreachable") }
go
func ToUint64(v Value) (uint64, error) { num, err := newIntegralNumeric(v) if err != nil { return 0, err } switch num.typ { case Int64: if num.ival < 0 { return 0, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "negative number cannot be converted to unsigned: %d", num.ival) } return uint64(num.ival), nil case Uint64: return num.uval, nil } panic("unreachable") }
[ "func", "ToUint64", "(", "v", "Value", ")", "(", "uint64", ",", "error", ")", "{", "num", ",", "err", ":=", "newIntegralNumeric", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "switch", "num", ".", "typ", "{", "case", "Int64", ":", "if", "num", ".", "ival", "<", "0", "{", "return", "0", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "num", ".", "ival", ")", "\n", "}", "\n", "return", "uint64", "(", "num", ".", "ival", ")", ",", "nil", "\n", "case", "Uint64", ":", "return", "num", ".", "uval", ",", "nil", "\n", "}", "\n", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// ToUint64 converts Value to uint64.
[ "ToUint64", "converts", "Value", "to", "uint64", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L184-L199
train
vitessio/vitess
go/sqltypes/arithmetic.go
ToFloat64
func ToFloat64(v Value) (float64, error) { num, err := newNumeric(v) if err != nil { return 0, err } switch num.typ { case Int64: return float64(num.ival), nil case Uint64: return float64(num.uval), nil case Float64: return num.fval, nil } panic("unreachable") }
go
func ToFloat64(v Value) (float64, error) { num, err := newNumeric(v) if err != nil { return 0, err } switch num.typ { case Int64: return float64(num.ival), nil case Uint64: return float64(num.uval), nil case Float64: return num.fval, nil } panic("unreachable") }
[ "func", "ToFloat64", "(", "v", "Value", ")", "(", "float64", ",", "error", ")", "{", "num", ",", "err", ":=", "newNumeric", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "switch", "num", ".", "typ", "{", "case", "Int64", ":", "return", "float64", "(", "num", ".", "ival", ")", ",", "nil", "\n", "case", "Uint64", ":", "return", "float64", "(", "num", ".", "uval", ")", ",", "nil", "\n", "case", "Float64", ":", "return", "num", ".", "fval", ",", "nil", "\n", "}", "\n", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// ToFloat64 converts Value to float64.
[ "ToFloat64", "converts", "Value", "to", "float64", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L221-L235
train
vitessio/vitess
go/sqltypes/arithmetic.go
newNumeric
func newNumeric(v Value) (numeric, error) { str := v.ToString() switch { case v.IsSigned(): ival, err := strconv.ParseInt(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{ival: ival, typ: Int64}, nil case v.IsUnsigned(): uval, err := strconv.ParseUint(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{uval: uval, typ: Uint64}, nil case v.IsFloat(): fval, err := strconv.ParseFloat(str, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{fval: fval, typ: Float64}, nil } // For other types, do best effort. if ival, err := strconv.ParseInt(str, 10, 64); err == nil { return numeric{ival: ival, typ: Int64}, nil } if fval, err := strconv.ParseFloat(str, 64); err == nil { return numeric{fval: fval, typ: Float64}, nil } return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "could not parse value: '%s'", str) }
go
func newNumeric(v Value) (numeric, error) { str := v.ToString() switch { case v.IsSigned(): ival, err := strconv.ParseInt(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{ival: ival, typ: Int64}, nil case v.IsUnsigned(): uval, err := strconv.ParseUint(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{uval: uval, typ: Uint64}, nil case v.IsFloat(): fval, err := strconv.ParseFloat(str, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{fval: fval, typ: Float64}, nil } // For other types, do best effort. if ival, err := strconv.ParseInt(str, 10, 64); err == nil { return numeric{ival: ival, typ: Int64}, nil } if fval, err := strconv.ParseFloat(str, 64); err == nil { return numeric{fval: fval, typ: Float64}, nil } return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "could not parse value: '%s'", str) }
[ "func", "newNumeric", "(", "v", "Value", ")", "(", "numeric", ",", "error", ")", "{", "str", ":=", "v", ".", "ToString", "(", ")", "\n", "switch", "{", "case", "v", ".", "IsSigned", "(", ")", ":", "ival", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "str", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "numeric", "{", "}", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "numeric", "{", "ival", ":", "ival", ",", "typ", ":", "Int64", "}", ",", "nil", "\n", "case", "v", ".", "IsUnsigned", "(", ")", ":", "uval", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "str", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "numeric", "{", "}", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "numeric", "{", "uval", ":", "uval", ",", "typ", ":", "Uint64", "}", ",", "nil", "\n", "case", "v", ".", "IsFloat", "(", ")", ":", "fval", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "str", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "numeric", "{", "}", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "numeric", "{", "fval", ":", "fval", ",", "typ", ":", "Float64", "}", ",", "nil", "\n", "}", "\n\n", "// For other types, do best effort.", "if", "ival", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "str", ",", "10", ",", "64", ")", ";", "err", "==", "nil", "{", "return", "numeric", "{", "ival", ":", "ival", ",", "typ", ":", "Int64", "}", ",", "nil", "\n", "}", "\n", "if", "fval", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "str", ",", "64", ")", ";", "err", "==", "nil", "{", "return", "numeric", "{", "fval", ":", "fval", ",", "typ", ":", "Float64", "}", ",", "nil", "\n", "}", "\n", "return", "numeric", "{", "}", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "str", ")", "\n", "}" ]
// newNumeric parses a value and produces an Int64, Uint64 or Float64.
[ "newNumeric", "parses", "a", "value", "and", "produces", "an", "Int64", "Uint64", "or", "Float64", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L260-L291
train
vitessio/vitess
go/sqltypes/arithmetic.go
newIntegralNumeric
func newIntegralNumeric(v Value) (numeric, error) { str := v.ToString() switch { case v.IsSigned(): ival, err := strconv.ParseInt(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{ival: ival, typ: Int64}, nil case v.IsUnsigned(): uval, err := strconv.ParseUint(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{uval: uval, typ: Uint64}, nil } // For other types, do best effort. if ival, err := strconv.ParseInt(str, 10, 64); err == nil { return numeric{ival: ival, typ: Int64}, nil } if uval, err := strconv.ParseUint(str, 10, 64); err == nil { return numeric{uval: uval, typ: Uint64}, nil } return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "could not parse value: '%s'", str) }
go
func newIntegralNumeric(v Value) (numeric, error) { str := v.ToString() switch { case v.IsSigned(): ival, err := strconv.ParseInt(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{ival: ival, typ: Int64}, nil case v.IsUnsigned(): uval, err := strconv.ParseUint(str, 10, 64) if err != nil { return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } return numeric{uval: uval, typ: Uint64}, nil } // For other types, do best effort. if ival, err := strconv.ParseInt(str, 10, 64); err == nil { return numeric{ival: ival, typ: Int64}, nil } if uval, err := strconv.ParseUint(str, 10, 64); err == nil { return numeric{uval: uval, typ: Uint64}, nil } return numeric{}, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "could not parse value: '%s'", str) }
[ "func", "newIntegralNumeric", "(", "v", "Value", ")", "(", "numeric", ",", "error", ")", "{", "str", ":=", "v", ".", "ToString", "(", ")", "\n", "switch", "{", "case", "v", ".", "IsSigned", "(", ")", ":", "ival", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "str", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "numeric", "{", "}", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "numeric", "{", "ival", ":", "ival", ",", "typ", ":", "Int64", "}", ",", "nil", "\n", "case", "v", ".", "IsUnsigned", "(", ")", ":", "uval", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "str", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "numeric", "{", "}", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "numeric", "{", "uval", ":", "uval", ",", "typ", ":", "Uint64", "}", ",", "nil", "\n", "}", "\n\n", "// For other types, do best effort.", "if", "ival", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "str", ",", "10", ",", "64", ")", ";", "err", "==", "nil", "{", "return", "numeric", "{", "ival", ":", "ival", ",", "typ", ":", "Int64", "}", ",", "nil", "\n", "}", "\n", "if", "uval", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "str", ",", "10", ",", "64", ")", ";", "err", "==", "nil", "{", "return", "numeric", "{", "uval", ":", "uval", ",", "typ", ":", "Uint64", "}", ",", "nil", "\n", "}", "\n", "return", "numeric", "{", "}", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "str", ")", "\n", "}" ]
// newIntegralNumeric parses a value and produces an Int64 or Uint64.
[ "newIntegralNumeric", "parses", "a", "value", "and", "produces", "an", "Int64", "or", "Uint64", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L294-L319
train
vitessio/vitess
go/sqltypes/arithmetic.go
prioritize
func prioritize(v1, v2 numeric) (altv1, altv2 numeric) { switch v1.typ { case Int64: if v2.typ == Uint64 || v2.typ == Float64 { return v2, v1 } case Uint64: if v2.typ == Float64 { return v2, v1 } } return v1, v2 }
go
func prioritize(v1, v2 numeric) (altv1, altv2 numeric) { switch v1.typ { case Int64: if v2.typ == Uint64 || v2.typ == Float64 { return v2, v1 } case Uint64: if v2.typ == Float64 { return v2, v1 } } return v1, v2 }
[ "func", "prioritize", "(", "v1", ",", "v2", "numeric", ")", "(", "altv1", ",", "altv2", "numeric", ")", "{", "switch", "v1", ".", "typ", "{", "case", "Int64", ":", "if", "v2", ".", "typ", "==", "Uint64", "||", "v2", ".", "typ", "==", "Float64", "{", "return", "v2", ",", "v1", "\n", "}", "\n", "case", "Uint64", ":", "if", "v2", ".", "typ", "==", "Float64", "{", "return", "v2", ",", "v1", "\n", "}", "\n", "}", "\n", "return", "v1", ",", "v2", "\n", "}" ]
// prioritize reorders the input parameters // to be Float64, Uint64, Int64.
[ "prioritize", "reorders", "the", "input", "parameters", "to", "be", "Float64", "Uint64", "Int64", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/arithmetic.go#L341-L353
train
vitessio/vitess
go/vt/vtgate/logstats.go
RemoteAddrUsername
func (stats *LogStats) RemoteAddrUsername() (string, string) { ci, ok := callinfo.FromContext(stats.Ctx) if !ok { return "", "" } return ci.RemoteAddr(), ci.Username() }
go
func (stats *LogStats) RemoteAddrUsername() (string, string) { ci, ok := callinfo.FromContext(stats.Ctx) if !ok { return "", "" } return ci.RemoteAddr(), ci.Username() }
[ "func", "(", "stats", "*", "LogStats", ")", "RemoteAddrUsername", "(", ")", "(", "string", ",", "string", ")", "{", "ci", ",", "ok", ":=", "callinfo", ".", "FromContext", "(", "stats", ".", "Ctx", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "\"", "\"", "\n", "}", "\n", "return", "ci", ".", "RemoteAddr", "(", ")", ",", "ci", ".", "Username", "(", ")", "\n", "}" ]
// RemoteAddrUsername returns some parts of CallInfo if set
[ "RemoteAddrUsername", "returns", "some", "parts", "of", "CallInfo", "if", "set" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/logstats.go#L113-L119
train
vitessio/vitess
go/vt/vtgate/vschemaacl/vschemaacl.go
Authorized
func Authorized(caller *querypb.VTGateCallerID) bool { if allowAll { return true } user := caller.GetUsername() _, ok := acl[user] return ok }
go
func Authorized(caller *querypb.VTGateCallerID) bool { if allowAll { return true } user := caller.GetUsername() _, ok := acl[user] return ok }
[ "func", "Authorized", "(", "caller", "*", "querypb", ".", "VTGateCallerID", ")", "bool", "{", "if", "allowAll", "{", "return", "true", "\n", "}", "\n\n", "user", ":=", "caller", ".", "GetUsername", "(", ")", "\n", "_", ",", "ok", ":=", "acl", "[", "user", "]", "\n", "return", "ok", "\n", "}" ]
// Authorized returns true if the given caller is allowed to execute vschema operations
[ "Authorized", "returns", "true", "if", "the", "given", "caller", "is", "allowed", "to", "execute", "vschema", "operations" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vschemaacl/vschemaacl.go#L56-L64
train
vitessio/vitess
go/vt/worker/status_worker.go
SetState
func (w *StatusWorker) SetState(state StatusWorkerState) { w.mu.Lock() defer w.mu.Unlock() w.state = state statsState.Set(string(state)) }
go
func (w *StatusWorker) SetState(state StatusWorkerState) { w.mu.Lock() defer w.mu.Unlock() w.state = state statsState.Set(string(state)) }
[ "func", "(", "w", "*", "StatusWorker", ")", "SetState", "(", "state", "StatusWorkerState", ")", "{", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "w", ".", "state", "=", "state", "\n", "statsState", ".", "Set", "(", "string", "(", "state", ")", ")", "\n", "}" ]
// SetState is a convenience function for workers.
[ "SetState", "is", "a", "convenience", "function", "for", "workers", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/status_worker.go#L88-L94
train
vitessio/vitess
go/vt/worker/status_worker.go
State
func (w *StatusWorker) State() StatusWorkerState { w.mu.Lock() defer w.mu.Unlock() return w.state }
go
func (w *StatusWorker) State() StatusWorkerState { w.mu.Lock() defer w.mu.Unlock() return w.state }
[ "func", "(", "w", "*", "StatusWorker", ")", "State", "(", ")", "StatusWorkerState", "{", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "w", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "w", ".", "state", "\n", "}" ]
// State is part of the Worker interface.
[ "State", "is", "part", "of", "the", "Worker", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/status_worker.go#L97-L102
train
vitessio/vitess
go/vt/automation/id_generator.go
GetNextID
func (ig *IDGenerator) GetNextID() string { return strconv.FormatInt(atomic.AddInt64(&ig.counter, 1), 10) }
go
func (ig *IDGenerator) GetNextID() string { return strconv.FormatInt(atomic.AddInt64(&ig.counter, 1), 10) }
[ "func", "(", "ig", "*", "IDGenerator", ")", "GetNextID", "(", ")", "string", "{", "return", "strconv", ".", "FormatInt", "(", "atomic", ".", "AddInt64", "(", "&", "ig", ".", "counter", ",", "1", ")", ",", "10", ")", "\n", "}" ]
// GetNextID returns an ID which wasn't returned before.
[ "GetNextID", "returns", "an", "ID", "which", "wasn", "t", "returned", "before", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/id_generator.go#L30-L32
train
vitessio/vitess
go/pools/id_pool.go
Get
func (pool *IDPool) Get() (id uint32) { pool.Lock() defer pool.Unlock() // Pick a value that's been returned, if any. for key := range pool.used { delete(pool.used, key) return key } // No recycled IDs are available, so increase the pool size. pool.maxUsed += 1 return pool.maxUsed }
go
func (pool *IDPool) Get() (id uint32) { pool.Lock() defer pool.Unlock() // Pick a value that's been returned, if any. for key := range pool.used { delete(pool.used, key) return key } // No recycled IDs are available, so increase the pool size. pool.maxUsed += 1 return pool.maxUsed }
[ "func", "(", "pool", "*", "IDPool", ")", "Get", "(", ")", "(", "id", "uint32", ")", "{", "pool", ".", "Lock", "(", ")", "\n", "defer", "pool", ".", "Unlock", "(", ")", "\n\n", "// Pick a value that's been returned, if any.", "for", "key", ":=", "range", "pool", ".", "used", "{", "delete", "(", "pool", ".", "used", ",", "key", ")", "\n", "return", "key", "\n", "}", "\n\n", "// No recycled IDs are available, so increase the pool size.", "pool", ".", "maxUsed", "+=", "1", "\n", "return", "pool", ".", "maxUsed", "\n", "}" ]
// Get returns an ID that is unique among currently active users of this pool.
[ "Get", "returns", "an", "ID", "that", "is", "unique", "among", "currently", "active", "users", "of", "this", "pool", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/id_pool.go#L46-L59
train
vitessio/vitess
go/pools/id_pool.go
Put
func (pool *IDPool) Put(id uint32) { pool.Lock() defer pool.Unlock() if id < 1 || id > pool.maxUsed { panic(fmt.Errorf("IDPool.Put(%v): invalid value, must be in the range [1,%v]", id, pool.maxUsed)) } if pool.used[id] { panic(fmt.Errorf("IDPool.Put(%v): can't put value that was already recycled", id)) } // If we're recycling maxUsed, just shrink the pool. if id == pool.maxUsed { pool.maxUsed = id - 1 return } // Add it to the set of recycled IDs. pool.used[id] = true }
go
func (pool *IDPool) Put(id uint32) { pool.Lock() defer pool.Unlock() if id < 1 || id > pool.maxUsed { panic(fmt.Errorf("IDPool.Put(%v): invalid value, must be in the range [1,%v]", id, pool.maxUsed)) } if pool.used[id] { panic(fmt.Errorf("IDPool.Put(%v): can't put value that was already recycled", id)) } // If we're recycling maxUsed, just shrink the pool. if id == pool.maxUsed { pool.maxUsed = id - 1 return } // Add it to the set of recycled IDs. pool.used[id] = true }
[ "func", "(", "pool", "*", "IDPool", ")", "Put", "(", "id", "uint32", ")", "{", "pool", ".", "Lock", "(", ")", "\n", "defer", "pool", ".", "Unlock", "(", ")", "\n\n", "if", "id", "<", "1", "||", "id", ">", "pool", ".", "maxUsed", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "pool", ".", "maxUsed", ")", ")", "\n", "}", "\n\n", "if", "pool", ".", "used", "[", "id", "]", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n\n", "// If we're recycling maxUsed, just shrink the pool.", "if", "id", "==", "pool", ".", "maxUsed", "{", "pool", ".", "maxUsed", "=", "id", "-", "1", "\n", "return", "\n", "}", "\n\n", "// Add it to the set of recycled IDs.", "pool", ".", "used", "[", "id", "]", "=", "true", "\n", "}" ]
// Put recycles an ID back into the pool for others to use. Putting back a value // or 0, or a value that is not currently "checked out", will result in a panic // because that should never happen except in the case of a programming error.
[ "Put", "recycles", "an", "ID", "back", "into", "the", "pool", "for", "others", "to", "use", ".", "Putting", "back", "a", "value", "or", "0", "or", "a", "value", "that", "is", "not", "currently", "checked", "out", "will", "result", "in", "a", "panic", "because", "that", "should", "never", "happen", "except", "in", "the", "case", "of", "a", "programming", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/id_pool.go#L64-L84
train
vitessio/vitess
go/vt/mysqlctl/backup.go
removeExistingFiles
func removeExistingFiles(cnf *Mycnf) error { paths := map[string]string{ "BinLogPath.*": cnf.BinLogPath, "DataDir": cnf.DataDir, "InnodbDataHomeDir": cnf.InnodbDataHomeDir, "InnodbLogGroupHomeDir": cnf.InnodbLogGroupHomeDir, "RelayLogPath.*": cnf.RelayLogPath, "RelayLogIndexPath": cnf.RelayLogIndexPath, "RelayLogInfoPath": cnf.RelayLogInfoPath, } for name, path := range paths { if path == "" { return vterrors.Errorf(vtrpc.Code_UNKNOWN, "can't remove existing files: %v is unknown", name) } if strings.HasSuffix(name, ".*") { // These paths are actually filename prefixes, not directories. // An extension of the form ".###" is appended by mysqld. path += ".*" log.Infof("Restore: removing files in %v (%v)", name, path) matches, err := filepath.Glob(path) if err != nil { return vterrors.Wrapf(err, "can't expand path glob %q", path) } for _, match := range matches { if err := os.Remove(match); err != nil { return vterrors.Wrapf(err, "can't remove existing file from %v (%v)", name, match) } } continue } // Regular directory: delete recursively. if _, err := os.Stat(path); os.IsNotExist(err) { log.Infof("Restore: skipping removal of nonexistent %v (%v)", name, path) continue } log.Infof("Restore: removing files in %v (%v)", name, path) if err := os.RemoveAll(path); err != nil { return vterrors.Wrapf(err, "can't remove existing files in %v (%v)", name, path) } } return nil }
go
func removeExistingFiles(cnf *Mycnf) error { paths := map[string]string{ "BinLogPath.*": cnf.BinLogPath, "DataDir": cnf.DataDir, "InnodbDataHomeDir": cnf.InnodbDataHomeDir, "InnodbLogGroupHomeDir": cnf.InnodbLogGroupHomeDir, "RelayLogPath.*": cnf.RelayLogPath, "RelayLogIndexPath": cnf.RelayLogIndexPath, "RelayLogInfoPath": cnf.RelayLogInfoPath, } for name, path := range paths { if path == "" { return vterrors.Errorf(vtrpc.Code_UNKNOWN, "can't remove existing files: %v is unknown", name) } if strings.HasSuffix(name, ".*") { // These paths are actually filename prefixes, not directories. // An extension of the form ".###" is appended by mysqld. path += ".*" log.Infof("Restore: removing files in %v (%v)", name, path) matches, err := filepath.Glob(path) if err != nil { return vterrors.Wrapf(err, "can't expand path glob %q", path) } for _, match := range matches { if err := os.Remove(match); err != nil { return vterrors.Wrapf(err, "can't remove existing file from %v (%v)", name, match) } } continue } // Regular directory: delete recursively. if _, err := os.Stat(path); os.IsNotExist(err) { log.Infof("Restore: skipping removal of nonexistent %v (%v)", name, path) continue } log.Infof("Restore: removing files in %v (%v)", name, path) if err := os.RemoveAll(path); err != nil { return vterrors.Wrapf(err, "can't remove existing files in %v (%v)", name, path) } } return nil }
[ "func", "removeExistingFiles", "(", "cnf", "*", "Mycnf", ")", "error", "{", "paths", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "cnf", ".", "BinLogPath", ",", "\"", "\"", ":", "cnf", ".", "DataDir", ",", "\"", "\"", ":", "cnf", ".", "InnodbDataHomeDir", ",", "\"", "\"", ":", "cnf", ".", "InnodbLogGroupHomeDir", ",", "\"", "\"", ":", "cnf", ".", "RelayLogPath", ",", "\"", "\"", ":", "cnf", ".", "RelayLogIndexPath", ",", "\"", "\"", ":", "cnf", ".", "RelayLogInfoPath", ",", "}", "\n", "for", "name", ",", "path", ":=", "range", "paths", "{", "if", "path", "==", "\"", "\"", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_UNKNOWN", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "if", "strings", ".", "HasSuffix", "(", "name", ",", "\"", "\"", ")", "{", "// These paths are actually filename prefixes, not directories.", "// An extension of the form \".###\" is appended by mysqld.", "path", "+=", "\"", "\"", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "path", ")", "\n", "matches", ",", "err", ":=", "filepath", ".", "Glob", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "for", "_", ",", "match", ":=", "range", "matches", "{", "if", "err", ":=", "os", ".", "Remove", "(", "match", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "name", ",", "match", ")", "\n", "}", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// Regular directory: delete recursively.", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "path", ")", "\n", "continue", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "path", ")", "\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "name", ",", "path", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// removeExistingFiles will delete existing files in the data dir to prevent // conflicts with the restored archive. In particular, binlogs can be created // even during initial bootstrap, and these can interfere with configuring // replication if kept around after the restore.
[ "removeExistingFiles", "will", "delete", "existing", "files", "in", "the", "data", "dir", "to", "prevent", "conflicts", "with", "the", "restored", "archive", ".", "In", "particular", "binlogs", "can", "be", "created", "even", "during", "initial", "bootstrap", "and", "these", "can", "interfere", "with", "configuring", "replication", "if", "kept", "around", "after", "the", "restore", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/backup.go#L163-L206
train
vitessio/vitess
go/vt/workflow/node.go
BroadcastChanges
func (n *Node) BroadcastChanges(updateChildren bool) error { n.nodeManager.mu.Lock() defer n.nodeManager.mu.Unlock() return n.nodeManager.updateNodeAndBroadcastLocked(n, updateChildren) }
go
func (n *Node) BroadcastChanges(updateChildren bool) error { n.nodeManager.mu.Lock() defer n.nodeManager.mu.Unlock() return n.nodeManager.updateNodeAndBroadcastLocked(n, updateChildren) }
[ "func", "(", "n", "*", "Node", ")", "BroadcastChanges", "(", "updateChildren", "bool", ")", "error", "{", "n", ".", "nodeManager", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "n", ".", "nodeManager", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "n", ".", "nodeManager", ".", "updateNodeAndBroadcastLocked", "(", "n", ",", "updateChildren", ")", "\n", "}" ]
// BroadcastChanges sends the new contents of the node to the watchers.
[ "BroadcastChanges", "sends", "the", "new", "contents", "of", "the", "node", "to", "the", "watchers", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L193-L197
train
vitessio/vitess
go/vt/workflow/node.go
deepCopyFrom
func (n *Node) deepCopyFrom(otherNode *Node, copyChildren bool) error { oldChildren := n.Children *n = *otherNode n.Children = oldChildren n.Actions = []*Action{} for _, otherAction := range otherNode.Actions { action := &Action{} *action = *otherAction n.Actions = append(n.Actions, action) } if !copyChildren { return nil } n.Children = []*Node{} childNamesSet := make(map[string]bool) for _, otherChild := range otherNode.Children { if _, ok := childNamesSet[otherChild.PathName]; ok { return fmt.Errorf("node %v already has a child name %v", n.Path, otherChild.PathName) } childNamesSet[otherChild.PathName] = true // Populate a few values in case the otherChild is newly created by user. otherChild.nodeManager = n.nodeManager otherChild.Path = path.Join(n.Path, otherChild.PathName) child := NewNode() child.deepCopyFrom(otherChild, true /* copyChildren */) n.Children = append(n.Children, child) } return nil }
go
func (n *Node) deepCopyFrom(otherNode *Node, copyChildren bool) error { oldChildren := n.Children *n = *otherNode n.Children = oldChildren n.Actions = []*Action{} for _, otherAction := range otherNode.Actions { action := &Action{} *action = *otherAction n.Actions = append(n.Actions, action) } if !copyChildren { return nil } n.Children = []*Node{} childNamesSet := make(map[string]bool) for _, otherChild := range otherNode.Children { if _, ok := childNamesSet[otherChild.PathName]; ok { return fmt.Errorf("node %v already has a child name %v", n.Path, otherChild.PathName) } childNamesSet[otherChild.PathName] = true // Populate a few values in case the otherChild is newly created by user. otherChild.nodeManager = n.nodeManager otherChild.Path = path.Join(n.Path, otherChild.PathName) child := NewNode() child.deepCopyFrom(otherChild, true /* copyChildren */) n.Children = append(n.Children, child) } return nil }
[ "func", "(", "n", "*", "Node", ")", "deepCopyFrom", "(", "otherNode", "*", "Node", ",", "copyChildren", "bool", ")", "error", "{", "oldChildren", ":=", "n", ".", "Children", "\n", "*", "n", "=", "*", "otherNode", "\n", "n", ".", "Children", "=", "oldChildren", "\n\n", "n", ".", "Actions", "=", "[", "]", "*", "Action", "{", "}", "\n", "for", "_", ",", "otherAction", ":=", "range", "otherNode", ".", "Actions", "{", "action", ":=", "&", "Action", "{", "}", "\n", "*", "action", "=", "*", "otherAction", "\n", "n", ".", "Actions", "=", "append", "(", "n", ".", "Actions", ",", "action", ")", "\n", "}", "\n\n", "if", "!", "copyChildren", "{", "return", "nil", "\n", "}", "\n", "n", ".", "Children", "=", "[", "]", "*", "Node", "{", "}", "\n", "childNamesSet", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "otherChild", ":=", "range", "otherNode", ".", "Children", "{", "if", "_", ",", "ok", ":=", "childNamesSet", "[", "otherChild", ".", "PathName", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ".", "Path", ",", "otherChild", ".", "PathName", ")", "\n", "}", "\n", "childNamesSet", "[", "otherChild", ".", "PathName", "]", "=", "true", "\n\n", "// Populate a few values in case the otherChild is newly created by user.", "otherChild", ".", "nodeManager", "=", "n", ".", "nodeManager", "\n", "otherChild", ".", "Path", "=", "path", ".", "Join", "(", "n", ".", "Path", ",", "otherChild", ".", "PathName", ")", "\n\n", "child", ":=", "NewNode", "(", ")", "\n", "child", ".", "deepCopyFrom", "(", "otherChild", ",", "true", "/* copyChildren */", ")", "\n", "n", ".", "Children", "=", "append", "(", "n", ".", "Children", ",", "child", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// deepCopyFrom copies contents of otherNode into this node. Contents of Actions // is copied into new Action objects, so that changes in otherNode are not // immediately visible in this node. When copyChildren is false the contents of // Children in this node is preserved fully even if it doesn't match the contents // of otherNode. When copyChildren is true then contents of Children is copied // into new Node objects similar to contents of Actions. // Method returns error if children in otherNode have non-unique values of // PathName, i.e. it's impossible to create unique values of Path for them.
[ "deepCopyFrom", "copies", "contents", "of", "otherNode", "into", "this", "node", ".", "Contents", "of", "Actions", "is", "copied", "into", "new", "Action", "objects", "so", "that", "changes", "in", "otherNode", "are", "not", "immediately", "visible", "in", "this", "node", ".", "When", "copyChildren", "is", "false", "the", "contents", "of", "Children", "in", "this", "node", "is", "preserved", "fully", "even", "if", "it", "doesn", "t", "match", "the", "contents", "of", "otherNode", ".", "When", "copyChildren", "is", "true", "then", "contents", "of", "Children", "is", "copied", "into", "new", "Node", "objects", "similar", "to", "contents", "of", "Actions", ".", "Method", "returns", "error", "if", "children", "in", "otherNode", "have", "non", "-", "unique", "values", "of", "PathName", "i", ".", "e", ".", "it", "s", "impossible", "to", "create", "unique", "values", "of", "Path", "for", "them", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L207-L239
train
vitessio/vitess
go/vt/workflow/node.go
GetChildByPath
func (n *Node) GetChildByPath(subPath string) (*Node, error) { // Find the subnode if needed. parts := strings.Split(subPath, "/") currentNode := n for i := 0; i < len(parts); i++ { childPathName := parts[i] found := false for _, child := range currentNode.Children { if child.PathName == childPathName { found = true currentNode = child break } } if !found { return nil, fmt.Errorf("node %v has no children named %v", currentNode.Path, childPathName) } } return currentNode, nil }
go
func (n *Node) GetChildByPath(subPath string) (*Node, error) { // Find the subnode if needed. parts := strings.Split(subPath, "/") currentNode := n for i := 0; i < len(parts); i++ { childPathName := parts[i] found := false for _, child := range currentNode.Children { if child.PathName == childPathName { found = true currentNode = child break } } if !found { return nil, fmt.Errorf("node %v has no children named %v", currentNode.Path, childPathName) } } return currentNode, nil }
[ "func", "(", "n", "*", "Node", ")", "GetChildByPath", "(", "subPath", "string", ")", "(", "*", "Node", ",", "error", ")", "{", "// Find the subnode if needed.", "parts", ":=", "strings", ".", "Split", "(", "subPath", ",", "\"", "\"", ")", "\n\n", "currentNode", ":=", "n", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "parts", ")", ";", "i", "++", "{", "childPathName", ":=", "parts", "[", "i", "]", "\n", "found", ":=", "false", "\n", "for", "_", ",", "child", ":=", "range", "currentNode", ".", "Children", "{", "if", "child", ".", "PathName", "==", "childPathName", "{", "found", "=", "true", "\n", "currentNode", "=", "child", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "currentNode", ".", "Path", ",", "childPathName", ")", "\n", "}", "\n", "}", "\n", "return", "currentNode", ",", "nil", "\n", "}" ]
// GetChildByPath returns the child node given the relative path to this node. // The caller must ensure that the node tree is not modified during the call.
[ "GetChildByPath", "returns", "the", "child", "node", "given", "the", "relative", "path", "to", "this", "node", ".", "The", "caller", "must", "ensure", "that", "the", "node", "tree", "is", "not", "modified", "during", "the", "call", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L243-L263
train
vitessio/vitess
go/vt/workflow/node.go
NewNodeManager
func NewNodeManager() *NodeManager { return &NodeManager{ roots: make(map[string]*Node), watchers: make(map[int]chan []byte), nextWatcherIndex: 1, } }
go
func NewNodeManager() *NodeManager { return &NodeManager{ roots: make(map[string]*Node), watchers: make(map[int]chan []byte), nextWatcherIndex: 1, } }
[ "func", "NewNodeManager", "(", ")", "*", "NodeManager", "{", "return", "&", "NodeManager", "{", "roots", ":", "make", "(", "map", "[", "string", "]", "*", "Node", ")", ",", "watchers", ":", "make", "(", "map", "[", "int", "]", "chan", "[", "]", "byte", ")", ",", "nextWatcherIndex", ":", "1", ",", "}", "\n", "}" ]
// NewNodeManager returns a new NodeManager.
[ "NewNodeManager", "returns", "a", "new", "NodeManager", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L291-L297
train
vitessio/vitess
go/vt/workflow/node.go
AddRootNode
func (m *NodeManager) AddRootNode(n *Node) error { m.mu.Lock() defer m.mu.Unlock() if _, ok := m.roots[n.PathName]; ok { return fmt.Errorf("toplevel node %v (with name %v) already exists", n.Path, n.Name) } n.Path = "/" + n.PathName n.nodeManager = m savedNode := NewNode() m.roots[n.PathName] = savedNode return m.updateNodeAndBroadcastLocked(n, true /* updateChildren */) }
go
func (m *NodeManager) AddRootNode(n *Node) error { m.mu.Lock() defer m.mu.Unlock() if _, ok := m.roots[n.PathName]; ok { return fmt.Errorf("toplevel node %v (with name %v) already exists", n.Path, n.Name) } n.Path = "/" + n.PathName n.nodeManager = m savedNode := NewNode() m.roots[n.PathName] = savedNode return m.updateNodeAndBroadcastLocked(n, true /* updateChildren */) }
[ "func", "(", "m", "*", "NodeManager", ")", "AddRootNode", "(", "n", "*", "Node", ")", "error", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "m", ".", "roots", "[", "n", ".", "PathName", "]", ";", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ".", "Path", ",", "n", ".", "Name", ")", "\n", "}", "\n", "n", ".", "Path", "=", "\"", "\"", "+", "n", ".", "PathName", "\n", "n", ".", "nodeManager", "=", "m", "\n\n", "savedNode", ":=", "NewNode", "(", ")", "\n", "m", ".", "roots", "[", "n", ".", "PathName", "]", "=", "savedNode", "\n", "return", "m", ".", "updateNodeAndBroadcastLocked", "(", "n", ",", "true", "/* updateChildren */", ")", "\n", "}" ]
// AddRootNode adds a toplevel Node to the NodeManager, // and broadcasts the Node to the listeners.
[ "AddRootNode", "adds", "a", "toplevel", "Node", "to", "the", "NodeManager", "and", "broadcasts", "the", "Node", "to", "the", "listeners", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L301-L314
train
vitessio/vitess
go/vt/workflow/node.go
RemoveRootNode
func (m *NodeManager) RemoveRootNode(n *Node) { m.mu.Lock() defer m.mu.Unlock() delete(m.roots, n.PathName) u := &Update{ Deletes: []string{n.Path}, } m.broadcastUpdateLocked(u) }
go
func (m *NodeManager) RemoveRootNode(n *Node) { m.mu.Lock() defer m.mu.Unlock() delete(m.roots, n.PathName) u := &Update{ Deletes: []string{n.Path}, } m.broadcastUpdateLocked(u) }
[ "func", "(", "m", "*", "NodeManager", ")", "RemoveRootNode", "(", "n", "*", "Node", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "m", ".", "roots", ",", "n", ".", "PathName", ")", "\n\n", "u", ":=", "&", "Update", "{", "Deletes", ":", "[", "]", "string", "{", "n", ".", "Path", "}", ",", "}", "\n", "m", ".", "broadcastUpdateLocked", "(", "u", ")", "\n", "}" ]
// RemoveRootNode removes a toplevel Node from the NodeManager, // and broadcasts the change to the listeners.
[ "RemoveRootNode", "removes", "a", "toplevel", "Node", "from", "the", "NodeManager", "and", "broadcasts", "the", "change", "to", "the", "listeners", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L318-L328
train
vitessio/vitess
go/vt/workflow/node.go
GetFullTree
func (m *NodeManager) GetFullTree() ([]byte, error) { m.mu.Lock() defer m.mu.Unlock() return m.toJSON(0) }
go
func (m *NodeManager) GetFullTree() ([]byte, error) { m.mu.Lock() defer m.mu.Unlock() return m.toJSON(0) }
[ "func", "(", "m", "*", "NodeManager", ")", "GetFullTree", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "m", ".", "toJSON", "(", "0", ")", "\n", "}" ]
// GetFullTree returns the JSON representation of the entire Node tree.
[ "GetFullTree", "returns", "the", "JSON", "representation", "of", "the", "entire", "Node", "tree", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L345-L349
train
vitessio/vitess
go/vt/workflow/node.go
GetAndWatchFullTree
func (m *NodeManager) GetAndWatchFullTree(notifications chan []byte) ([]byte, int, error) { m.mu.Lock() defer m.mu.Unlock() i := m.nextWatcherIndex m.nextWatcherIndex++ result, err := m.toJSON(i) if err != nil { return nil, 0, err } // It worked, register the watcher. m.watchers[i] = notifications return result, i, nil }
go
func (m *NodeManager) GetAndWatchFullTree(notifications chan []byte) ([]byte, int, error) { m.mu.Lock() defer m.mu.Unlock() i := m.nextWatcherIndex m.nextWatcherIndex++ result, err := m.toJSON(i) if err != nil { return nil, 0, err } // It worked, register the watcher. m.watchers[i] = notifications return result, i, nil }
[ "func", "(", "m", "*", "NodeManager", ")", "GetAndWatchFullTree", "(", "notifications", "chan", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "int", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "i", ":=", "m", ".", "nextWatcherIndex", "\n", "m", ".", "nextWatcherIndex", "++", "\n\n", "result", ",", "err", ":=", "m", ".", "toJSON", "(", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "// It worked, register the watcher.", "m", ".", "watchers", "[", "i", "]", "=", "notifications", "\n", "return", "result", ",", "i", ",", "nil", "\n", "}" ]
// GetAndWatchFullTree returns the JSON representation of the entire Node tree, // and registers a watcher to monitor changes to the tree.
[ "GetAndWatchFullTree", "returns", "the", "JSON", "representation", "of", "the", "entire", "Node", "tree", "and", "registers", "a", "watcher", "to", "monitor", "changes", "to", "the", "tree", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L353-L368
train
vitessio/vitess
go/vt/workflow/node.go
broadcastUpdateLocked
func (m *NodeManager) broadcastUpdateLocked(u *Update) { data, err := json.Marshal(u) if err != nil { log.Errorf("Cannot JSON encode update: %v", err) return } // If we can't write on the channel, we close it and remove it // from the list. It probably means the web browser on the // other side is not there any more. for i, watcher := range m.watchers { select { case watcher <- data: default: log.Infof("Couldn't write to watcher %v, closing it.", i) close(watcher) delete(m.watchers, i) } } }
go
func (m *NodeManager) broadcastUpdateLocked(u *Update) { data, err := json.Marshal(u) if err != nil { log.Errorf("Cannot JSON encode update: %v", err) return } // If we can't write on the channel, we close it and remove it // from the list. It probably means the web browser on the // other side is not there any more. for i, watcher := range m.watchers { select { case watcher <- data: default: log.Infof("Couldn't write to watcher %v, closing it.", i) close(watcher) delete(m.watchers, i) } } }
[ "func", "(", "m", "*", "NodeManager", ")", "broadcastUpdateLocked", "(", "u", "*", "Update", ")", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// If we can't write on the channel, we close it and remove it", "// from the list. It probably means the web browser on the", "// other side is not there any more.", "for", "i", ",", "watcher", ":=", "range", "m", ".", "watchers", "{", "select", "{", "case", "watcher", "<-", "data", ":", "default", ":", "log", ".", "Infof", "(", "\"", "\"", ",", "i", ")", "\n", "close", "(", "watcher", ")", "\n", "delete", "(", "m", ".", "watchers", ",", "i", ")", "\n", "}", "\n", "}", "\n", "}" ]
// broadcastUpdateLocked sends the provided update to all watchers. // Has to be called with the lock.
[ "broadcastUpdateLocked", "sends", "the", "provided", "update", "to", "all", "watchers", ".", "Has", "to", "be", "called", "with", "the", "lock", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L372-L391
train
vitessio/vitess
go/vt/workflow/node.go
CloseWatcher
func (m *NodeManager) CloseWatcher(i int) { m.mu.Lock() defer m.mu.Unlock() delete(m.watchers, i) }
go
func (m *NodeManager) CloseWatcher(i int) { m.mu.Lock() defer m.mu.Unlock() delete(m.watchers, i) }
[ "func", "(", "m", "*", "NodeManager", ")", "CloseWatcher", "(", "i", "int", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "m", ".", "watchers", ",", "i", ")", "\n", "}" ]
// CloseWatcher unregisters the watcher from this Manager.
[ "CloseWatcher", "unregisters", "the", "watcher", "from", "this", "Manager", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L426-L431
train
vitessio/vitess
go/vt/workflow/node.go
Action
func (m *NodeManager) Action(ctx context.Context, ap *ActionParameters) error { n, err := m.getNodeByPath(ap.Path) if err != nil { return err } m.mu.Lock() if n.Listener == nil { m.mu.Unlock() return fmt.Errorf("Action %v is invoked on a node without listener (node path is %v)", ap.Name, ap.Path) } nodeListener := n.Listener m.mu.Unlock() return nodeListener.Action(ctx, ap.Path, ap.Name) }
go
func (m *NodeManager) Action(ctx context.Context, ap *ActionParameters) error { n, err := m.getNodeByPath(ap.Path) if err != nil { return err } m.mu.Lock() if n.Listener == nil { m.mu.Unlock() return fmt.Errorf("Action %v is invoked on a node without listener (node path is %v)", ap.Name, ap.Path) } nodeListener := n.Listener m.mu.Unlock() return nodeListener.Action(ctx, ap.Path, ap.Name) }
[ "func", "(", "m", "*", "NodeManager", ")", "Action", "(", "ctx", "context", ".", "Context", ",", "ap", "*", "ActionParameters", ")", "error", "{", "n", ",", "err", ":=", "m", ".", "getNodeByPath", "(", "ap", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n\n", "if", "n", ".", "Listener", "==", "nil", "{", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ap", ".", "Name", ",", "ap", ".", "Path", ")", "\n", "}", "\n", "nodeListener", ":=", "n", ".", "Listener", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "nodeListener", ".", "Action", "(", "ctx", ",", "ap", ".", "Path", ",", "ap", ".", "Name", ")", "\n", "}" ]
// Action is called by the UI agents to trigger actions.
[ "Action", "is", "called", "by", "the", "UI", "agents", "to", "trigger", "actions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/node.go#L434-L450
train
vitessio/vitess
go/mysql/mysql56_gtid.go
parseMysql56GTID
func parseMysql56GTID(s string) (GTID, error) { // Split into parts. parts := strings.Split(s, ":") if len(parts) != 2 { return nil, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid MySQL 5.6 GTID (%v): expecting UUID:Sequence", s) } // Parse Server ID. sid, err := ParseSID(parts[0]) if err != nil { return nil, vterrors.Wrapf(err, "invalid MySQL 5.6 GTID Server ID (%v)", parts[0]) } // Parse Sequence number. seq, err := strconv.ParseInt(parts[1], 10, 64) if err != nil { return nil, vterrors.Wrapf(err, "invalid MySQL 5.6 GTID Sequence number (%v)", parts[1]) } return Mysql56GTID{Server: sid, Sequence: seq}, nil }
go
func parseMysql56GTID(s string) (GTID, error) { // Split into parts. parts := strings.Split(s, ":") if len(parts) != 2 { return nil, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid MySQL 5.6 GTID (%v): expecting UUID:Sequence", s) } // Parse Server ID. sid, err := ParseSID(parts[0]) if err != nil { return nil, vterrors.Wrapf(err, "invalid MySQL 5.6 GTID Server ID (%v)", parts[0]) } // Parse Sequence number. seq, err := strconv.ParseInt(parts[1], 10, 64) if err != nil { return nil, vterrors.Wrapf(err, "invalid MySQL 5.6 GTID Sequence number (%v)", parts[1]) } return Mysql56GTID{Server: sid, Sequence: seq}, nil }
[ "func", "parseMysql56GTID", "(", "s", "string", ")", "(", "GTID", ",", "error", ")", "{", "// Split into parts.", "parts", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "!=", "2", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "s", ")", "\n", "}", "\n\n", "// Parse Server ID.", "sid", ",", "err", ":=", "ParseSID", "(", "parts", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "parts", "[", "0", "]", ")", "\n", "}", "\n\n", "// Parse Sequence number.", "seq", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "parts", "[", "1", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "parts", "[", "1", "]", ")", "\n", "}", "\n\n", "return", "Mysql56GTID", "{", "Server", ":", "sid", ",", "Sequence", ":", "seq", "}", ",", "nil", "\n", "}" ]
// parseMysql56GTID is registered as a GTID parser.
[ "parseMysql56GTID", "is", "registered", "as", "a", "GTID", "parser", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid.go#L32-L52
train
vitessio/vitess
go/mysql/mysql56_gtid.go
String
func (sid SID) String() string { dst := []byte("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") hex.Encode(dst, sid[:4]) hex.Encode(dst[9:], sid[4:6]) hex.Encode(dst[14:], sid[6:8]) hex.Encode(dst[19:], sid[8:10]) hex.Encode(dst[24:], sid[10:16]) return string(dst) }
go
func (sid SID) String() string { dst := []byte("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") hex.Encode(dst, sid[:4]) hex.Encode(dst[9:], sid[4:6]) hex.Encode(dst[14:], sid[6:8]) hex.Encode(dst[19:], sid[8:10]) hex.Encode(dst[24:], sid[10:16]) return string(dst) }
[ "func", "(", "sid", "SID", ")", "String", "(", ")", "string", "{", "dst", ":=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "hex", ".", "Encode", "(", "dst", ",", "sid", "[", ":", "4", "]", ")", "\n", "hex", ".", "Encode", "(", "dst", "[", "9", ":", "]", ",", "sid", "[", "4", ":", "6", "]", ")", "\n", "hex", ".", "Encode", "(", "dst", "[", "14", ":", "]", ",", "sid", "[", "6", ":", "8", "]", ")", "\n", "hex", ".", "Encode", "(", "dst", "[", "19", ":", "]", ",", "sid", "[", "8", ":", "10", "]", ")", "\n", "hex", ".", "Encode", "(", "dst", "[", "24", ":", "]", ",", "sid", "[", "10", ":", "16", "]", ")", "\n", "return", "string", "(", "dst", ")", "\n", "}" ]
// String prints an SID in the form used by MySQL 5.6.
[ "String", "prints", "an", "SID", "in", "the", "form", "used", "by", "MySQL", "5", ".", "6", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid.go#L58-L66
train
vitessio/vitess
go/mysql/mysql56_gtid.go
ParseSID
func ParseSID(s string) (sid SID, err error) { if len(s) != 36 || s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { return sid, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid MySQL 5.6 SID %q", s) } // Drop the dashes so we can just check the error of Decode once. b := make([]byte, 0, 32) b = append(b, s[:8]...) b = append(b, s[9:13]...) b = append(b, s[14:18]...) b = append(b, s[19:23]...) b = append(b, s[24:]...) if _, err := hex.Decode(sid[:], b); err != nil { return sid, vterrors.Wrapf(err, "invalid MySQL 5.6 SID %q", s) } return sid, nil }
go
func ParseSID(s string) (sid SID, err error) { if len(s) != 36 || s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { return sid, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid MySQL 5.6 SID %q", s) } // Drop the dashes so we can just check the error of Decode once. b := make([]byte, 0, 32) b = append(b, s[:8]...) b = append(b, s[9:13]...) b = append(b, s[14:18]...) b = append(b, s[19:23]...) b = append(b, s[24:]...) if _, err := hex.Decode(sid[:], b); err != nil { return sid, vterrors.Wrapf(err, "invalid MySQL 5.6 SID %q", s) } return sid, nil }
[ "func", "ParseSID", "(", "s", "string", ")", "(", "sid", "SID", ",", "err", "error", ")", "{", "if", "len", "(", "s", ")", "!=", "36", "||", "s", "[", "8", "]", "!=", "'-'", "||", "s", "[", "13", "]", "!=", "'-'", "||", "s", "[", "18", "]", "!=", "'-'", "||", "s", "[", "23", "]", "!=", "'-'", "{", "return", "sid", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "s", ")", "\n", "}", "\n\n", "// Drop the dashes so we can just check the error of Decode once.", "b", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "32", ")", "\n", "b", "=", "append", "(", "b", ",", "s", "[", ":", "8", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "s", "[", "9", ":", "13", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "s", "[", "14", ":", "18", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "s", "[", "19", ":", "23", "]", "...", ")", "\n", "b", "=", "append", "(", "b", ",", "s", "[", "24", ":", "]", "...", ")", "\n\n", "if", "_", ",", "err", ":=", "hex", ".", "Decode", "(", "sid", "[", ":", "]", ",", "b", ")", ";", "err", "!=", "nil", "{", "return", "sid", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "s", ")", "\n", "}", "\n", "return", "sid", ",", "nil", "\n", "}" ]
// ParseSID parses an SID in the form used by MySQL 5.6.
[ "ParseSID", "parses", "an", "SID", "in", "the", "form", "used", "by", "MySQL", "5", ".", "6", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid.go#L69-L86
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
Open
func (tpc *TwoPC) Open(dbconfigs *dbconfigs.DBConfigs) { tpc.readPool.Open(dbconfigs.AppWithDB(), dbconfigs.DbaWithDB(), dbconfigs.DbaWithDB()) }
go
func (tpc *TwoPC) Open(dbconfigs *dbconfigs.DBConfigs) { tpc.readPool.Open(dbconfigs.AppWithDB(), dbconfigs.DbaWithDB(), dbconfigs.DbaWithDB()) }
[ "func", "(", "tpc", "*", "TwoPC", ")", "Open", "(", "dbconfigs", "*", "dbconfigs", ".", "DBConfigs", ")", "{", "tpc", ".", "readPool", ".", "Open", "(", "dbconfigs", ".", "AppWithDB", "(", ")", ",", "dbconfigs", ".", "DbaWithDB", "(", ")", ",", "dbconfigs", ".", "DbaWithDB", "(", ")", ")", "\n", "}" ]
// Open starts the TwoPC service.
[ "Open", "starts", "the", "TwoPC", "service", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L203-L205
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
SaveRedo
func (tpc *TwoPC) SaveRedo(ctx context.Context, conn *TxConnection, dtid string, queries []string) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(RedoStatePrepared), "time_created": sqltypes.Int64BindVariable(time.Now().UnixNano()), } _, err := tpc.exec(ctx, conn, tpc.insertRedoTx, bindVars) if err != nil { return err } rows := make([][]sqltypes.Value, len(queries)) for i, query := range queries { rows[i] = []sqltypes.Value{ sqltypes.NewVarBinary(dtid), sqltypes.NewInt64(int64(i + 1)), sqltypes.NewVarBinary(query), } } extras := map[string]sqlparser.Encodable{ "vals": sqlparser.InsertValues(rows), } q, err := tpc.insertRedoStmt.GenerateQuery(nil, extras) if err != nil { return err } _, err = conn.Exec(ctx, q, 1, false) return err }
go
func (tpc *TwoPC) SaveRedo(ctx context.Context, conn *TxConnection, dtid string, queries []string) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(RedoStatePrepared), "time_created": sqltypes.Int64BindVariable(time.Now().UnixNano()), } _, err := tpc.exec(ctx, conn, tpc.insertRedoTx, bindVars) if err != nil { return err } rows := make([][]sqltypes.Value, len(queries)) for i, query := range queries { rows[i] = []sqltypes.Value{ sqltypes.NewVarBinary(dtid), sqltypes.NewInt64(int64(i + 1)), sqltypes.NewVarBinary(query), } } extras := map[string]sqlparser.Encodable{ "vals": sqlparser.InsertValues(rows), } q, err := tpc.insertRedoStmt.GenerateQuery(nil, extras) if err != nil { return err } _, err = conn.Exec(ctx, q, 1, false) return err }
[ "func", "(", "tpc", "*", "TwoPC", ")", "SaveRedo", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "TxConnection", ",", "dtid", "string", ",", "queries", "[", "]", "string", ")", "error", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "StringBindVariable", "(", "dtid", ")", ",", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "RedoStatePrepared", ")", ",", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ",", "}", "\n", "_", ",", "err", ":=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "insertRedoTx", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "rows", ":=", "make", "(", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "len", "(", "queries", ")", ")", "\n", "for", "i", ",", "query", ":=", "range", "queries", "{", "rows", "[", "i", "]", "=", "[", "]", "sqltypes", ".", "Value", "{", "sqltypes", ".", "NewVarBinary", "(", "dtid", ")", ",", "sqltypes", ".", "NewInt64", "(", "int64", "(", "i", "+", "1", ")", ")", ",", "sqltypes", ".", "NewVarBinary", "(", "query", ")", ",", "}", "\n", "}", "\n", "extras", ":=", "map", "[", "string", "]", "sqlparser", ".", "Encodable", "{", "\"", "\"", ":", "sqlparser", ".", "InsertValues", "(", "rows", ")", ",", "}", "\n", "q", ",", "err", ":=", "tpc", ".", "insertRedoStmt", ".", "GenerateQuery", "(", "nil", ",", "extras", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "conn", ".", "Exec", "(", "ctx", ",", "q", ",", "1", ",", "false", ")", "\n", "return", "err", "\n", "}" ]
// SaveRedo saves the statements in the redo log using the supplied connection.
[ "SaveRedo", "saves", "the", "statements", "in", "the", "redo", "log", "using", "the", "supplied", "connection", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L213-L241
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
UpdateRedo
func (tpc *TwoPC) UpdateRedo(ctx context.Context, conn *TxConnection, dtid string, state int) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(int64(state)), } _, err := tpc.exec(ctx, conn, tpc.updateRedoTx, bindVars) return err }
go
func (tpc *TwoPC) UpdateRedo(ctx context.Context, conn *TxConnection, dtid string, state int) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(int64(state)), } _, err := tpc.exec(ctx, conn, tpc.updateRedoTx, bindVars) return err }
[ "func", "(", "tpc", "*", "TwoPC", ")", "UpdateRedo", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "TxConnection", ",", "dtid", "string", ",", "state", "int", ")", "error", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "StringBindVariable", "(", "dtid", ")", ",", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "int64", "(", "state", ")", ")", ",", "}", "\n", "_", ",", "err", ":=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "updateRedoTx", ",", "bindVars", ")", "\n", "return", "err", "\n", "}" ]
// UpdateRedo changes the state of the redo log for the dtid.
[ "UpdateRedo", "changes", "the", "state", "of", "the", "redo", "log", "for", "the", "dtid", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L244-L251
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
DeleteRedo
func (tpc *TwoPC) DeleteRedo(ctx context.Context, conn *TxConnection, dtid string) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), } _, err := tpc.exec(ctx, conn, tpc.deleteRedoTx, bindVars) if err != nil { return err } _, err = tpc.exec(ctx, conn, tpc.deleteRedoStmt, bindVars) return err }
go
func (tpc *TwoPC) DeleteRedo(ctx context.Context, conn *TxConnection, dtid string) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), } _, err := tpc.exec(ctx, conn, tpc.deleteRedoTx, bindVars) if err != nil { return err } _, err = tpc.exec(ctx, conn, tpc.deleteRedoStmt, bindVars) return err }
[ "func", "(", "tpc", "*", "TwoPC", ")", "DeleteRedo", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "TxConnection", ",", "dtid", "string", ")", "error", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "StringBindVariable", "(", "dtid", ")", ",", "}", "\n", "_", ",", "err", ":=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "deleteRedoTx", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "deleteRedoStmt", ",", "bindVars", ")", "\n", "return", "err", "\n", "}" ]
// DeleteRedo deletes the redo log for the dtid.
[ "DeleteRedo", "deletes", "the", "redo", "log", "for", "the", "dtid", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L254-L264
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
ReadAllRedo
func (tpc *TwoPC) ReadAllRedo(ctx context.Context) (prepared, failed []*PreparedTx, err error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, nil, err } defer conn.Recycle() qr, err := conn.Exec(ctx, tpc.readAllRedo, 10000, false) if err != nil { return nil, nil, err } var curTx *PreparedTx for _, row := range qr.Rows { dtid := row[0].ToString() if curTx == nil || dtid != curTx.Dtid { // Initialize the new element. // A failure in time parsing will show up as a very old time, // which is harmless. tm, _ := sqltypes.ToInt64(row[2]) curTx = &PreparedTx{ Dtid: dtid, Time: time.Unix(0, tm), } st, err := sqltypes.ToInt64(row[1]) if err != nil { log.Errorf("Error parsing state for dtid %s: %v.", dtid, err) } switch st { case RedoStatePrepared: prepared = append(prepared, curTx) default: if st != RedoStateFailed { log.Errorf("Unexpected state for dtid %s: %d. Treating it as a failure.", dtid, st) } failed = append(failed, curTx) } } curTx.Queries = append(curTx.Queries, row[3].ToString()) } return prepared, failed, nil }
go
func (tpc *TwoPC) ReadAllRedo(ctx context.Context) (prepared, failed []*PreparedTx, err error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, nil, err } defer conn.Recycle() qr, err := conn.Exec(ctx, tpc.readAllRedo, 10000, false) if err != nil { return nil, nil, err } var curTx *PreparedTx for _, row := range qr.Rows { dtid := row[0].ToString() if curTx == nil || dtid != curTx.Dtid { // Initialize the new element. // A failure in time parsing will show up as a very old time, // which is harmless. tm, _ := sqltypes.ToInt64(row[2]) curTx = &PreparedTx{ Dtid: dtid, Time: time.Unix(0, tm), } st, err := sqltypes.ToInt64(row[1]) if err != nil { log.Errorf("Error parsing state for dtid %s: %v.", dtid, err) } switch st { case RedoStatePrepared: prepared = append(prepared, curTx) default: if st != RedoStateFailed { log.Errorf("Unexpected state for dtid %s: %d. Treating it as a failure.", dtid, st) } failed = append(failed, curTx) } } curTx.Queries = append(curTx.Queries, row[3].ToString()) } return prepared, failed, nil }
[ "func", "(", "tpc", "*", "TwoPC", ")", "ReadAllRedo", "(", "ctx", "context", ".", "Context", ")", "(", "prepared", ",", "failed", "[", "]", "*", "PreparedTx", ",", "err", "error", ")", "{", "conn", ",", "err", ":=", "tpc", ".", "readPool", ".", "Get", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n\n", "qr", ",", "err", ":=", "conn", ".", "Exec", "(", "ctx", ",", "tpc", ".", "readAllRedo", ",", "10000", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "var", "curTx", "*", "PreparedTx", "\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "dtid", ":=", "row", "[", "0", "]", ".", "ToString", "(", ")", "\n", "if", "curTx", "==", "nil", "||", "dtid", "!=", "curTx", ".", "Dtid", "{", "// Initialize the new element.", "// A failure in time parsing will show up as a very old time,", "// which is harmless.", "tm", ",", "_", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "2", "]", ")", "\n", "curTx", "=", "&", "PreparedTx", "{", "Dtid", ":", "dtid", ",", "Time", ":", "time", ".", "Unix", "(", "0", ",", "tm", ")", ",", "}", "\n", "st", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "err", ")", "\n", "}", "\n", "switch", "st", "{", "case", "RedoStatePrepared", ":", "prepared", "=", "append", "(", "prepared", ",", "curTx", ")", "\n", "default", ":", "if", "st", "!=", "RedoStateFailed", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "st", ")", "\n", "}", "\n", "failed", "=", "append", "(", "failed", ",", "curTx", ")", "\n", "}", "\n", "}", "\n", "curTx", ".", "Queries", "=", "append", "(", "curTx", ".", "Queries", ",", "row", "[", "3", "]", ".", "ToString", "(", ")", ")", "\n", "}", "\n", "return", "prepared", ",", "failed", ",", "nil", "\n", "}" ]
// ReadAllRedo returns all the prepared transactions from the redo logs.
[ "ReadAllRedo", "returns", "all", "the", "prepared", "transactions", "from", "the", "redo", "logs", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L274-L315
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
CountUnresolvedRedo
func (tpc *TwoPC) CountUnresolvedRedo(ctx context.Context, unresolvedTime time.Time) (int64, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return 0, err } defer conn.Recycle() bindVars := map[string]*querypb.BindVariable{ "time_created": sqltypes.Int64BindVariable(unresolvedTime.UnixNano()), } qr, err := tpc.read(ctx, conn, tpc.countUnresolvedRedo, bindVars) if err != nil { return 0, err } if len(qr.Rows) < 1 { return 0, nil } v, _ := sqltypes.ToInt64(qr.Rows[0][0]) return v, nil }
go
func (tpc *TwoPC) CountUnresolvedRedo(ctx context.Context, unresolvedTime time.Time) (int64, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return 0, err } defer conn.Recycle() bindVars := map[string]*querypb.BindVariable{ "time_created": sqltypes.Int64BindVariable(unresolvedTime.UnixNano()), } qr, err := tpc.read(ctx, conn, tpc.countUnresolvedRedo, bindVars) if err != nil { return 0, err } if len(qr.Rows) < 1 { return 0, nil } v, _ := sqltypes.ToInt64(qr.Rows[0][0]) return v, nil }
[ "func", "(", "tpc", "*", "TwoPC", ")", "CountUnresolvedRedo", "(", "ctx", "context", ".", "Context", ",", "unresolvedTime", "time", ".", "Time", ")", "(", "int64", ",", "error", ")", "{", "conn", ",", "err", ":=", "tpc", ".", "readPool", ".", "Get", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n\n", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "unresolvedTime", ".", "UnixNano", "(", ")", ")", ",", "}", "\n", "qr", ",", "err", ":=", "tpc", ".", "read", "(", "ctx", ",", "conn", ",", "tpc", ".", "countUnresolvedRedo", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "len", "(", "qr", ".", "Rows", ")", "<", "1", "{", "return", "0", ",", "nil", "\n", "}", "\n", "v", ",", "_", ":=", "sqltypes", ".", "ToInt64", "(", "qr", ".", "Rows", "[", "0", "]", "[", "0", "]", ")", "\n", "return", "v", ",", "nil", "\n", "}" ]
// CountUnresolvedRedo returns the number of prepared transactions that are still unresolved.
[ "CountUnresolvedRedo", "returns", "the", "number", "of", "prepared", "transactions", "that", "are", "still", "unresolved", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L318-L337
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
CreateTransaction
func (tpc *TwoPC) CreateTransaction(ctx context.Context, conn *TxConnection, dtid string, participants []*querypb.Target) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(int64(DTStatePrepare)), "cur_time": sqltypes.Int64BindVariable(time.Now().UnixNano()), } _, err := tpc.exec(ctx, conn, tpc.insertTransaction, bindVars) if err != nil { return err } rows := make([][]sqltypes.Value, len(participants)) for i, participant := range participants { rows[i] = []sqltypes.Value{ sqltypes.NewVarBinary(dtid), sqltypes.NewInt64(int64(i + 1)), sqltypes.NewVarBinary(participant.Keyspace), sqltypes.NewVarBinary(participant.Shard), } } extras := map[string]sqlparser.Encodable{ "vals": sqlparser.InsertValues(rows), } q, err := tpc.insertParticipants.GenerateQuery(nil, extras) if err != nil { return err } _, err = conn.Exec(ctx, q, 1, false) return err }
go
func (tpc *TwoPC) CreateTransaction(ctx context.Context, conn *TxConnection, dtid string, participants []*querypb.Target) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(int64(DTStatePrepare)), "cur_time": sqltypes.Int64BindVariable(time.Now().UnixNano()), } _, err := tpc.exec(ctx, conn, tpc.insertTransaction, bindVars) if err != nil { return err } rows := make([][]sqltypes.Value, len(participants)) for i, participant := range participants { rows[i] = []sqltypes.Value{ sqltypes.NewVarBinary(dtid), sqltypes.NewInt64(int64(i + 1)), sqltypes.NewVarBinary(participant.Keyspace), sqltypes.NewVarBinary(participant.Shard), } } extras := map[string]sqlparser.Encodable{ "vals": sqlparser.InsertValues(rows), } q, err := tpc.insertParticipants.GenerateQuery(nil, extras) if err != nil { return err } _, err = conn.Exec(ctx, q, 1, false) return err }
[ "func", "(", "tpc", "*", "TwoPC", ")", "CreateTransaction", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "TxConnection", ",", "dtid", "string", ",", "participants", "[", "]", "*", "querypb", ".", "Target", ")", "error", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "StringBindVariable", "(", "dtid", ")", ",", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "int64", "(", "DTStatePrepare", ")", ")", ",", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ",", "}", "\n", "_", ",", "err", ":=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "insertTransaction", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "rows", ":=", "make", "(", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "len", "(", "participants", ")", ")", "\n", "for", "i", ",", "participant", ":=", "range", "participants", "{", "rows", "[", "i", "]", "=", "[", "]", "sqltypes", ".", "Value", "{", "sqltypes", ".", "NewVarBinary", "(", "dtid", ")", ",", "sqltypes", ".", "NewInt64", "(", "int64", "(", "i", "+", "1", ")", ")", ",", "sqltypes", ".", "NewVarBinary", "(", "participant", ".", "Keyspace", ")", ",", "sqltypes", ".", "NewVarBinary", "(", "participant", ".", "Shard", ")", ",", "}", "\n", "}", "\n", "extras", ":=", "map", "[", "string", "]", "sqlparser", ".", "Encodable", "{", "\"", "\"", ":", "sqlparser", ".", "InsertValues", "(", "rows", ")", ",", "}", "\n", "q", ",", "err", ":=", "tpc", ".", "insertParticipants", ".", "GenerateQuery", "(", "nil", ",", "extras", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "conn", ".", "Exec", "(", "ctx", ",", "q", ",", "1", ",", "false", ")", "\n", "return", "err", "\n", "}" ]
// CreateTransaction saves the metadata of a 2pc transaction as Prepared.
[ "CreateTransaction", "saves", "the", "metadata", "of", "a", "2pc", "transaction", "as", "Prepared", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L340-L369
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
Transition
func (tpc *TwoPC) Transition(ctx context.Context, conn *TxConnection, dtid string, state querypb.TransactionState) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(int64(state)), "prepare": sqltypes.Int64BindVariable(int64(querypb.TransactionState_PREPARE)), } qr, err := tpc.exec(ctx, conn, tpc.transition, bindVars) if err != nil { return err } if qr.RowsAffected != 1 { return vterrors.Errorf(vtrpcpb.Code_NOT_FOUND, "could not transition to %v: %s", state, dtid) } return nil }
go
func (tpc *TwoPC) Transition(ctx context.Context, conn *TxConnection, dtid string, state querypb.TransactionState) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), "state": sqltypes.Int64BindVariable(int64(state)), "prepare": sqltypes.Int64BindVariable(int64(querypb.TransactionState_PREPARE)), } qr, err := tpc.exec(ctx, conn, tpc.transition, bindVars) if err != nil { return err } if qr.RowsAffected != 1 { return vterrors.Errorf(vtrpcpb.Code_NOT_FOUND, "could not transition to %v: %s", state, dtid) } return nil }
[ "func", "(", "tpc", "*", "TwoPC", ")", "Transition", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "TxConnection", ",", "dtid", "string", ",", "state", "querypb", ".", "TransactionState", ")", "error", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "StringBindVariable", "(", "dtid", ")", ",", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "int64", "(", "state", ")", ")", ",", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "int64", "(", "querypb", ".", "TransactionState_PREPARE", ")", ")", ",", "}", "\n", "qr", ",", "err", ":=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "transition", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "qr", ".", "RowsAffected", "!=", "1", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_NOT_FOUND", ",", "\"", "\"", ",", "state", ",", "dtid", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Transition performs a transition from Prepare to the specified state. // If the transaction is not a in the Prepare state, an error is returned.
[ "Transition", "performs", "a", "transition", "from", "Prepare", "to", "the", "specified", "state", ".", "If", "the", "transaction", "is", "not", "a", "in", "the", "Prepare", "state", "an", "error", "is", "returned", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L373-L387
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
DeleteTransaction
func (tpc *TwoPC) DeleteTransaction(ctx context.Context, conn *TxConnection, dtid string) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), } _, err := tpc.exec(ctx, conn, tpc.deleteTransaction, bindVars) if err != nil { return err } _, err = tpc.exec(ctx, conn, tpc.deleteParticipants, bindVars) return err }
go
func (tpc *TwoPC) DeleteTransaction(ctx context.Context, conn *TxConnection, dtid string) error { bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), } _, err := tpc.exec(ctx, conn, tpc.deleteTransaction, bindVars) if err != nil { return err } _, err = tpc.exec(ctx, conn, tpc.deleteParticipants, bindVars) return err }
[ "func", "(", "tpc", "*", "TwoPC", ")", "DeleteTransaction", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "TxConnection", ",", "dtid", "string", ")", "error", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "StringBindVariable", "(", "dtid", ")", ",", "}", "\n", "_", ",", "err", ":=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "deleteTransaction", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "tpc", ".", "exec", "(", "ctx", ",", "conn", ",", "tpc", ".", "deleteParticipants", ",", "bindVars", ")", "\n", "return", "err", "\n", "}" ]
// DeleteTransaction deletes the metadata for the specified transaction.
[ "DeleteTransaction", "deletes", "the", "metadata", "for", "the", "specified", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L390-L400
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
ReadTransaction
func (tpc *TwoPC) ReadTransaction(ctx context.Context, dtid string) (*querypb.TransactionMetadata, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, err } defer conn.Recycle() result := &querypb.TransactionMetadata{} bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), } qr, err := tpc.read(ctx, conn, tpc.readTransaction, bindVars) if err != nil { return nil, err } if len(qr.Rows) == 0 { return result, nil } result.Dtid = qr.Rows[0][0].ToString() st, err := sqltypes.ToInt64(qr.Rows[0][1]) if err != nil { return nil, vterrors.Wrapf(err, "Error parsing state for dtid %s", dtid) } result.State = querypb.TransactionState(st) if result.State < querypb.TransactionState_PREPARE || result.State > querypb.TransactionState_ROLLBACK { return nil, fmt.Errorf("unexpected state for dtid %s: %v", dtid, result.State) } // A failure in time parsing will show up as a very old time, // which is harmless. tm, _ := sqltypes.ToInt64(qr.Rows[0][2]) result.TimeCreated = tm qr, err = tpc.read(ctx, conn, tpc.readParticipants, bindVars) if err != nil { return nil, err } participants := make([]*querypb.Target, 0, len(qr.Rows)) for _, row := range qr.Rows { participants = append(participants, &querypb.Target{ Keyspace: row[0].ToString(), Shard: row[1].ToString(), TabletType: topodatapb.TabletType_MASTER, }) } result.Participants = participants return result, nil }
go
func (tpc *TwoPC) ReadTransaction(ctx context.Context, dtid string) (*querypb.TransactionMetadata, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, err } defer conn.Recycle() result := &querypb.TransactionMetadata{} bindVars := map[string]*querypb.BindVariable{ "dtid": sqltypes.StringBindVariable(dtid), } qr, err := tpc.read(ctx, conn, tpc.readTransaction, bindVars) if err != nil { return nil, err } if len(qr.Rows) == 0 { return result, nil } result.Dtid = qr.Rows[0][0].ToString() st, err := sqltypes.ToInt64(qr.Rows[0][1]) if err != nil { return nil, vterrors.Wrapf(err, "Error parsing state for dtid %s", dtid) } result.State = querypb.TransactionState(st) if result.State < querypb.TransactionState_PREPARE || result.State > querypb.TransactionState_ROLLBACK { return nil, fmt.Errorf("unexpected state for dtid %s: %v", dtid, result.State) } // A failure in time parsing will show up as a very old time, // which is harmless. tm, _ := sqltypes.ToInt64(qr.Rows[0][2]) result.TimeCreated = tm qr, err = tpc.read(ctx, conn, tpc.readParticipants, bindVars) if err != nil { return nil, err } participants := make([]*querypb.Target, 0, len(qr.Rows)) for _, row := range qr.Rows { participants = append(participants, &querypb.Target{ Keyspace: row[0].ToString(), Shard: row[1].ToString(), TabletType: topodatapb.TabletType_MASTER, }) } result.Participants = participants return result, nil }
[ "func", "(", "tpc", "*", "TwoPC", ")", "ReadTransaction", "(", "ctx", "context", ".", "Context", ",", "dtid", "string", ")", "(", "*", "querypb", ".", "TransactionMetadata", ",", "error", ")", "{", "conn", ",", "err", ":=", "tpc", ".", "readPool", ".", "Get", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n\n", "result", ":=", "&", "querypb", ".", "TransactionMetadata", "{", "}", "\n", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "StringBindVariable", "(", "dtid", ")", ",", "}", "\n", "qr", ",", "err", ":=", "tpc", ".", "read", "(", "ctx", ",", "conn", ",", "tpc", ".", "readTransaction", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "qr", ".", "Rows", ")", "==", "0", "{", "return", "result", ",", "nil", "\n", "}", "\n", "result", ".", "Dtid", "=", "qr", ".", "Rows", "[", "0", "]", "[", "0", "]", ".", "ToString", "(", ")", "\n", "st", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "qr", ".", "Rows", "[", "0", "]", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dtid", ")", "\n", "}", "\n", "result", ".", "State", "=", "querypb", ".", "TransactionState", "(", "st", ")", "\n", "if", "result", ".", "State", "<", "querypb", ".", "TransactionState_PREPARE", "||", "result", ".", "State", ">", "querypb", ".", "TransactionState_ROLLBACK", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "result", ".", "State", ")", "\n", "}", "\n", "// A failure in time parsing will show up as a very old time,", "// which is harmless.", "tm", ",", "_", ":=", "sqltypes", ".", "ToInt64", "(", "qr", ".", "Rows", "[", "0", "]", "[", "2", "]", ")", "\n", "result", ".", "TimeCreated", "=", "tm", "\n\n", "qr", ",", "err", "=", "tpc", ".", "read", "(", "ctx", ",", "conn", ",", "tpc", ".", "readParticipants", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "participants", ":=", "make", "(", "[", "]", "*", "querypb", ".", "Target", ",", "0", ",", "len", "(", "qr", ".", "Rows", ")", ")", "\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "participants", "=", "append", "(", "participants", ",", "&", "querypb", ".", "Target", "{", "Keyspace", ":", "row", "[", "0", "]", ".", "ToString", "(", ")", ",", "Shard", ":", "row", "[", "1", "]", ".", "ToString", "(", ")", ",", "TabletType", ":", "topodatapb", ".", "TabletType_MASTER", ",", "}", ")", "\n", "}", "\n", "result", ".", "Participants", "=", "participants", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ReadTransaction returns the metadata for the transaction.
[ "ReadTransaction", "returns", "the", "metadata", "for", "the", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L403-L449
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
ReadAbandoned
func (tpc *TwoPC) ReadAbandoned(ctx context.Context, abandonTime time.Time) (map[string]time.Time, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, err } defer conn.Recycle() bindVars := map[string]*querypb.BindVariable{ "time_created": sqltypes.Int64BindVariable(abandonTime.UnixNano()), } qr, err := tpc.read(ctx, conn, tpc.readAbandoned, bindVars) if err != nil { return nil, err } txs := make(map[string]time.Time, len(qr.Rows)) for _, row := range qr.Rows { t, err := sqltypes.ToInt64(row[1]) if err != nil { return nil, err } txs[row[0].ToString()] = time.Unix(0, t) } return txs, nil }
go
func (tpc *TwoPC) ReadAbandoned(ctx context.Context, abandonTime time.Time) (map[string]time.Time, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, err } defer conn.Recycle() bindVars := map[string]*querypb.BindVariable{ "time_created": sqltypes.Int64BindVariable(abandonTime.UnixNano()), } qr, err := tpc.read(ctx, conn, tpc.readAbandoned, bindVars) if err != nil { return nil, err } txs := make(map[string]time.Time, len(qr.Rows)) for _, row := range qr.Rows { t, err := sqltypes.ToInt64(row[1]) if err != nil { return nil, err } txs[row[0].ToString()] = time.Unix(0, t) } return txs, nil }
[ "func", "(", "tpc", "*", "TwoPC", ")", "ReadAbandoned", "(", "ctx", "context", ".", "Context", ",", "abandonTime", "time", ".", "Time", ")", "(", "map", "[", "string", "]", "time", ".", "Time", ",", "error", ")", "{", "conn", ",", "err", ":=", "tpc", ".", "readPool", ".", "Get", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n\n", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "abandonTime", ".", "UnixNano", "(", ")", ")", ",", "}", "\n", "qr", ",", "err", ":=", "tpc", ".", "read", "(", "ctx", ",", "conn", ",", "tpc", ".", "readAbandoned", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "txs", ":=", "make", "(", "map", "[", "string", "]", "time", ".", "Time", ",", "len", "(", "qr", ".", "Rows", ")", ")", "\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "t", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "txs", "[", "row", "[", "0", "]", ".", "ToString", "(", ")", "]", "=", "time", ".", "Unix", "(", "0", ",", "t", ")", "\n", "}", "\n", "return", "txs", ",", "nil", "\n", "}" ]
// ReadAbandoned returns the list of abandoned transactions // and their associated start time.
[ "ReadAbandoned", "returns", "the", "list", "of", "abandoned", "transactions", "and", "their", "associated", "start", "time", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L453-L476
train
vitessio/vitess
go/vt/vttablet/tabletserver/twopc.go
ReadAllTransactions
func (tpc *TwoPC) ReadAllTransactions(ctx context.Context) ([]*DistributedTx, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, err } defer conn.Recycle() qr, err := conn.Exec(ctx, tpc.readAllTransactions, 10000, false) if err != nil { return nil, err } var curTx *DistributedTx var distributed []*DistributedTx for _, row := range qr.Rows { dtid := row[0].ToString() if curTx == nil || dtid != curTx.Dtid { // Initialize the new element. // A failure in time parsing will show up as a very old time, // which is harmless. tm, _ := sqltypes.ToInt64(row[2]) st, err := sqltypes.ToInt64(row[1]) // Just log on error and continue. The state will show up as UNKNOWN // on the display. if err != nil { log.Errorf("Error parsing state for dtid %s: %v.", dtid, err) } protostate := querypb.TransactionState(st) if protostate < querypb.TransactionState_UNKNOWN || protostate > querypb.TransactionState_ROLLBACK { log.Errorf("Unexpected state for dtid %s: %v.", dtid, protostate) } curTx = &DistributedTx{ Dtid: dtid, State: querypb.TransactionState(st).String(), Created: time.Unix(0, tm), } distributed = append(distributed, curTx) } curTx.Participants = append(curTx.Participants, querypb.Target{ Keyspace: row[3].ToString(), Shard: row[4].ToString(), }) } return distributed, nil }
go
func (tpc *TwoPC) ReadAllTransactions(ctx context.Context) ([]*DistributedTx, error) { conn, err := tpc.readPool.Get(ctx) if err != nil { return nil, err } defer conn.Recycle() qr, err := conn.Exec(ctx, tpc.readAllTransactions, 10000, false) if err != nil { return nil, err } var curTx *DistributedTx var distributed []*DistributedTx for _, row := range qr.Rows { dtid := row[0].ToString() if curTx == nil || dtid != curTx.Dtid { // Initialize the new element. // A failure in time parsing will show up as a very old time, // which is harmless. tm, _ := sqltypes.ToInt64(row[2]) st, err := sqltypes.ToInt64(row[1]) // Just log on error and continue. The state will show up as UNKNOWN // on the display. if err != nil { log.Errorf("Error parsing state for dtid %s: %v.", dtid, err) } protostate := querypb.TransactionState(st) if protostate < querypb.TransactionState_UNKNOWN || protostate > querypb.TransactionState_ROLLBACK { log.Errorf("Unexpected state for dtid %s: %v.", dtid, protostate) } curTx = &DistributedTx{ Dtid: dtid, State: querypb.TransactionState(st).String(), Created: time.Unix(0, tm), } distributed = append(distributed, curTx) } curTx.Participants = append(curTx.Participants, querypb.Target{ Keyspace: row[3].ToString(), Shard: row[4].ToString(), }) } return distributed, nil }
[ "func", "(", "tpc", "*", "TwoPC", ")", "ReadAllTransactions", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "*", "DistributedTx", ",", "error", ")", "{", "conn", ",", "err", ":=", "tpc", ".", "readPool", ".", "Get", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n\n", "qr", ",", "err", ":=", "conn", ".", "Exec", "(", "ctx", ",", "tpc", ".", "readAllTransactions", ",", "10000", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "curTx", "*", "DistributedTx", "\n", "var", "distributed", "[", "]", "*", "DistributedTx", "\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "dtid", ":=", "row", "[", "0", "]", ".", "ToString", "(", ")", "\n", "if", "curTx", "==", "nil", "||", "dtid", "!=", "curTx", ".", "Dtid", "{", "// Initialize the new element.", "// A failure in time parsing will show up as a very old time,", "// which is harmless.", "tm", ",", "_", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "2", "]", ")", "\n", "st", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "1", "]", ")", "\n", "// Just log on error and continue. The state will show up as UNKNOWN", "// on the display.", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "err", ")", "\n", "}", "\n", "protostate", ":=", "querypb", ".", "TransactionState", "(", "st", ")", "\n", "if", "protostate", "<", "querypb", ".", "TransactionState_UNKNOWN", "||", "protostate", ">", "querypb", ".", "TransactionState_ROLLBACK", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "protostate", ")", "\n", "}", "\n", "curTx", "=", "&", "DistributedTx", "{", "Dtid", ":", "dtid", ",", "State", ":", "querypb", ".", "TransactionState", "(", "st", ")", ".", "String", "(", ")", ",", "Created", ":", "time", ".", "Unix", "(", "0", ",", "tm", ")", ",", "}", "\n", "distributed", "=", "append", "(", "distributed", ",", "curTx", ")", "\n", "}", "\n", "curTx", ".", "Participants", "=", "append", "(", "curTx", ".", "Participants", ",", "querypb", ".", "Target", "{", "Keyspace", ":", "row", "[", "3", "]", ".", "ToString", "(", ")", ",", "Shard", ":", "row", "[", "4", "]", ".", "ToString", "(", ")", ",", "}", ")", "\n", "}", "\n", "return", "distributed", ",", "nil", "\n", "}" ]
// ReadAllTransactions returns info about all distributed transactions.
[ "ReadAllTransactions", "returns", "info", "about", "all", "distributed", "transactions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/twopc.go#L488-L532
train
vitessio/vitess
go/vt/servenv/run.go
Run
func Run(port int) { populateListeningURL(int32(port)) createGRPCServer() onRunHooks.Fire() serveGRPC() serveSocketFile() l, err := proc.Listen(fmt.Sprintf("%v", port)) if err != nil { log.Exit(err) } go http.Serve(l, nil) proc.Wait() l.Close() startTime := time.Now() log.Infof("Entering lameduck mode for at least %v", *lameduckPeriod) log.Infof("Firing asynchronous OnTerm hooks") go onTermHooks.Fire() fireOnTermSyncHooks(*onTermTimeout) if remain := *lameduckPeriod - time.Since(startTime); remain > 0 { log.Infof("Sleeping an extra %v after OnTermSync to finish lameduck period", remain) time.Sleep(remain) } log.Info("Shutting down gracefully") Close() }
go
func Run(port int) { populateListeningURL(int32(port)) createGRPCServer() onRunHooks.Fire() serveGRPC() serveSocketFile() l, err := proc.Listen(fmt.Sprintf("%v", port)) if err != nil { log.Exit(err) } go http.Serve(l, nil) proc.Wait() l.Close() startTime := time.Now() log.Infof("Entering lameduck mode for at least %v", *lameduckPeriod) log.Infof("Firing asynchronous OnTerm hooks") go onTermHooks.Fire() fireOnTermSyncHooks(*onTermTimeout) if remain := *lameduckPeriod - time.Since(startTime); remain > 0 { log.Infof("Sleeping an extra %v after OnTermSync to finish lameduck period", remain) time.Sleep(remain) } log.Info("Shutting down gracefully") Close() }
[ "func", "Run", "(", "port", "int", ")", "{", "populateListeningURL", "(", "int32", "(", "port", ")", ")", "\n", "createGRPCServer", "(", ")", "\n", "onRunHooks", ".", "Fire", "(", ")", "\n", "serveGRPC", "(", ")", "\n", "serveSocketFile", "(", ")", "\n\n", "l", ",", "err", ":=", "proc", ".", "Listen", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "port", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Exit", "(", "err", ")", "\n", "}", "\n", "go", "http", ".", "Serve", "(", "l", ",", "nil", ")", "\n\n", "proc", ".", "Wait", "(", ")", "\n", "l", ".", "Close", "(", ")", "\n\n", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "*", "lameduckPeriod", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "go", "onTermHooks", ".", "Fire", "(", ")", "\n\n", "fireOnTermSyncHooks", "(", "*", "onTermTimeout", ")", "\n", "if", "remain", ":=", "*", "lameduckPeriod", "-", "time", ".", "Since", "(", "startTime", ")", ";", "remain", ">", "0", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "remain", ")", "\n", "time", ".", "Sleep", "(", "remain", ")", "\n", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "Close", "(", ")", "\n", "}" ]
// Run starts listening for RPC and HTTP requests, // and blocks until it the process gets a signal.
[ "Run", "starts", "listening", "for", "RPC", "and", "HTTP", "requests", "and", "blocks", "until", "it", "the", "process", "gets", "a", "signal", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/run.go#L36-L65
train
vitessio/vitess
go/vt/workflow/resharding/tasks.go
GetTasks
func (hw *horizontalReshardingWorkflow) GetTasks(phase workflow.PhaseType) []*workflowpb.Task { var shards []string switch phase { case phaseCopySchema, phaseWaitForFilteredReplication, phaseDiff: shards = strings.Split(hw.checkpoint.Settings["destination_shards"], ",") case phaseClone, phaseMigrateRdonly, phaseMigrateReplica, phaseMigrateMaster: shards = strings.Split(hw.checkpoint.Settings["source_shards"], ",") default: log.Fatalf("BUG: unknown phase type: %v", phase) } var tasks []*workflowpb.Task for _, s := range shards { taskID := createTaskID(phase, s) tasks = append(tasks, hw.checkpoint.Tasks[taskID]) } return tasks }
go
func (hw *horizontalReshardingWorkflow) GetTasks(phase workflow.PhaseType) []*workflowpb.Task { var shards []string switch phase { case phaseCopySchema, phaseWaitForFilteredReplication, phaseDiff: shards = strings.Split(hw.checkpoint.Settings["destination_shards"], ",") case phaseClone, phaseMigrateRdonly, phaseMigrateReplica, phaseMigrateMaster: shards = strings.Split(hw.checkpoint.Settings["source_shards"], ",") default: log.Fatalf("BUG: unknown phase type: %v", phase) } var tasks []*workflowpb.Task for _, s := range shards { taskID := createTaskID(phase, s) tasks = append(tasks, hw.checkpoint.Tasks[taskID]) } return tasks }
[ "func", "(", "hw", "*", "horizontalReshardingWorkflow", ")", "GetTasks", "(", "phase", "workflow", ".", "PhaseType", ")", "[", "]", "*", "workflowpb", ".", "Task", "{", "var", "shards", "[", "]", "string", "\n", "switch", "phase", "{", "case", "phaseCopySchema", ",", "phaseWaitForFilteredReplication", ",", "phaseDiff", ":", "shards", "=", "strings", ".", "Split", "(", "hw", ".", "checkpoint", ".", "Settings", "[", "\"", "\"", "]", ",", "\"", "\"", ")", "\n", "case", "phaseClone", ",", "phaseMigrateRdonly", ",", "phaseMigrateReplica", ",", "phaseMigrateMaster", ":", "shards", "=", "strings", ".", "Split", "(", "hw", ".", "checkpoint", ".", "Settings", "[", "\"", "\"", "]", ",", "\"", "\"", ")", "\n", "default", ":", "log", ".", "Fatalf", "(", "\"", "\"", ",", "phase", ")", "\n", "}", "\n\n", "var", "tasks", "[", "]", "*", "workflowpb", ".", "Task", "\n", "for", "_", ",", "s", ":=", "range", "shards", "{", "taskID", ":=", "createTaskID", "(", "phase", ",", "s", ")", "\n", "tasks", "=", "append", "(", "tasks", ",", "hw", ".", "checkpoint", ".", "Tasks", "[", "taskID", "]", ")", "\n", "}", "\n", "return", "tasks", "\n", "}" ]
// GetTasks returns selected tasks for a phase from the checkpoint // with expected execution order.
[ "GetTasks", "returns", "selected", "tasks", "for", "a", "phase", "from", "the", "checkpoint", "with", "expected", "execution", "order", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/resharding/tasks.go#L41-L58
train
vitessio/vitess
go/vt/worker/split_clone.go
newSplitCloneWorker
func newSplitCloneWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, online, offline bool, excludeTables []string, chunkCount, minRowsPerChunk, sourceReaderCount, writeQueryMaxRows, writeQueryMaxSize, destinationWriterCount, minHealthyTablets int, tabletType topodatapb.TabletType, maxTPS, maxReplicationLag int64, useConsistentSnapshot bool) (Worker, error) { return newCloneWorker(wr, horizontalResharding, cell, keyspace, shard, online, offline, nil /* tables */, excludeTables, chunkCount, minRowsPerChunk, sourceReaderCount, writeQueryMaxRows, writeQueryMaxSize, destinationWriterCount, minHealthyTablets, tabletType, maxTPS, maxReplicationLag, useConsistentSnapshot) }
go
func newSplitCloneWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, online, offline bool, excludeTables []string, chunkCount, minRowsPerChunk, sourceReaderCount, writeQueryMaxRows, writeQueryMaxSize, destinationWriterCount, minHealthyTablets int, tabletType topodatapb.TabletType, maxTPS, maxReplicationLag int64, useConsistentSnapshot bool) (Worker, error) { return newCloneWorker(wr, horizontalResharding, cell, keyspace, shard, online, offline, nil /* tables */, excludeTables, chunkCount, minRowsPerChunk, sourceReaderCount, writeQueryMaxRows, writeQueryMaxSize, destinationWriterCount, minHealthyTablets, tabletType, maxTPS, maxReplicationLag, useConsistentSnapshot) }
[ "func", "newSplitCloneWorker", "(", "wr", "*", "wrangler", ".", "Wrangler", ",", "cell", ",", "keyspace", ",", "shard", "string", ",", "online", ",", "offline", "bool", ",", "excludeTables", "[", "]", "string", ",", "chunkCount", ",", "minRowsPerChunk", ",", "sourceReaderCount", ",", "writeQueryMaxRows", ",", "writeQueryMaxSize", ",", "destinationWriterCount", ",", "minHealthyTablets", "int", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "maxTPS", ",", "maxReplicationLag", "int64", ",", "useConsistentSnapshot", "bool", ")", "(", "Worker", ",", "error", ")", "{", "return", "newCloneWorker", "(", "wr", ",", "horizontalResharding", ",", "cell", ",", "keyspace", ",", "shard", ",", "online", ",", "offline", ",", "nil", "/* tables */", ",", "excludeTables", ",", "chunkCount", ",", "minRowsPerChunk", ",", "sourceReaderCount", ",", "writeQueryMaxRows", ",", "writeQueryMaxSize", ",", "destinationWriterCount", ",", "minHealthyTablets", ",", "tabletType", ",", "maxTPS", ",", "maxReplicationLag", ",", "useConsistentSnapshot", ")", "\n", "}" ]
// newSplitCloneWorker returns a new worker object for the SplitClone command.
[ "newSplitCloneWorker", "returns", "a", "new", "worker", "object", "for", "the", "SplitClone", "command", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/split_clone.go#L147-L149
train
vitessio/vitess
go/vt/worker/split_clone.go
FormattedOfflineSources
func (scw *SplitCloneWorker) FormattedOfflineSources() string { scw.formattedOfflineSourcesMu.Lock() defer scw.formattedOfflineSourcesMu.Unlock() if scw.formattedOfflineSources == "" { return "no offline source tablets currently in use" } return scw.formattedOfflineSources }
go
func (scw *SplitCloneWorker) FormattedOfflineSources() string { scw.formattedOfflineSourcesMu.Lock() defer scw.formattedOfflineSourcesMu.Unlock() if scw.formattedOfflineSources == "" { return "no offline source tablets currently in use" } return scw.formattedOfflineSources }
[ "func", "(", "scw", "*", "SplitCloneWorker", ")", "FormattedOfflineSources", "(", ")", "string", "{", "scw", ".", "formattedOfflineSourcesMu", ".", "Lock", "(", ")", "\n", "defer", "scw", ".", "formattedOfflineSourcesMu", ".", "Unlock", "(", ")", "\n\n", "if", "scw", ".", "formattedOfflineSources", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "scw", ".", "formattedOfflineSources", "\n", "}" ]
// FormattedOfflineSources returns a space separated list of tablets which // are in use during the offline clone phase.
[ "FormattedOfflineSources", "returns", "a", "space", "separated", "list", "of", "tablets", "which", "are", "in", "use", "during", "the", "offline", "clone", "phase", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/split_clone.go#L290-L298
train
vitessio/vitess
go/vt/worker/split_clone.go
findDestinationMasters
func (scw *SplitCloneWorker) findDestinationMasters(ctx context.Context) error { scw.setState(WorkerStateFindTargets) // Make sure we find a master for each destination shard and log it. scw.wr.Logger().Infof("Finding a MASTER tablet for each destination shard...") for _, si := range scw.destinationShards { waitCtx, waitCancel := context.WithTimeout(ctx, *waitForHealthyTabletsTimeout) err := scw.tsc.WaitForTablets(waitCtx, scw.cell, si.Keyspace(), si.ShardName(), topodatapb.TabletType_MASTER) waitCancel() if err != nil { return vterrors.Wrapf(err, "cannot find MASTER tablet for destination shard for %v/%v (in cell: %v)", si.Keyspace(), si.ShardName(), scw.cell) } masters := scw.tsc.GetHealthyTabletStats(si.Keyspace(), si.ShardName(), topodatapb.TabletType_MASTER) if len(masters) == 0 { return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "cannot find MASTER tablet for destination shard for %v/%v (in cell: %v) in HealthCheck: empty TabletStats list", si.Keyspace(), si.ShardName(), scw.cell) } master := masters[0] // Get the MySQL database name of the tablet. keyspaceAndShard := topoproto.KeyspaceShardString(si.Keyspace(), si.ShardName()) scw.destinationDbNames[keyspaceAndShard] = topoproto.TabletDbName(master.Tablet) scw.wr.Logger().Infof("Using tablet %v as destination master for %v/%v", topoproto.TabletAliasString(master.Tablet.Alias), si.Keyspace(), si.ShardName()) } scw.wr.Logger().Infof("NOTE: The used master of a destination shard might change over the course of the copy e.g. due to a reparent. The HealthCheck module will track and log master changes and any error message will always refer the actually used master address.") return nil }
go
func (scw *SplitCloneWorker) findDestinationMasters(ctx context.Context) error { scw.setState(WorkerStateFindTargets) // Make sure we find a master for each destination shard and log it. scw.wr.Logger().Infof("Finding a MASTER tablet for each destination shard...") for _, si := range scw.destinationShards { waitCtx, waitCancel := context.WithTimeout(ctx, *waitForHealthyTabletsTimeout) err := scw.tsc.WaitForTablets(waitCtx, scw.cell, si.Keyspace(), si.ShardName(), topodatapb.TabletType_MASTER) waitCancel() if err != nil { return vterrors.Wrapf(err, "cannot find MASTER tablet for destination shard for %v/%v (in cell: %v)", si.Keyspace(), si.ShardName(), scw.cell) } masters := scw.tsc.GetHealthyTabletStats(si.Keyspace(), si.ShardName(), topodatapb.TabletType_MASTER) if len(masters) == 0 { return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "cannot find MASTER tablet for destination shard for %v/%v (in cell: %v) in HealthCheck: empty TabletStats list", si.Keyspace(), si.ShardName(), scw.cell) } master := masters[0] // Get the MySQL database name of the tablet. keyspaceAndShard := topoproto.KeyspaceShardString(si.Keyspace(), si.ShardName()) scw.destinationDbNames[keyspaceAndShard] = topoproto.TabletDbName(master.Tablet) scw.wr.Logger().Infof("Using tablet %v as destination master for %v/%v", topoproto.TabletAliasString(master.Tablet.Alias), si.Keyspace(), si.ShardName()) } scw.wr.Logger().Infof("NOTE: The used master of a destination shard might change over the course of the copy e.g. due to a reparent. The HealthCheck module will track and log master changes and any error message will always refer the actually used master address.") return nil }
[ "func", "(", "scw", "*", "SplitCloneWorker", ")", "findDestinationMasters", "(", "ctx", "context", ".", "Context", ")", "error", "{", "scw", ".", "setState", "(", "WorkerStateFindTargets", ")", "\n\n", "// Make sure we find a master for each destination shard and log it.", "scw", ".", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ")", "\n", "for", "_", ",", "si", ":=", "range", "scw", ".", "destinationShards", "{", "waitCtx", ",", "waitCancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "*", "waitForHealthyTabletsTimeout", ")", "\n", "err", ":=", "scw", ".", "tsc", ".", "WaitForTablets", "(", "waitCtx", ",", "scw", ".", "cell", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "topodatapb", ".", "TabletType_MASTER", ")", "\n", "waitCancel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "scw", ".", "cell", ")", "\n", "}", "\n", "masters", ":=", "scw", ".", "tsc", ".", "GetHealthyTabletStats", "(", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "topodatapb", ".", "TabletType_MASTER", ")", "\n", "if", "len", "(", "masters", ")", "==", "0", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "scw", ".", "cell", ")", "\n", "}", "\n", "master", ":=", "masters", "[", "0", "]", "\n\n", "// Get the MySQL database name of the tablet.", "keyspaceAndShard", ":=", "topoproto", ".", "KeyspaceShardString", "(", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ")", "\n", "scw", ".", "destinationDbNames", "[", "keyspaceAndShard", "]", "=", "topoproto", ".", "TabletDbName", "(", "master", ".", "Tablet", ")", "\n\n", "scw", ".", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "master", ".", "Tablet", ".", "Alias", ")", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ")", "\n", "}", "\n", "scw", ".", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ")", "\n\n", "return", "nil", "\n", "}" ]
// findDestinationMasters finds for each destination shard the current master.
[ "findDestinationMasters", "finds", "for", "each", "destination", "shard", "the", "current", "master", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/split_clone.go#L840-L867
train
vitessio/vitess
go/vt/worker/split_clone.go
createKeyResolver
func (scw *SplitCloneWorker) createKeyResolver(td *tabletmanagerdatapb.TableDefinition) (keyspaceIDResolver, error) { if scw.cloneType == verticalSplit { // VerticalSplitClone currently always has exactly one destination shard // and therefore does not require routing between multiple shards. return nil, nil } if *useV3ReshardingMode { return newV3ResolverFromTableDefinition(scw.keyspaceSchema, td) } return newV2Resolver(scw.destinationKeyspaceInfo, td) }
go
func (scw *SplitCloneWorker) createKeyResolver(td *tabletmanagerdatapb.TableDefinition) (keyspaceIDResolver, error) { if scw.cloneType == verticalSplit { // VerticalSplitClone currently always has exactly one destination shard // and therefore does not require routing between multiple shards. return nil, nil } if *useV3ReshardingMode { return newV3ResolverFromTableDefinition(scw.keyspaceSchema, td) } return newV2Resolver(scw.destinationKeyspaceInfo, td) }
[ "func", "(", "scw", "*", "SplitCloneWorker", ")", "createKeyResolver", "(", "td", "*", "tabletmanagerdatapb", ".", "TableDefinition", ")", "(", "keyspaceIDResolver", ",", "error", ")", "{", "if", "scw", ".", "cloneType", "==", "verticalSplit", "{", "// VerticalSplitClone currently always has exactly one destination shard", "// and therefore does not require routing between multiple shards.", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "*", "useV3ReshardingMode", "{", "return", "newV3ResolverFromTableDefinition", "(", "scw", ".", "keyspaceSchema", ",", "td", ")", "\n", "}", "\n", "return", "newV2Resolver", "(", "scw", ".", "destinationKeyspaceInfo", ",", "td", ")", "\n", "}" ]
// createKeyResolver is called at the start of each chunk pipeline. // It creates a keyspaceIDResolver which translates a given row to a // keyspace ID. This is necessary to route the to be copied rows to the // different destination shards.
[ "createKeyResolver", "is", "called", "at", "the", "start", "of", "each", "chunk", "pipeline", ".", "It", "creates", "a", "keyspaceIDResolver", "which", "translates", "a", "given", "row", "to", "a", "keyspace", "ID", ".", "This", "is", "necessary", "to", "route", "the", "to", "be", "copied", "rows", "to", "the", "different", "destination", "shards", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/split_clone.go#L1343-L1354
train
vitessio/vitess
go/vt/worker/split_clone.go
StatsUpdate
func (scw *SplitCloneWorker) StatsUpdate(ts *discovery.TabletStats) { scw.tsc.StatsUpdate(ts) // Ignore unless REPLICA or RDONLY. if ts.Target.TabletType != topodatapb.TabletType_REPLICA && ts.Target.TabletType != topodatapb.TabletType_RDONLY { return } // Lock throttlers mutex to avoid that this method (and the called method // Throttler.RecordReplicationLag()) races with closeThrottlers() (which calls // Throttler.Close()). scw.throttlersMu.Lock() defer scw.throttlersMu.Unlock() t := scw.getThrottlerLocked(ts.Target.Keyspace, ts.Target.Shard) if t != nil { t.RecordReplicationLag(time.Now(), ts) } }
go
func (scw *SplitCloneWorker) StatsUpdate(ts *discovery.TabletStats) { scw.tsc.StatsUpdate(ts) // Ignore unless REPLICA or RDONLY. if ts.Target.TabletType != topodatapb.TabletType_REPLICA && ts.Target.TabletType != topodatapb.TabletType_RDONLY { return } // Lock throttlers mutex to avoid that this method (and the called method // Throttler.RecordReplicationLag()) races with closeThrottlers() (which calls // Throttler.Close()). scw.throttlersMu.Lock() defer scw.throttlersMu.Unlock() t := scw.getThrottlerLocked(ts.Target.Keyspace, ts.Target.Shard) if t != nil { t.RecordReplicationLag(time.Now(), ts) } }
[ "func", "(", "scw", "*", "SplitCloneWorker", ")", "StatsUpdate", "(", "ts", "*", "discovery", ".", "TabletStats", ")", "{", "scw", ".", "tsc", ".", "StatsUpdate", "(", "ts", ")", "\n\n", "// Ignore unless REPLICA or RDONLY.", "if", "ts", ".", "Target", ".", "TabletType", "!=", "topodatapb", ".", "TabletType_REPLICA", "&&", "ts", ".", "Target", ".", "TabletType", "!=", "topodatapb", ".", "TabletType_RDONLY", "{", "return", "\n", "}", "\n\n", "// Lock throttlers mutex to avoid that this method (and the called method", "// Throttler.RecordReplicationLag()) races with closeThrottlers() (which calls", "// Throttler.Close()).", "scw", ".", "throttlersMu", ".", "Lock", "(", ")", "\n", "defer", "scw", ".", "throttlersMu", ".", "Unlock", "(", ")", "\n\n", "t", ":=", "scw", ".", "getThrottlerLocked", "(", "ts", ".", "Target", ".", "Keyspace", ",", "ts", ".", "Target", ".", "Shard", ")", "\n", "if", "t", "!=", "nil", "{", "t", ".", "RecordReplicationLag", "(", "time", ".", "Now", "(", ")", ",", "ts", ")", "\n", "}", "\n", "}" ]
// StatsUpdate receives replication lag updates for each destination master // and forwards them to the respective throttler instance. // It also forwards any update to the TabletStatsCache to keep it up to date. // It is part of the discovery.HealthCheckStatsListener interface.
[ "StatsUpdate", "receives", "replication", "lag", "updates", "for", "each", "destination", "master", "and", "forwards", "them", "to", "the", "respective", "throttler", "instance", ".", "It", "also", "forwards", "any", "update", "to", "the", "TabletStatsCache", "to", "keep", "it", "up", "to", "date", ".", "It", "is", "part", "of", "the", "discovery", ".", "HealthCheckStatsListener", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/split_clone.go#L1360-L1378
train
vitessio/vitess
go/vt/worker/tablet_tracker.go
Track
func (t *TabletTracker) Track(stats []discovery.TabletStats) *topodatapb.Tablet { if len(stats) == 0 { panic("stats must not be empty") } t.mu.Lock() defer t.mu.Unlock() // Try to find a tablet which is not in use yet. for _, stat := range stats { key := topoproto.TabletAliasString(stat.Tablet.Alias) if _, ok := t.usedTablets[key]; !ok { t.usedTablets[key] = 1 return stat.Tablet } } // If we reached this point, "stats" is a subset of "usedTablets" i.e. // all tablets are already in use. Take the least used one. for _, aliasString := range t.tabletsByUsage() { for _, stat := range stats { key := topoproto.TabletAliasString(stat.Tablet.Alias) if key == aliasString { t.usedTablets[key]++ return stat.Tablet } } } panic("BUG: we did not add any tablet") }
go
func (t *TabletTracker) Track(stats []discovery.TabletStats) *topodatapb.Tablet { if len(stats) == 0 { panic("stats must not be empty") } t.mu.Lock() defer t.mu.Unlock() // Try to find a tablet which is not in use yet. for _, stat := range stats { key := topoproto.TabletAliasString(stat.Tablet.Alias) if _, ok := t.usedTablets[key]; !ok { t.usedTablets[key] = 1 return stat.Tablet } } // If we reached this point, "stats" is a subset of "usedTablets" i.e. // all tablets are already in use. Take the least used one. for _, aliasString := range t.tabletsByUsage() { for _, stat := range stats { key := topoproto.TabletAliasString(stat.Tablet.Alias) if key == aliasString { t.usedTablets[key]++ return stat.Tablet } } } panic("BUG: we did not add any tablet") }
[ "func", "(", "t", "*", "TabletTracker", ")", "Track", "(", "stats", "[", "]", "discovery", ".", "TabletStats", ")", "*", "topodatapb", ".", "Tablet", "{", "if", "len", "(", "stats", ")", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "t", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Try to find a tablet which is not in use yet.", "for", "_", ",", "stat", ":=", "range", "stats", "{", "key", ":=", "topoproto", ".", "TabletAliasString", "(", "stat", ".", "Tablet", ".", "Alias", ")", "\n", "if", "_", ",", "ok", ":=", "t", ".", "usedTablets", "[", "key", "]", ";", "!", "ok", "{", "t", ".", "usedTablets", "[", "key", "]", "=", "1", "\n", "return", "stat", ".", "Tablet", "\n", "}", "\n", "}", "\n\n", "// If we reached this point, \"stats\" is a subset of \"usedTablets\" i.e.", "// all tablets are already in use. Take the least used one.", "for", "_", ",", "aliasString", ":=", "range", "t", ".", "tabletsByUsage", "(", ")", "{", "for", "_", ",", "stat", ":=", "range", "stats", "{", "key", ":=", "topoproto", ".", "TabletAliasString", "(", "stat", ".", "Tablet", ".", "Alias", ")", "\n", "if", "key", "==", "aliasString", "{", "t", ".", "usedTablets", "[", "key", "]", "++", "\n", "return", "stat", ".", "Tablet", "\n", "}", "\n", "}", "\n", "}", "\n", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// Track will pick the least used tablet from "stats", increment its usage by 1 // and return it. // "stats" must not be empty.
[ "Track", "will", "pick", "the", "least", "used", "tablet", "from", "stats", "increment", "its", "usage", "by", "1", "and", "return", "it", ".", "stats", "must", "not", "be", "empty", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/tablet_tracker.go#L53-L81
train
vitessio/vitess
go/vt/worker/tablet_tracker.go
Untrack
func (t *TabletTracker) Untrack(alias *topodatapb.TabletAlias) { t.mu.Lock() defer t.mu.Unlock() key := topoproto.TabletAliasString(alias) count, ok := t.usedTablets[key] if !ok { panic(fmt.Sprintf("tablet: %v was never tracked", key)) } count-- if count == 0 { delete(t.usedTablets, key) } else { t.usedTablets[key] = count } }
go
func (t *TabletTracker) Untrack(alias *topodatapb.TabletAlias) { t.mu.Lock() defer t.mu.Unlock() key := topoproto.TabletAliasString(alias) count, ok := t.usedTablets[key] if !ok { panic(fmt.Sprintf("tablet: %v was never tracked", key)) } count-- if count == 0 { delete(t.usedTablets, key) } else { t.usedTablets[key] = count } }
[ "func", "(", "t", "*", "TabletTracker", ")", "Untrack", "(", "alias", "*", "topodatapb", ".", "TabletAlias", ")", "{", "t", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "key", ":=", "topoproto", ".", "TabletAliasString", "(", "alias", ")", "\n", "count", ",", "ok", ":=", "t", ".", "usedTablets", "[", "key", "]", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ")", ")", "\n", "}", "\n", "count", "--", "\n", "if", "count", "==", "0", "{", "delete", "(", "t", ".", "usedTablets", ",", "key", ")", "\n", "}", "else", "{", "t", ".", "usedTablets", "[", "key", "]", "=", "count", "\n", "}", "\n", "}" ]
// Untrack decrements the usage of "alias" by 1.
[ "Untrack", "decrements", "the", "usage", "of", "alias", "by", "1", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/tablet_tracker.go#L84-L99
train
vitessio/vitess
go/vt/worker/tablet_tracker.go
TabletsInUse
func (t *TabletTracker) TabletsInUse() string { t.mu.Lock() defer t.mu.Unlock() var aliases []string for alias := range t.usedTablets { aliases = append(aliases, alias) } sort.Strings(aliases) return strings.Join(aliases, " ") }
go
func (t *TabletTracker) TabletsInUse() string { t.mu.Lock() defer t.mu.Unlock() var aliases []string for alias := range t.usedTablets { aliases = append(aliases, alias) } sort.Strings(aliases) return strings.Join(aliases, " ") }
[ "func", "(", "t", "*", "TabletTracker", ")", "TabletsInUse", "(", ")", "string", "{", "t", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "var", "aliases", "[", "]", "string", "\n", "for", "alias", ":=", "range", "t", ".", "usedTablets", "{", "aliases", "=", "append", "(", "aliases", ",", "alias", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "aliases", ")", "\n", "return", "strings", ".", "Join", "(", "aliases", ",", "\"", "\"", ")", "\n", "}" ]
// TabletsInUse returns a string of all tablet aliases currently in use. // The tablets are separated by a space.
[ "TabletsInUse", "returns", "a", "string", "of", "all", "tablet", "aliases", "currently", "in", "use", ".", "The", "tablets", "are", "separated", "by", "a", "space", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/tablet_tracker.go#L103-L113
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
NewClient
func NewClient() *QueryClient { return &QueryClient{ ctx: callerid.NewContext( context.Background(), &vtrpcpb.CallerID{}, &querypb.VTGateCallerID{Username: "dev"}, ), target: Target, server: Server, } }
go
func NewClient() *QueryClient { return &QueryClient{ ctx: callerid.NewContext( context.Background(), &vtrpcpb.CallerID{}, &querypb.VTGateCallerID{Username: "dev"}, ), target: Target, server: Server, } }
[ "func", "NewClient", "(", ")", "*", "QueryClient", "{", "return", "&", "QueryClient", "{", "ctx", ":", "callerid", ".", "NewContext", "(", "context", ".", "Background", "(", ")", ",", "&", "vtrpcpb", ".", "CallerID", "{", "}", ",", "&", "querypb", ".", "VTGateCallerID", "{", "Username", ":", "\"", "\"", "}", ",", ")", ",", "target", ":", "Target", ",", "server", ":", "Server", ",", "}", "\n", "}" ]
// NewClient creates a new client for Server.
[ "NewClient", "creates", "a", "new", "client", "for", "Server", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L43-L53
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
NewClientWithContext
func NewClientWithContext(ctx context.Context) *QueryClient { return &QueryClient{ ctx: ctx, target: Target, server: Server, } }
go
func NewClientWithContext(ctx context.Context) *QueryClient { return &QueryClient{ ctx: ctx, target: Target, server: Server, } }
[ "func", "NewClientWithContext", "(", "ctx", "context", ".", "Context", ")", "*", "QueryClient", "{", "return", "&", "QueryClient", "{", "ctx", ":", "ctx", ",", "target", ":", "Target", ",", "server", ":", "Server", ",", "}", "\n", "}" ]
// NewClientWithContext creates a new client for Server with the provided context.
[ "NewClientWithContext", "creates", "a", "new", "client", "for", "Server", "with", "the", "provided", "context", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L56-L62
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
Begin
func (client *QueryClient) Begin(clientFoundRows bool) error { if client.transactionID != 0 { return errors.New("already in transaction") } var options *querypb.ExecuteOptions if clientFoundRows { options = &querypb.ExecuteOptions{ClientFoundRows: clientFoundRows} } transactionID, err := client.server.Begin(client.ctx, &client.target, options) if err != nil { return err } client.transactionID = transactionID return nil }
go
func (client *QueryClient) Begin(clientFoundRows bool) error { if client.transactionID != 0 { return errors.New("already in transaction") } var options *querypb.ExecuteOptions if clientFoundRows { options = &querypb.ExecuteOptions{ClientFoundRows: clientFoundRows} } transactionID, err := client.server.Begin(client.ctx, &client.target, options) if err != nil { return err } client.transactionID = transactionID return nil }
[ "func", "(", "client", "*", "QueryClient", ")", "Begin", "(", "clientFoundRows", "bool", ")", "error", "{", "if", "client", ".", "transactionID", "!=", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "options", "*", "querypb", ".", "ExecuteOptions", "\n", "if", "clientFoundRows", "{", "options", "=", "&", "querypb", ".", "ExecuteOptions", "{", "ClientFoundRows", ":", "clientFoundRows", "}", "\n", "}", "\n", "transactionID", ",", "err", ":=", "client", ".", "server", ".", "Begin", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "client", ".", "transactionID", "=", "transactionID", "\n", "return", "nil", "\n", "}" ]
// Begin begins a transaction.
[ "Begin", "begins", "a", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L65-L79
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
Prepare
func (client *QueryClient) Prepare(dtid string) error { defer func() { client.transactionID = 0 }() return client.server.Prepare(client.ctx, &client.target, client.transactionID, dtid) }
go
func (client *QueryClient) Prepare(dtid string) error { defer func() { client.transactionID = 0 }() return client.server.Prepare(client.ctx, &client.target, client.transactionID, dtid) }
[ "func", "(", "client", "*", "QueryClient", ")", "Prepare", "(", "dtid", "string", ")", "error", "{", "defer", "func", "(", ")", "{", "client", ".", "transactionID", "=", "0", "}", "(", ")", "\n", "return", "client", ".", "server", ".", "Prepare", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "client", ".", "transactionID", ",", "dtid", ")", "\n", "}" ]
// Prepare executes a prepare on the current transaction.
[ "Prepare", "executes", "a", "prepare", "on", "the", "current", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L94-L97
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
RollbackPrepared
func (client *QueryClient) RollbackPrepared(dtid string, originalID int64) error { return client.server.RollbackPrepared(client.ctx, &client.target, dtid, originalID) }
go
func (client *QueryClient) RollbackPrepared(dtid string, originalID int64) error { return client.server.RollbackPrepared(client.ctx, &client.target, dtid, originalID) }
[ "func", "(", "client", "*", "QueryClient", ")", "RollbackPrepared", "(", "dtid", "string", ",", "originalID", "int64", ")", "error", "{", "return", "client", ".", "server", ".", "RollbackPrepared", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "dtid", ",", "originalID", ")", "\n", "}" ]
// RollbackPrepared rollsback a prepared transaction.
[ "RollbackPrepared", "rollsback", "a", "prepared", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L105-L107
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
CreateTransaction
func (client *QueryClient) CreateTransaction(dtid string, participants []*querypb.Target) error { return client.server.CreateTransaction(client.ctx, &client.target, dtid, participants) }
go
func (client *QueryClient) CreateTransaction(dtid string, participants []*querypb.Target) error { return client.server.CreateTransaction(client.ctx, &client.target, dtid, participants) }
[ "func", "(", "client", "*", "QueryClient", ")", "CreateTransaction", "(", "dtid", "string", ",", "participants", "[", "]", "*", "querypb", ".", "Target", ")", "error", "{", "return", "client", ".", "server", ".", "CreateTransaction", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "dtid", ",", "participants", ")", "\n", "}" ]
// CreateTransaction issues a CreateTransaction to TabletServer.
[ "CreateTransaction", "issues", "a", "CreateTransaction", "to", "TabletServer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L110-L112
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
SetRollback
func (client *QueryClient) SetRollback(dtid string, transactionID int64) error { return client.server.SetRollback(client.ctx, &client.target, dtid, client.transactionID) }
go
func (client *QueryClient) SetRollback(dtid string, transactionID int64) error { return client.server.SetRollback(client.ctx, &client.target, dtid, client.transactionID) }
[ "func", "(", "client", "*", "QueryClient", ")", "SetRollback", "(", "dtid", "string", ",", "transactionID", "int64", ")", "error", "{", "return", "client", ".", "server", ".", "SetRollback", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "dtid", ",", "client", ".", "transactionID", ")", "\n", "}" ]
// SetRollback issues a SetRollback to TabletServer.
[ "SetRollback", "issues", "a", "SetRollback", "to", "TabletServer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L121-L123
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
ConcludeTransaction
func (client *QueryClient) ConcludeTransaction(dtid string) error { return client.server.ConcludeTransaction(client.ctx, &client.target, dtid) }
go
func (client *QueryClient) ConcludeTransaction(dtid string) error { return client.server.ConcludeTransaction(client.ctx, &client.target, dtid) }
[ "func", "(", "client", "*", "QueryClient", ")", "ConcludeTransaction", "(", "dtid", "string", ")", "error", "{", "return", "client", ".", "server", ".", "ConcludeTransaction", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "dtid", ")", "\n", "}" ]
// ConcludeTransaction issues a ConcludeTransaction to TabletServer.
[ "ConcludeTransaction", "issues", "a", "ConcludeTransaction", "to", "TabletServer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L126-L128
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
ReadTransaction
func (client *QueryClient) ReadTransaction(dtid string) (*querypb.TransactionMetadata, error) { return client.server.ReadTransaction(client.ctx, &client.target, dtid) }
go
func (client *QueryClient) ReadTransaction(dtid string) (*querypb.TransactionMetadata, error) { return client.server.ReadTransaction(client.ctx, &client.target, dtid) }
[ "func", "(", "client", "*", "QueryClient", ")", "ReadTransaction", "(", "dtid", "string", ")", "(", "*", "querypb", ".", "TransactionMetadata", ",", "error", ")", "{", "return", "client", ".", "server", ".", "ReadTransaction", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "dtid", ")", "\n", "}" ]
// ReadTransaction returns the transaction metadata.
[ "ReadTransaction", "returns", "the", "transaction", "metadata", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L131-L133
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
SetServingType
func (client *QueryClient) SetServingType(tabletType topodatapb.TabletType) error { _, err := client.server.SetServingType(tabletType, true, nil) return err }
go
func (client *QueryClient) SetServingType(tabletType topodatapb.TabletType) error { _, err := client.server.SetServingType(tabletType, true, nil) return err }
[ "func", "(", "client", "*", "QueryClient", ")", "SetServingType", "(", "tabletType", "topodatapb", ".", "TabletType", ")", "error", "{", "_", ",", "err", ":=", "client", ".", "server", ".", "SetServingType", "(", "tabletType", ",", "true", ",", "nil", ")", "\n", "return", "err", "\n", "}" ]
// SetServingType is for testing transitions. // It currently supports only master->replica and back.
[ "SetServingType", "is", "for", "testing", "transitions", ".", "It", "currently", "supports", "only", "master", "-", ">", "replica", "and", "back", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L137-L140
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
Execute
func (client *QueryClient) Execute(query string, bindvars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return client.ExecuteWithOptions(query, bindvars, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}) }
go
func (client *QueryClient) Execute(query string, bindvars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return client.ExecuteWithOptions(query, bindvars, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}) }
[ "func", "(", "client", "*", "QueryClient", ")", "Execute", "(", "query", "string", ",", "bindvars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "return", "client", ".", "ExecuteWithOptions", "(", "query", ",", "bindvars", ",", "&", "querypb", ".", "ExecuteOptions", "{", "IncludedFields", ":", "querypb", ".", "ExecuteOptions_ALL", "}", ")", "\n", "}" ]
// Execute executes a query.
[ "Execute", "executes", "a", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L143-L145
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
BeginExecute
func (client *QueryClient) BeginExecute(query string, bindvars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { if client.transactionID != 0 { return nil, errors.New("already in transaction") } qr, transactionID, err := client.server.BeginExecute( client.ctx, &client.target, query, bindvars, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}, ) if err != nil { return nil, err } client.transactionID = transactionID return qr, nil }
go
func (client *QueryClient) BeginExecute(query string, bindvars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { if client.transactionID != 0 { return nil, errors.New("already in transaction") } qr, transactionID, err := client.server.BeginExecute( client.ctx, &client.target, query, bindvars, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}, ) if err != nil { return nil, err } client.transactionID = transactionID return qr, nil }
[ "func", "(", "client", "*", "QueryClient", ")", "BeginExecute", "(", "query", "string", ",", "bindvars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "if", "client", ".", "transactionID", "!=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "qr", ",", "transactionID", ",", "err", ":=", "client", ".", "server", ".", "BeginExecute", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "query", ",", "bindvars", ",", "&", "querypb", ".", "ExecuteOptions", "{", "IncludedFields", ":", "querypb", ".", "ExecuteOptions_ALL", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "client", ".", "transactionID", "=", "transactionID", "\n", "return", "qr", ",", "nil", "\n", "}" ]
// BeginExecute performs a BeginExecute.
[ "BeginExecute", "performs", "a", "BeginExecute", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L148-L164
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
ExecuteWithOptions
func (client *QueryClient) ExecuteWithOptions(query string, bindvars map[string]*querypb.BindVariable, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { return client.server.Execute( client.ctx, &client.target, query, bindvars, client.transactionID, options, ) }
go
func (client *QueryClient) ExecuteWithOptions(query string, bindvars map[string]*querypb.BindVariable, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { return client.server.Execute( client.ctx, &client.target, query, bindvars, client.transactionID, options, ) }
[ "func", "(", "client", "*", "QueryClient", ")", "ExecuteWithOptions", "(", "query", "string", ",", "bindvars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "return", "client", ".", "server", ".", "Execute", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "query", ",", "bindvars", ",", "client", ".", "transactionID", ",", "options", ",", ")", "\n", "}" ]
// ExecuteWithOptions executes a query using 'options'.
[ "ExecuteWithOptions", "executes", "a", "query", "using", "options", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L167-L176
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
StreamExecute
func (client *QueryClient) StreamExecute(query string, bindvars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return client.StreamExecuteWithOptions(query, bindvars, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}) }
go
func (client *QueryClient) StreamExecute(query string, bindvars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return client.StreamExecuteWithOptions(query, bindvars, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}) }
[ "func", "(", "client", "*", "QueryClient", ")", "StreamExecute", "(", "query", "string", ",", "bindvars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "return", "client", ".", "StreamExecuteWithOptions", "(", "query", ",", "bindvars", ",", "&", "querypb", ".", "ExecuteOptions", "{", "IncludedFields", ":", "querypb", ".", "ExecuteOptions_ALL", "}", ")", "\n", "}" ]
// StreamExecute executes a query & returns the results.
[ "StreamExecute", "executes", "a", "query", "&", "returns", "the", "results", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L179-L181
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
StreamExecuteWithOptions
func (client *QueryClient) StreamExecuteWithOptions(query string, bindvars map[string]*querypb.BindVariable, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { result := &sqltypes.Result{} err := client.server.StreamExecute( client.ctx, &client.target, query, bindvars, 0, options, func(res *sqltypes.Result) error { if result.Fields == nil { result.Fields = res.Fields } result.Rows = append(result.Rows, res.Rows...) result.RowsAffected += uint64(len(res.Rows)) return nil }, ) if err != nil { return nil, err } return result, nil }
go
func (client *QueryClient) StreamExecuteWithOptions(query string, bindvars map[string]*querypb.BindVariable, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { result := &sqltypes.Result{} err := client.server.StreamExecute( client.ctx, &client.target, query, bindvars, 0, options, func(res *sqltypes.Result) error { if result.Fields == nil { result.Fields = res.Fields } result.Rows = append(result.Rows, res.Rows...) result.RowsAffected += uint64(len(res.Rows)) return nil }, ) if err != nil { return nil, err } return result, nil }
[ "func", "(", "client", "*", "QueryClient", ")", "StreamExecuteWithOptions", "(", "query", "string", ",", "bindvars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "result", ":=", "&", "sqltypes", ".", "Result", "{", "}", "\n", "err", ":=", "client", ".", "server", ".", "StreamExecute", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "query", ",", "bindvars", ",", "0", ",", "options", ",", "func", "(", "res", "*", "sqltypes", ".", "Result", ")", "error", "{", "if", "result", ".", "Fields", "==", "nil", "{", "result", ".", "Fields", "=", "res", ".", "Fields", "\n", "}", "\n", "result", ".", "Rows", "=", "append", "(", "result", ".", "Rows", ",", "res", ".", "Rows", "...", ")", "\n", "result", ".", "RowsAffected", "+=", "uint64", "(", "len", "(", "res", ".", "Rows", ")", ")", "\n", "return", "nil", "\n", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// StreamExecuteWithOptions executes a query & returns the results using 'options'.
[ "StreamExecuteWithOptions", "executes", "a", "query", "&", "returns", "the", "results", "using", "options", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L184-L206
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
Stream
func (client *QueryClient) Stream(query string, bindvars map[string]*querypb.BindVariable, sendFunc func(*sqltypes.Result) error) error { return client.server.StreamExecute( client.ctx, &client.target, query, bindvars, 0, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}, sendFunc, ) }
go
func (client *QueryClient) Stream(query string, bindvars map[string]*querypb.BindVariable, sendFunc func(*sqltypes.Result) error) error { return client.server.StreamExecute( client.ctx, &client.target, query, bindvars, 0, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}, sendFunc, ) }
[ "func", "(", "client", "*", "QueryClient", ")", "Stream", "(", "query", "string", ",", "bindvars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "sendFunc", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "return", "client", ".", "server", ".", "StreamExecute", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "query", ",", "bindvars", ",", "0", ",", "&", "querypb", ".", "ExecuteOptions", "{", "IncludedFields", ":", "querypb", ".", "ExecuteOptions_ALL", "}", ",", "sendFunc", ",", ")", "\n", "}" ]
// Stream streams the results of a query.
[ "Stream", "streams", "the", "results", "of", "a", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L209-L219
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
ExecuteBatch
func (client *QueryClient) ExecuteBatch(queries []*querypb.BoundQuery, asTransaction bool) ([]sqltypes.Result, error) { return client.server.ExecuteBatch( client.ctx, &client.target, queries, asTransaction, client.transactionID, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}, ) }
go
func (client *QueryClient) ExecuteBatch(queries []*querypb.BoundQuery, asTransaction bool) ([]sqltypes.Result, error) { return client.server.ExecuteBatch( client.ctx, &client.target, queries, asTransaction, client.transactionID, &querypb.ExecuteOptions{IncludedFields: querypb.ExecuteOptions_ALL}, ) }
[ "func", "(", "client", "*", "QueryClient", ")", "ExecuteBatch", "(", "queries", "[", "]", "*", "querypb", ".", "BoundQuery", ",", "asTransaction", "bool", ")", "(", "[", "]", "sqltypes", ".", "Result", ",", "error", ")", "{", "return", "client", ".", "server", ".", "ExecuteBatch", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "queries", ",", "asTransaction", ",", "client", ".", "transactionID", ",", "&", "querypb", ".", "ExecuteOptions", "{", "IncludedFields", ":", "querypb", ".", "ExecuteOptions_ALL", "}", ",", ")", "\n", "}" ]
// ExecuteBatch executes a batch of queries.
[ "ExecuteBatch", "executes", "a", "batch", "of", "queries", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L222-L231
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
MessageStream
func (client *QueryClient) MessageStream(name string, callback func(*sqltypes.Result) error) (err error) { return client.server.MessageStream(client.ctx, &client.target, name, callback) }
go
func (client *QueryClient) MessageStream(name string, callback func(*sqltypes.Result) error) (err error) { return client.server.MessageStream(client.ctx, &client.target, name, callback) }
[ "func", "(", "client", "*", "QueryClient", ")", "MessageStream", "(", "name", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "(", "err", "error", ")", "{", "return", "client", ".", "server", ".", "MessageStream", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "name", ",", "callback", ")", "\n", "}" ]
// MessageStream streams messages from the message table.
[ "MessageStream", "streams", "messages", "from", "the", "message", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L234-L236
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/client.go
MessageAck
func (client *QueryClient) MessageAck(name string, ids []string) (int64, error) { bids := make([]*querypb.Value, 0, len(ids)) for _, id := range ids { bids = append(bids, &querypb.Value{ Type: sqltypes.VarChar, Value: []byte(id), }) } return client.server.MessageAck(client.ctx, &client.target, name, bids) }
go
func (client *QueryClient) MessageAck(name string, ids []string) (int64, error) { bids := make([]*querypb.Value, 0, len(ids)) for _, id := range ids { bids = append(bids, &querypb.Value{ Type: sqltypes.VarChar, Value: []byte(id), }) } return client.server.MessageAck(client.ctx, &client.target, name, bids) }
[ "func", "(", "client", "*", "QueryClient", ")", "MessageAck", "(", "name", "string", ",", "ids", "[", "]", "string", ")", "(", "int64", ",", "error", ")", "{", "bids", ":=", "make", "(", "[", "]", "*", "querypb", ".", "Value", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "bids", "=", "append", "(", "bids", ",", "&", "querypb", ".", "Value", "{", "Type", ":", "sqltypes", ".", "VarChar", ",", "Value", ":", "[", "]", "byte", "(", "id", ")", ",", "}", ")", "\n", "}", "\n", "return", "client", ".", "server", ".", "MessageAck", "(", "client", ".", "ctx", ",", "&", "client", ".", "target", ",", "name", ",", "bids", ")", "\n", "}" ]
// MessageAck acks messages
[ "MessageAck", "acks", "messages" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/client.go#L239-L248
train
vitessio/vitess
go/vt/worker/command.go
AddCommand
func AddCommand(groupName string, c Command) { for i, group := range commands { if group.Name == groupName { commands[i].Commands = append(commands[i].Commands, c) return } } panic(vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "trying to add to missing group %v", groupName)) }
go
func AddCommand(groupName string, c Command) { for i, group := range commands { if group.Name == groupName { commands[i].Commands = append(commands[i].Commands, c) return } } panic(vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "trying to add to missing group %v", groupName)) }
[ "func", "AddCommand", "(", "groupName", "string", ",", "c", "Command", ")", "{", "for", "i", ",", "group", ":=", "range", "commands", "{", "if", "group", ".", "Name", "==", "groupName", "{", "commands", "[", "i", "]", ".", "Commands", "=", "append", "(", "commands", "[", "i", "]", ".", "Commands", ",", "c", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "panic", "(", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "groupName", ")", ")", "\n", "}" ]
// AddCommand registers a command and makes it available.
[ "AddCommand", "registers", "a", "command", "and", "makes", "it", "available", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/command.go#L73-L81
train
vitessio/vitess
go/vt/worker/command.go
WaitForCommand
func (wi *Instance) WaitForCommand(wrk Worker, done chan struct{}) error { // display the status every second timer := time.NewTicker(wi.commandDisplayInterval) defer timer.Stop() for { select { case <-done: log.Info(wrk.StatusAsText()) wi.currentWorkerMutex.Lock() err := wi.lastRunError wi.currentWorkerMutex.Unlock() if err != nil { return err } return nil case <-timer.C: log.Info(wrk.StatusAsText()) } } }
go
func (wi *Instance) WaitForCommand(wrk Worker, done chan struct{}) error { // display the status every second timer := time.NewTicker(wi.commandDisplayInterval) defer timer.Stop() for { select { case <-done: log.Info(wrk.StatusAsText()) wi.currentWorkerMutex.Lock() err := wi.lastRunError wi.currentWorkerMutex.Unlock() if err != nil { return err } return nil case <-timer.C: log.Info(wrk.StatusAsText()) } } }
[ "func", "(", "wi", "*", "Instance", ")", "WaitForCommand", "(", "wrk", "Worker", ",", "done", "chan", "struct", "{", "}", ")", "error", "{", "// display the status every second", "timer", ":=", "time", ".", "NewTicker", "(", "wi", ".", "commandDisplayInterval", ")", "\n", "defer", "timer", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "done", ":", "log", ".", "Info", "(", "wrk", ".", "StatusAsText", "(", ")", ")", "\n", "wi", ".", "currentWorkerMutex", ".", "Lock", "(", ")", "\n", "err", ":=", "wi", ".", "lastRunError", "\n", "wi", ".", "currentWorkerMutex", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "case", "<-", "timer", ".", "C", ":", "log", ".", "Info", "(", "wrk", ".", "StatusAsText", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// WaitForCommand blocks until "done" is closed. In the meantime, it logs the status of "wrk".
[ "WaitForCommand", "blocks", "until", "done", "is", "closed", ".", "In", "the", "meantime", "it", "logs", "the", "status", "of", "wrk", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/command.go#L146-L165
train
vitessio/vitess
go/vt/worker/command.go
PrintAllCommands
func PrintAllCommands(logger logutil.Logger) { for _, group := range commands { if group.Name == "Debugging" { continue } logger.Printf("%v: %v\n", group.Name, group.Description) for _, cmd := range group.Commands { logger.Printf(" %v %v\n", cmd.Name, cmd.Params) } logger.Printf("\n") } }
go
func PrintAllCommands(logger logutil.Logger) { for _, group := range commands { if group.Name == "Debugging" { continue } logger.Printf("%v: %v\n", group.Name, group.Description) for _, cmd := range group.Commands { logger.Printf(" %v %v\n", cmd.Name, cmd.Params) } logger.Printf("\n") } }
[ "func", "PrintAllCommands", "(", "logger", "logutil", ".", "Logger", ")", "{", "for", "_", ",", "group", ":=", "range", "commands", "{", "if", "group", ".", "Name", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "group", ".", "Name", ",", "group", ".", "Description", ")", "\n", "for", "_", ",", "cmd", ":=", "range", "group", ".", "Commands", "{", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "cmd", ".", "Name", ",", "cmd", ".", "Params", ")", "\n", "}", "\n", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "}" ]
// PrintAllCommands prints a help text for all registered commands to the given Logger.
[ "PrintAllCommands", "prints", "a", "help", "text", "for", "all", "registered", "commands", "to", "the", "given", "Logger", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/command.go#L168-L179
train
vitessio/vitess
go/vt/binlog/binlog_streamer.go
NewStreamer
func NewStreamer(cp *mysql.ConnParams, se *schema.Engine, clientCharset *binlogdatapb.Charset, startPos mysql.Position, timestamp int64, sendTransaction sendTransactionFunc) *Streamer { return &Streamer{ cp: cp, se: se, clientCharset: clientCharset, startPos: startPos, timestamp: timestamp, sendTransaction: sendTransaction, } }
go
func NewStreamer(cp *mysql.ConnParams, se *schema.Engine, clientCharset *binlogdatapb.Charset, startPos mysql.Position, timestamp int64, sendTransaction sendTransactionFunc) *Streamer { return &Streamer{ cp: cp, se: se, clientCharset: clientCharset, startPos: startPos, timestamp: timestamp, sendTransaction: sendTransaction, } }
[ "func", "NewStreamer", "(", "cp", "*", "mysql", ".", "ConnParams", ",", "se", "*", "schema", ".", "Engine", ",", "clientCharset", "*", "binlogdatapb", ".", "Charset", ",", "startPos", "mysql", ".", "Position", ",", "timestamp", "int64", ",", "sendTransaction", "sendTransactionFunc", ")", "*", "Streamer", "{", "return", "&", "Streamer", "{", "cp", ":", "cp", ",", "se", ":", "se", ",", "clientCharset", ":", "clientCharset", ",", "startPos", ":", "startPos", ",", "timestamp", ":", "timestamp", ",", "sendTransaction", ":", "sendTransaction", ",", "}", "\n", "}" ]
// NewStreamer creates a binlog Streamer. // // dbname specifes the database to stream events for. // mysqld is the local instance of mysqlctl.Mysqld. // charset is the default character set on the BinlogPlayer side. // startPos is the position to start streaming at. Incompatible with timestamp. // timestamp is the timestamp to start streaming at. Incompatible with startPos. // sendTransaction is called each time a transaction is committed or rolled back.
[ "NewStreamer", "creates", "a", "binlog", "Streamer", ".", "dbname", "specifes", "the", "database", "to", "stream", "events", "for", ".", "mysqld", "is", "the", "local", "instance", "of", "mysqlctl", ".", "Mysqld", ".", "charset", "is", "the", "default", "character", "set", "on", "the", "BinlogPlayer", "side", ".", "startPos", "is", "the", "position", "to", "start", "streaming", "at", ".", "Incompatible", "with", "timestamp", ".", "timestamp", "is", "the", "timestamp", "to", "start", "streaming", "at", ".", "Incompatible", "with", "startPos", ".", "sendTransaction", "is", "called", "each", "time", "a", "transaction", "is", "committed", "or", "rolled", "back", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/binlog_streamer.go#L158-L167
train
vitessio/vitess
go/vt/binlog/binlog_streamer.go
writeValuesAsSQL
func writeValuesAsSQL(sql *sqlparser.TrackedBuffer, tce *tableCacheEntry, rs *mysql.Rows, rowIndex int, getPK bool) (sqltypes.Value, []sqltypes.Value, error) { valueIndex := 0 data := rs.Rows[rowIndex].Data pos := 0 var keyspaceIDCell sqltypes.Value var pkValues []sqltypes.Value if getPK { pkValues = make([]sqltypes.Value, len(tce.pkNames)) } for c := 0; c < rs.DataColumns.Count(); c++ { if !rs.DataColumns.Bit(c) { continue } // Print a separator if needed, then print the name. if valueIndex > 0 { sql.WriteString(", ") } sql.Myprintf("%v", tce.ti.Columns[c].Name) sql.WriteByte('=') if rs.Rows[rowIndex].NullColumns.Bit(valueIndex) { // This column is represented, but its value is NULL. sql.WriteString("NULL") valueIndex++ continue } // We have real data. value, l, err := mysql.CellValue(data, pos, tce.tm.Types[c], tce.tm.Metadata[c], tce.ti.Columns[c].Type) if err != nil { return keyspaceIDCell, nil, err } if value.Type() == querypb.Type_TIMESTAMP && !bytes.HasPrefix(value.ToBytes(), mysql.ZeroTimestamp) { // Values in the binary log are UTC. Let's convert them // to whatever timezone the connection is using, // so MySQL properly converts them back to UTC. sql.WriteString("convert_tz(") value.EncodeSQL(sql) sql.WriteString(", '+00:00', @@session.time_zone)") } else { value.EncodeSQL(sql) } if c == tce.keyspaceIDIndex { keyspaceIDCell = value } if getPK { if tce.pkIndexes[c] != -1 { pkValues[tce.pkIndexes[c]] = value } } pos += l valueIndex++ } return keyspaceIDCell, pkValues, nil }
go
func writeValuesAsSQL(sql *sqlparser.TrackedBuffer, tce *tableCacheEntry, rs *mysql.Rows, rowIndex int, getPK bool) (sqltypes.Value, []sqltypes.Value, error) { valueIndex := 0 data := rs.Rows[rowIndex].Data pos := 0 var keyspaceIDCell sqltypes.Value var pkValues []sqltypes.Value if getPK { pkValues = make([]sqltypes.Value, len(tce.pkNames)) } for c := 0; c < rs.DataColumns.Count(); c++ { if !rs.DataColumns.Bit(c) { continue } // Print a separator if needed, then print the name. if valueIndex > 0 { sql.WriteString(", ") } sql.Myprintf("%v", tce.ti.Columns[c].Name) sql.WriteByte('=') if rs.Rows[rowIndex].NullColumns.Bit(valueIndex) { // This column is represented, but its value is NULL. sql.WriteString("NULL") valueIndex++ continue } // We have real data. value, l, err := mysql.CellValue(data, pos, tce.tm.Types[c], tce.tm.Metadata[c], tce.ti.Columns[c].Type) if err != nil { return keyspaceIDCell, nil, err } if value.Type() == querypb.Type_TIMESTAMP && !bytes.HasPrefix(value.ToBytes(), mysql.ZeroTimestamp) { // Values in the binary log are UTC. Let's convert them // to whatever timezone the connection is using, // so MySQL properly converts them back to UTC. sql.WriteString("convert_tz(") value.EncodeSQL(sql) sql.WriteString(", '+00:00', @@session.time_zone)") } else { value.EncodeSQL(sql) } if c == tce.keyspaceIDIndex { keyspaceIDCell = value } if getPK { if tce.pkIndexes[c] != -1 { pkValues[tce.pkIndexes[c]] = value } } pos += l valueIndex++ } return keyspaceIDCell, pkValues, nil }
[ "func", "writeValuesAsSQL", "(", "sql", "*", "sqlparser", ".", "TrackedBuffer", ",", "tce", "*", "tableCacheEntry", ",", "rs", "*", "mysql", ".", "Rows", ",", "rowIndex", "int", ",", "getPK", "bool", ")", "(", "sqltypes", ".", "Value", ",", "[", "]", "sqltypes", ".", "Value", ",", "error", ")", "{", "valueIndex", ":=", "0", "\n", "data", ":=", "rs", ".", "Rows", "[", "rowIndex", "]", ".", "Data", "\n", "pos", ":=", "0", "\n", "var", "keyspaceIDCell", "sqltypes", ".", "Value", "\n", "var", "pkValues", "[", "]", "sqltypes", ".", "Value", "\n", "if", "getPK", "{", "pkValues", "=", "make", "(", "[", "]", "sqltypes", ".", "Value", ",", "len", "(", "tce", ".", "pkNames", ")", ")", "\n", "}", "\n", "for", "c", ":=", "0", ";", "c", "<", "rs", ".", "DataColumns", ".", "Count", "(", ")", ";", "c", "++", "{", "if", "!", "rs", ".", "DataColumns", ".", "Bit", "(", "c", ")", "{", "continue", "\n", "}", "\n\n", "// Print a separator if needed, then print the name.", "if", "valueIndex", ">", "0", "{", "sql", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "\n", "sql", ".", "Myprintf", "(", "\"", "\"", ",", "tce", ".", "ti", ".", "Columns", "[", "c", "]", ".", "Name", ")", "\n", "sql", ".", "WriteByte", "(", "'='", ")", "\n\n", "if", "rs", ".", "Rows", "[", "rowIndex", "]", ".", "NullColumns", ".", "Bit", "(", "valueIndex", ")", "{", "// This column is represented, but its value is NULL.", "sql", ".", "WriteString", "(", "\"", "\"", ")", "\n", "valueIndex", "++", "\n", "continue", "\n", "}", "\n\n", "// We have real data.", "value", ",", "l", ",", "err", ":=", "mysql", ".", "CellValue", "(", "data", ",", "pos", ",", "tce", ".", "tm", ".", "Types", "[", "c", "]", ",", "tce", ".", "tm", ".", "Metadata", "[", "c", "]", ",", "tce", ".", "ti", ".", "Columns", "[", "c", "]", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "return", "keyspaceIDCell", ",", "nil", ",", "err", "\n", "}", "\n", "if", "value", ".", "Type", "(", ")", "==", "querypb", ".", "Type_TIMESTAMP", "&&", "!", "bytes", ".", "HasPrefix", "(", "value", ".", "ToBytes", "(", ")", ",", "mysql", ".", "ZeroTimestamp", ")", "{", "// Values in the binary log are UTC. Let's convert them", "// to whatever timezone the connection is using,", "// so MySQL properly converts them back to UTC.", "sql", ".", "WriteString", "(", "\"", "\"", ")", "\n", "value", ".", "EncodeSQL", "(", "sql", ")", "\n", "sql", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "else", "{", "value", ".", "EncodeSQL", "(", "sql", ")", "\n", "}", "\n", "if", "c", "==", "tce", ".", "keyspaceIDIndex", "{", "keyspaceIDCell", "=", "value", "\n", "}", "\n", "if", "getPK", "{", "if", "tce", ".", "pkIndexes", "[", "c", "]", "!=", "-", "1", "{", "pkValues", "[", "tce", ".", "pkIndexes", "[", "c", "]", "]", "=", "value", "\n", "}", "\n", "}", "\n", "pos", "+=", "l", "\n", "valueIndex", "++", "\n", "}", "\n\n", "return", "keyspaceIDCell", ",", "pkValues", ",", "nil", "\n", "}" ]
// writeValuesAsSQL is a helper method to print the values as SQL in the // provided bytes.Buffer. It also returns the value for the keyspaceIDColumn, // and the array of values for the PK, if necessary.
[ "writeValuesAsSQL", "is", "a", "helper", "method", "to", "print", "the", "values", "as", "SQL", "in", "the", "provided", "bytes", ".", "Buffer", ".", "It", "also", "returns", "the", "value", "for", "the", "keyspaceIDColumn", "and", "the", "array", "of", "values", "for", "the", "PK", "if", "necessary", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/binlog_streamer.go#L723-L779
train
vitessio/vitess
go/mysql/flavor_mariadb.go
setSlavePositionCommands
func (mariadbFlavor) setSlavePositionCommands(pos Position) []string { return []string{ // RESET MASTER will clear out gtid_binlog_pos, // which then guarantees that gtid_current_pos = gtid_slave_pos, // since gtid_current_pos = MAX(gtid_binlog_pos,gtid_slave_pos). // This also emptys the binlogs, which allows us to set // gtid_binlog_state. "RESET MASTER", // Set gtid_slave_pos to tell the slave where to start // replicating. fmt.Sprintf("SET GLOBAL gtid_slave_pos = '%s'", pos), // Set gtid_binlog_state so that if this server later becomes a // master, it will know that it has seen everything up to and // including 'pos'. Otherwise, if another slave asks this // server to replicate starting at exactly 'pos', this server // will throw an error when in gtid_strict_mode, since it // doesn't see 'pos' in its binlog - it only has everything // AFTER. fmt.Sprintf("SET GLOBAL gtid_binlog_state = '%s'", pos), } }
go
func (mariadbFlavor) setSlavePositionCommands(pos Position) []string { return []string{ // RESET MASTER will clear out gtid_binlog_pos, // which then guarantees that gtid_current_pos = gtid_slave_pos, // since gtid_current_pos = MAX(gtid_binlog_pos,gtid_slave_pos). // This also emptys the binlogs, which allows us to set // gtid_binlog_state. "RESET MASTER", // Set gtid_slave_pos to tell the slave where to start // replicating. fmt.Sprintf("SET GLOBAL gtid_slave_pos = '%s'", pos), // Set gtid_binlog_state so that if this server later becomes a // master, it will know that it has seen everything up to and // including 'pos'. Otherwise, if another slave asks this // server to replicate starting at exactly 'pos', this server // will throw an error when in gtid_strict_mode, since it // doesn't see 'pos' in its binlog - it only has everything // AFTER. fmt.Sprintf("SET GLOBAL gtid_binlog_state = '%s'", pos), } }
[ "func", "(", "mariadbFlavor", ")", "setSlavePositionCommands", "(", "pos", "Position", ")", "[", "]", "string", "{", "return", "[", "]", "string", "{", "// RESET MASTER will clear out gtid_binlog_pos,", "// which then guarantees that gtid_current_pos = gtid_slave_pos,", "// since gtid_current_pos = MAX(gtid_binlog_pos,gtid_slave_pos).", "// This also emptys the binlogs, which allows us to set", "// gtid_binlog_state.", "\"", "\"", ",", "// Set gtid_slave_pos to tell the slave where to start", "// replicating.", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pos", ")", ",", "// Set gtid_binlog_state so that if this server later becomes a", "// master, it will know that it has seen everything up to and", "// including 'pos'. Otherwise, if another slave asks this", "// server to replicate starting at exactly 'pos', this server", "// will throw an error when in gtid_strict_mode, since it", "// doesn't see 'pos' in its binlog - it only has everything", "// AFTER.", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pos", ")", ",", "}", "\n", "}" ]
// setSlavePositionCommands is part of the Flavor interface.
[ "setSlavePositionCommands", "is", "part", "of", "the", "Flavor", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/flavor_mariadb.go#L97-L117
train
vitessio/vitess
go/vt/wrangler/version.go
GetVersion
func (wr *Wrangler) GetVersion(ctx context.Context, tabletAlias *topodatapb.TabletAlias) (string, error) { tablet, err := wr.ts.GetTablet(ctx, tabletAlias) if err != nil { return "", err } version, err := getVersionFromTablet(tablet.Addr()) if err != nil { return "", err } log.Infof("Tablet %v is running version '%v'", topoproto.TabletAliasString(tabletAlias), version) return version, err }
go
func (wr *Wrangler) GetVersion(ctx context.Context, tabletAlias *topodatapb.TabletAlias) (string, error) { tablet, err := wr.ts.GetTablet(ctx, tabletAlias) if err != nil { return "", err } version, err := getVersionFromTablet(tablet.Addr()) if err != nil { return "", err } log.Infof("Tablet %v is running version '%v'", topoproto.TabletAliasString(tabletAlias), version) return version, err }
[ "func", "(", "wr", "*", "Wrangler", ")", "GetVersion", "(", "ctx", "context", ".", "Context", ",", "tabletAlias", "*", "topodatapb", ".", "TabletAlias", ")", "(", "string", ",", "error", ")", "{", "tablet", ",", "err", ":=", "wr", ".", "ts", ".", "GetTablet", "(", "ctx", ",", "tabletAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "version", ",", "err", ":=", "getVersionFromTablet", "(", "tablet", ".", "Addr", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tabletAlias", ")", ",", "version", ")", "\n", "return", "version", ",", "err", "\n", "}" ]
// GetVersion returns the version string from a tablet
[ "GetVersion", "returns", "the", "version", "string", "from", "a", "tablet" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/version.go#L72-L84
train
vitessio/vitess
go/vt/wrangler/version.go
diffVersion
func (wr *Wrangler) diffVersion(ctx context.Context, masterVersion string, masterAlias *topodatapb.TabletAlias, alias *topodatapb.TabletAlias, wg *sync.WaitGroup, er concurrency.ErrorRecorder) { defer wg.Done() log.Infof("Gathering version for %v", topoproto.TabletAliasString(alias)) slaveVersion, err := wr.GetVersion(ctx, alias) if err != nil { er.RecordError(err) return } if masterVersion != slaveVersion { er.RecordError(fmt.Errorf("master %v version %v is different than slave %v version %v", topoproto.TabletAliasString(masterAlias), masterVersion, topoproto.TabletAliasString(alias), slaveVersion)) } }
go
func (wr *Wrangler) diffVersion(ctx context.Context, masterVersion string, masterAlias *topodatapb.TabletAlias, alias *topodatapb.TabletAlias, wg *sync.WaitGroup, er concurrency.ErrorRecorder) { defer wg.Done() log.Infof("Gathering version for %v", topoproto.TabletAliasString(alias)) slaveVersion, err := wr.GetVersion(ctx, alias) if err != nil { er.RecordError(err) return } if masterVersion != slaveVersion { er.RecordError(fmt.Errorf("master %v version %v is different than slave %v version %v", topoproto.TabletAliasString(masterAlias), masterVersion, topoproto.TabletAliasString(alias), slaveVersion)) } }
[ "func", "(", "wr", "*", "Wrangler", ")", "diffVersion", "(", "ctx", "context", ".", "Context", ",", "masterVersion", "string", ",", "masterAlias", "*", "topodatapb", ".", "TabletAlias", ",", "alias", "*", "topodatapb", ".", "TabletAlias", ",", "wg", "*", "sync", ".", "WaitGroup", ",", "er", "concurrency", ".", "ErrorRecorder", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "alias", ")", ")", "\n", "slaveVersion", ",", "err", ":=", "wr", ".", "GetVersion", "(", "ctx", ",", "alias", ")", "\n", "if", "err", "!=", "nil", "{", "er", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "masterVersion", "!=", "slaveVersion", "{", "er", ".", "RecordError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "masterAlias", ")", ",", "masterVersion", ",", "topoproto", ".", "TabletAliasString", "(", "alias", ")", ",", "slaveVersion", ")", ")", "\n", "}", "\n", "}" ]
// helper method to asynchronously get and diff a version
[ "helper", "method", "to", "asynchronously", "get", "and", "diff", "a", "version" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/version.go#L87-L99
train
vitessio/vitess
go/vt/wrangler/version.go
ValidateVersionShard
func (wr *Wrangler) ValidateVersionShard(ctx context.Context, keyspace, shard string) error { si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } // get version from the master, or error if !si.HasMaster() { return fmt.Errorf("no master in shard %v/%v", keyspace, shard) } log.Infof("Gathering version for master %v", topoproto.TabletAliasString(si.MasterAlias)) masterVersion, err := wr.GetVersion(ctx, si.MasterAlias) if err != nil { return err } // read all the aliases in the shard, that is all tablets that are // replicating from the master aliases, err := wr.ts.FindAllTabletAliasesInShard(ctx, keyspace, shard) if err != nil { return err } // then diff with all slaves er := concurrency.AllErrorRecorder{} wg := sync.WaitGroup{} for _, alias := range aliases { if topoproto.TabletAliasEqual(alias, si.MasterAlias) { continue } wg.Add(1) go wr.diffVersion(ctx, masterVersion, si.MasterAlias, alias, &wg, &er) } wg.Wait() if er.HasErrors() { return fmt.Errorf("version diffs: %v", er.Error().Error()) } return nil }
go
func (wr *Wrangler) ValidateVersionShard(ctx context.Context, keyspace, shard string) error { si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } // get version from the master, or error if !si.HasMaster() { return fmt.Errorf("no master in shard %v/%v", keyspace, shard) } log.Infof("Gathering version for master %v", topoproto.TabletAliasString(si.MasterAlias)) masterVersion, err := wr.GetVersion(ctx, si.MasterAlias) if err != nil { return err } // read all the aliases in the shard, that is all tablets that are // replicating from the master aliases, err := wr.ts.FindAllTabletAliasesInShard(ctx, keyspace, shard) if err != nil { return err } // then diff with all slaves er := concurrency.AllErrorRecorder{} wg := sync.WaitGroup{} for _, alias := range aliases { if topoproto.TabletAliasEqual(alias, si.MasterAlias) { continue } wg.Add(1) go wr.diffVersion(ctx, masterVersion, si.MasterAlias, alias, &wg, &er) } wg.Wait() if er.HasErrors() { return fmt.Errorf("version diffs: %v", er.Error().Error()) } return nil }
[ "func", "(", "wr", "*", "Wrangler", ")", "ValidateVersionShard", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ")", "error", "{", "si", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// get version from the master, or error", "if", "!", "si", ".", "HasMaster", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "si", ".", "MasterAlias", ")", ")", "\n", "masterVersion", ",", "err", ":=", "wr", ".", "GetVersion", "(", "ctx", ",", "si", ".", "MasterAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// read all the aliases in the shard, that is all tablets that are", "// replicating from the master", "aliases", ",", "err", ":=", "wr", ".", "ts", ".", "FindAllTabletAliasesInShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// then diff with all slaves", "er", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "for", "_", ",", "alias", ":=", "range", "aliases", "{", "if", "topoproto", ".", "TabletAliasEqual", "(", "alias", ",", "si", ".", "MasterAlias", ")", "{", "continue", "\n", "}", "\n\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "wr", ".", "diffVersion", "(", "ctx", ",", "masterVersion", ",", "si", ".", "MasterAlias", ",", "alias", ",", "&", "wg", ",", "&", "er", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "if", "er", ".", "HasErrors", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "er", ".", "Error", "(", ")", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateVersionShard validates all versions are the same in all // tablets in a shard
[ "ValidateVersionShard", "validates", "all", "versions", "are", "the", "same", "in", "all", "tablets", "in", "a", "shard" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/version.go#L103-L142
train
vitessio/vitess
go/vt/wrangler/version.go
ValidateVersionKeyspace
func (wr *Wrangler) ValidateVersionKeyspace(ctx context.Context, keyspace string) error { // find all the shards shards, err := wr.ts.GetShardNames(ctx, keyspace) if err != nil { return err } // corner cases if len(shards) == 0 { return fmt.Errorf("no shards in keyspace %v", keyspace) } sort.Strings(shards) if len(shards) == 1 { return wr.ValidateVersionShard(ctx, keyspace, shards[0]) } // find the reference version using the first shard's master si, err := wr.ts.GetShard(ctx, keyspace, shards[0]) if err != nil { return err } if !si.HasMaster() { return fmt.Errorf("no master in shard %v/%v", keyspace, shards[0]) } referenceAlias := si.MasterAlias log.Infof("Gathering version for reference master %v", topoproto.TabletAliasString(referenceAlias)) referenceVersion, err := wr.GetVersion(ctx, referenceAlias) if err != nil { return err } // then diff with all tablets but master 0 er := concurrency.AllErrorRecorder{} wg := sync.WaitGroup{} for _, shard := range shards { aliases, err := wr.ts.FindAllTabletAliasesInShard(ctx, keyspace, shard) if err != nil { er.RecordError(err) continue } for _, alias := range aliases { if topoproto.TabletAliasEqual(alias, si.MasterAlias) { continue } wg.Add(1) go wr.diffVersion(ctx, referenceVersion, referenceAlias, alias, &wg, &er) } } wg.Wait() if er.HasErrors() { return fmt.Errorf("version diffs: %v", er.Error().Error()) } return nil }
go
func (wr *Wrangler) ValidateVersionKeyspace(ctx context.Context, keyspace string) error { // find all the shards shards, err := wr.ts.GetShardNames(ctx, keyspace) if err != nil { return err } // corner cases if len(shards) == 0 { return fmt.Errorf("no shards in keyspace %v", keyspace) } sort.Strings(shards) if len(shards) == 1 { return wr.ValidateVersionShard(ctx, keyspace, shards[0]) } // find the reference version using the first shard's master si, err := wr.ts.GetShard(ctx, keyspace, shards[0]) if err != nil { return err } if !si.HasMaster() { return fmt.Errorf("no master in shard %v/%v", keyspace, shards[0]) } referenceAlias := si.MasterAlias log.Infof("Gathering version for reference master %v", topoproto.TabletAliasString(referenceAlias)) referenceVersion, err := wr.GetVersion(ctx, referenceAlias) if err != nil { return err } // then diff with all tablets but master 0 er := concurrency.AllErrorRecorder{} wg := sync.WaitGroup{} for _, shard := range shards { aliases, err := wr.ts.FindAllTabletAliasesInShard(ctx, keyspace, shard) if err != nil { er.RecordError(err) continue } for _, alias := range aliases { if topoproto.TabletAliasEqual(alias, si.MasterAlias) { continue } wg.Add(1) go wr.diffVersion(ctx, referenceVersion, referenceAlias, alias, &wg, &er) } } wg.Wait() if er.HasErrors() { return fmt.Errorf("version diffs: %v", er.Error().Error()) } return nil }
[ "func", "(", "wr", "*", "Wrangler", ")", "ValidateVersionKeyspace", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ")", "error", "{", "// find all the shards", "shards", ",", "err", ":=", "wr", ".", "ts", ".", "GetShardNames", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// corner cases", "if", "len", "(", "shards", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "shards", ")", "\n", "if", "len", "(", "shards", ")", "==", "1", "{", "return", "wr", ".", "ValidateVersionShard", "(", "ctx", ",", "keyspace", ",", "shards", "[", "0", "]", ")", "\n", "}", "\n\n", "// find the reference version using the first shard's master", "si", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shards", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "si", ".", "HasMaster", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shards", "[", "0", "]", ")", "\n", "}", "\n", "referenceAlias", ":=", "si", ".", "MasterAlias", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "referenceAlias", ")", ")", "\n", "referenceVersion", ",", "err", ":=", "wr", ".", "GetVersion", "(", "ctx", ",", "referenceAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// then diff with all tablets but master 0", "er", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "for", "_", ",", "shard", ":=", "range", "shards", "{", "aliases", ",", "err", ":=", "wr", ".", "ts", ".", "FindAllTabletAliasesInShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "er", ".", "RecordError", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "for", "_", ",", "alias", ":=", "range", "aliases", "{", "if", "topoproto", ".", "TabletAliasEqual", "(", "alias", ",", "si", ".", "MasterAlias", ")", "{", "continue", "\n", "}", "\n\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "wr", ".", "diffVersion", "(", "ctx", ",", "referenceVersion", ",", "referenceAlias", ",", "alias", ",", "&", "wg", ",", "&", "er", ")", "\n", "}", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "if", "er", ".", "HasErrors", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "er", ".", "Error", "(", ")", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateVersionKeyspace validates all versions are the same in all // tablets in a keyspace
[ "ValidateVersionKeyspace", "validates", "all", "versions", "are", "the", "same", "in", "all", "tablets", "in", "a", "keyspace" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/version.go#L146-L201
train
vitessio/vitess
go/vt/vtgate/vtgate.go
Execute
func (vtg *VTGate) Execute(ctx context.Context, session *vtgatepb.Session, sql string, bindVariables map[string]*querypb.BindVariable) (newSession *vtgatepb.Session, qr *sqltypes.Result, err error) { // In this context, we don't care if we can't fully parse destination destKeyspace, destTabletType, _, _ := vtg.executor.ParseDestinationTarget(session.TargetString) statsKey := []string{"Execute", destKeyspace, topoproto.TabletTypeLString(destTabletType)} defer vtg.timings.Record(statsKey, time.Now()) if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } qr, err = vtg.executor.Execute(ctx, "Execute", NewSafeSession(session), sql, bindVariables) if err == nil { vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows))) return session, qr, nil } handleError: query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Session": session, } err = recordAndAnnotateError(err, statsKey, query, vtg.logExecute) return session, nil, err }
go
func (vtg *VTGate) Execute(ctx context.Context, session *vtgatepb.Session, sql string, bindVariables map[string]*querypb.BindVariable) (newSession *vtgatepb.Session, qr *sqltypes.Result, err error) { // In this context, we don't care if we can't fully parse destination destKeyspace, destTabletType, _, _ := vtg.executor.ParseDestinationTarget(session.TargetString) statsKey := []string{"Execute", destKeyspace, topoproto.TabletTypeLString(destTabletType)} defer vtg.timings.Record(statsKey, time.Now()) if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } qr, err = vtg.executor.Execute(ctx, "Execute", NewSafeSession(session), sql, bindVariables) if err == nil { vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows))) return session, qr, nil } handleError: query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Session": session, } err = recordAndAnnotateError(err, statsKey, query, vtg.logExecute) return session, nil, err }
[ "func", "(", "vtg", "*", "VTGate", ")", "Execute", "(", "ctx", "context", ".", "Context", ",", "session", "*", "vtgatepb", ".", "Session", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "newSession", "*", "vtgatepb", ".", "Session", ",", "qr", "*", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "// In this context, we don't care if we can't fully parse destination", "destKeyspace", ",", "destTabletType", ",", "_", ",", "_", ":=", "vtg", ".", "executor", ".", "ParseDestinationTarget", "(", "session", ".", "TargetString", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "destKeyspace", ",", "topoproto", ".", "TabletTypeLString", "(", "destTabletType", ")", "}", "\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "time", ".", "Now", "(", ")", ")", "\n\n", "if", "bvErr", ":=", "sqltypes", ".", "ValidateBindVariables", "(", "bindVariables", ")", ";", "bvErr", "!=", "nil", "{", "err", "=", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "bvErr", ")", "\n", "goto", "handleError", "\n", "}", "\n\n", "qr", ",", "err", "=", "vtg", ".", "executor", ".", "Execute", "(", "ctx", ",", "\"", "\"", ",", "NewSafeSession", "(", "session", ")", ",", "sql", ",", "bindVariables", ")", "\n", "if", "err", "==", "nil", "{", "vtg", ".", "rowsReturned", ".", "Add", "(", "statsKey", ",", "int64", "(", "len", "(", "qr", ".", "Rows", ")", ")", ")", "\n", "return", "session", ",", "qr", ",", "nil", "\n", "}", "\n\n", "handleError", ":", "query", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "sql", ",", "\"", "\"", ":", "bindVariables", ",", "\"", "\"", ":", "session", ",", "}", "\n", "err", "=", "recordAndAnnotateError", "(", "err", ",", "statsKey", ",", "query", ",", "vtg", ".", "logExecute", ")", "\n", "return", "session", ",", "nil", ",", "err", "\n", "}" ]
// Execute executes a non-streaming query. This is a V3 function.
[ "Execute", "executes", "a", "non", "-", "streaming", "query", ".", "This", "is", "a", "V3", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L276-L301
train
vitessio/vitess
go/vt/vtgate/vtgate.go
ExecuteBatch
func (vtg *VTGate) ExecuteBatch(ctx context.Context, session *vtgatepb.Session, sqlList []string, bindVariablesList []map[string]*querypb.BindVariable) (*vtgatepb.Session, []sqltypes.QueryResponse, error) { // In this context, we don't care if we can't fully parse destination destKeyspace, destTabletType, _, _ := vtg.executor.ParseDestinationTarget(session.TargetString) statsKey := []string{"ExecuteBatch", destKeyspace, topoproto.TabletTypeLString(destTabletType)} defer vtg.timings.Record(statsKey, time.Now()) for _, bindVariables := range bindVariablesList { if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { return session, nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) } } qrl := make([]sqltypes.QueryResponse, len(sqlList)) for i, sql := range sqlList { var bv map[string]*querypb.BindVariable if len(bindVariablesList) != 0 { bv = bindVariablesList[i] } session, qrl[i].QueryResult, qrl[i].QueryError = vtg.Execute(ctx, session, sql, bv) if qr := qrl[i].QueryResult; qr != nil { vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows))) } } return session, qrl, nil }
go
func (vtg *VTGate) ExecuteBatch(ctx context.Context, session *vtgatepb.Session, sqlList []string, bindVariablesList []map[string]*querypb.BindVariable) (*vtgatepb.Session, []sqltypes.QueryResponse, error) { // In this context, we don't care if we can't fully parse destination destKeyspace, destTabletType, _, _ := vtg.executor.ParseDestinationTarget(session.TargetString) statsKey := []string{"ExecuteBatch", destKeyspace, topoproto.TabletTypeLString(destTabletType)} defer vtg.timings.Record(statsKey, time.Now()) for _, bindVariables := range bindVariablesList { if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { return session, nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) } } qrl := make([]sqltypes.QueryResponse, len(sqlList)) for i, sql := range sqlList { var bv map[string]*querypb.BindVariable if len(bindVariablesList) != 0 { bv = bindVariablesList[i] } session, qrl[i].QueryResult, qrl[i].QueryError = vtg.Execute(ctx, session, sql, bv) if qr := qrl[i].QueryResult; qr != nil { vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows))) } } return session, qrl, nil }
[ "func", "(", "vtg", "*", "VTGate", ")", "ExecuteBatch", "(", "ctx", "context", ".", "Context", ",", "session", "*", "vtgatepb", ".", "Session", ",", "sqlList", "[", "]", "string", ",", "bindVariablesList", "[", "]", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "vtgatepb", ".", "Session", ",", "[", "]", "sqltypes", ".", "QueryResponse", ",", "error", ")", "{", "// In this context, we don't care if we can't fully parse destination", "destKeyspace", ",", "destTabletType", ",", "_", ",", "_", ":=", "vtg", ".", "executor", ".", "ParseDestinationTarget", "(", "session", ".", "TargetString", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "destKeyspace", ",", "topoproto", ".", "TabletTypeLString", "(", "destTabletType", ")", "}", "\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "time", ".", "Now", "(", ")", ")", "\n\n", "for", "_", ",", "bindVariables", ":=", "range", "bindVariablesList", "{", "if", "bvErr", ":=", "sqltypes", ".", "ValidateBindVariables", "(", "bindVariables", ")", ";", "bvErr", "!=", "nil", "{", "return", "session", ",", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "bvErr", ")", "\n", "}", "\n", "}", "\n\n", "qrl", ":=", "make", "(", "[", "]", "sqltypes", ".", "QueryResponse", ",", "len", "(", "sqlList", ")", ")", "\n", "for", "i", ",", "sql", ":=", "range", "sqlList", "{", "var", "bv", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "\n", "if", "len", "(", "bindVariablesList", ")", "!=", "0", "{", "bv", "=", "bindVariablesList", "[", "i", "]", "\n", "}", "\n", "session", ",", "qrl", "[", "i", "]", ".", "QueryResult", ",", "qrl", "[", "i", "]", ".", "QueryError", "=", "vtg", ".", "Execute", "(", "ctx", ",", "session", ",", "sql", ",", "bv", ")", "\n", "if", "qr", ":=", "qrl", "[", "i", "]", ".", "QueryResult", ";", "qr", "!=", "nil", "{", "vtg", ".", "rowsReturned", ".", "Add", "(", "statsKey", ",", "int64", "(", "len", "(", "qr", ".", "Rows", ")", ")", ")", "\n", "}", "\n", "}", "\n", "return", "session", ",", "qrl", ",", "nil", "\n", "}" ]
// ExecuteBatch executes a batch of queries. This is a V3 function.
[ "ExecuteBatch", "executes", "a", "batch", "of", "queries", ".", "This", "is", "a", "V3", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L304-L328
train
vitessio/vitess
go/vt/vtgate/vtgate.go
StreamExecute
func (vtg *VTGate) StreamExecute(ctx context.Context, session *vtgatepb.Session, sql string, bindVariables map[string]*querypb.BindVariable, callback func(*sqltypes.Result) error) error { // In this context, we don't care if we can't fully parse destination destKeyspace, destTabletType, dest, _ := vtg.executor.ParseDestinationTarget(session.TargetString) statsKey := []string{"StreamExecute", destKeyspace, topoproto.TabletTypeLString(destTabletType)} defer vtg.timings.Record(statsKey, time.Now()) var err error if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } // TODO: This could be simplified to have a StreamExecute that takes // a destTarget without explicit destination. switch dest.(type) { case key.DestinationShard: err = vtg.resolver.StreamExecute( ctx, sql, bindVariables, destKeyspace, destTabletType, dest, session.Options, func(reply *sqltypes.Result) error { vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows))) return callback(reply) }) default: err = vtg.executor.StreamExecute( ctx, "StreamExecute", NewSafeSession(session), sql, bindVariables, querypb.Target{ Keyspace: destKeyspace, TabletType: destTabletType, }, func(reply *sqltypes.Result) error { vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows))) return callback(reply) }) } handleError: if err != nil { query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Session": session, } return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecute) } return nil }
go
func (vtg *VTGate) StreamExecute(ctx context.Context, session *vtgatepb.Session, sql string, bindVariables map[string]*querypb.BindVariable, callback func(*sqltypes.Result) error) error { // In this context, we don't care if we can't fully parse destination destKeyspace, destTabletType, dest, _ := vtg.executor.ParseDestinationTarget(session.TargetString) statsKey := []string{"StreamExecute", destKeyspace, topoproto.TabletTypeLString(destTabletType)} defer vtg.timings.Record(statsKey, time.Now()) var err error if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } // TODO: This could be simplified to have a StreamExecute that takes // a destTarget without explicit destination. switch dest.(type) { case key.DestinationShard: err = vtg.resolver.StreamExecute( ctx, sql, bindVariables, destKeyspace, destTabletType, dest, session.Options, func(reply *sqltypes.Result) error { vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows))) return callback(reply) }) default: err = vtg.executor.StreamExecute( ctx, "StreamExecute", NewSafeSession(session), sql, bindVariables, querypb.Target{ Keyspace: destKeyspace, TabletType: destTabletType, }, func(reply *sqltypes.Result) error { vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows))) return callback(reply) }) } handleError: if err != nil { query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Session": session, } return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecute) } return nil }
[ "func", "(", "vtg", "*", "VTGate", ")", "StreamExecute", "(", "ctx", "context", ".", "Context", ",", "session", "*", "vtgatepb", ".", "Session", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "// In this context, we don't care if we can't fully parse destination", "destKeyspace", ",", "destTabletType", ",", "dest", ",", "_", ":=", "vtg", ".", "executor", ".", "ParseDestinationTarget", "(", "session", ".", "TargetString", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "destKeyspace", ",", "topoproto", ".", "TabletTypeLString", "(", "destTabletType", ")", "}", "\n\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "time", ".", "Now", "(", ")", ")", "\n\n", "var", "err", "error", "\n", "if", "bvErr", ":=", "sqltypes", ".", "ValidateBindVariables", "(", "bindVariables", ")", ";", "bvErr", "!=", "nil", "{", "err", "=", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "bvErr", ")", "\n", "goto", "handleError", "\n", "}", "\n\n", "// TODO: This could be simplified to have a StreamExecute that takes", "// a destTarget without explicit destination.", "switch", "dest", ".", "(", "type", ")", "{", "case", "key", ".", "DestinationShard", ":", "err", "=", "vtg", ".", "resolver", ".", "StreamExecute", "(", "ctx", ",", "sql", ",", "bindVariables", ",", "destKeyspace", ",", "destTabletType", ",", "dest", ",", "session", ".", "Options", ",", "func", "(", "reply", "*", "sqltypes", ".", "Result", ")", "error", "{", "vtg", ".", "rowsReturned", ".", "Add", "(", "statsKey", ",", "int64", "(", "len", "(", "reply", ".", "Rows", ")", ")", ")", "\n", "return", "callback", "(", "reply", ")", "\n", "}", ")", "\n", "default", ":", "err", "=", "vtg", ".", "executor", ".", "StreamExecute", "(", "ctx", ",", "\"", "\"", ",", "NewSafeSession", "(", "session", ")", ",", "sql", ",", "bindVariables", ",", "querypb", ".", "Target", "{", "Keyspace", ":", "destKeyspace", ",", "TabletType", ":", "destTabletType", ",", "}", ",", "func", "(", "reply", "*", "sqltypes", ".", "Result", ")", "error", "{", "vtg", ".", "rowsReturned", ".", "Add", "(", "statsKey", ",", "int64", "(", "len", "(", "reply", ".", "Rows", ")", ")", ")", "\n", "return", "callback", "(", "reply", ")", "\n", "}", ")", "\n", "}", "\n", "handleError", ":", "if", "err", "!=", "nil", "{", "query", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "sql", ",", "\"", "\"", ":", "bindVariables", ",", "\"", "\"", ":", "session", ",", "}", "\n", "return", "recordAndAnnotateError", "(", "err", ",", "statsKey", ",", "query", ",", "vtg", ".", "logStreamExecute", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StreamExecute executes a streaming query. This is a V3 function. // Note we guarantee the callback will not be called concurrently // by mutiple go routines.
[ "StreamExecute", "executes", "a", "streaming", "query", ".", "This", "is", "a", "V3", "function", ".", "Note", "we", "guarantee", "the", "callback", "will", "not", "be", "called", "concurrently", "by", "mutiple", "go", "routines", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L333-L388
train
vitessio/vitess
go/vt/vtgate/vtgate.go
ExecuteKeyRanges
func (vtg *VTGate) ExecuteKeyRanges(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyRanges []*topodatapb.KeyRange, tabletType topodatapb.TabletType, session *vtgatepb.Session, notInTransaction bool, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"ExecuteKeyRanges", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) var qr *sqltypes.Result var err error if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } sql = sqlannotation.AnnotateIfDML(sql, nil) qr, err = vtg.resolver.Execute(ctx, sql, bindVariables, keyspace, tabletType, key.DestinationKeyRanges(keyRanges), session, notInTransaction, options, nil /* LogStats */) if err == nil { vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows))) return qr, nil } handleError: query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Keyspace": keyspace, "KeyRanges": keyRanges, "TabletType": ltt, "Session": session, "NotInTransaction": notInTransaction, "Options": options, } err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteKeyRanges) return nil, err }
go
func (vtg *VTGate) ExecuteKeyRanges(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyRanges []*topodatapb.KeyRange, tabletType topodatapb.TabletType, session *vtgatepb.Session, notInTransaction bool, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"ExecuteKeyRanges", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) var qr *sqltypes.Result var err error if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } sql = sqlannotation.AnnotateIfDML(sql, nil) qr, err = vtg.resolver.Execute(ctx, sql, bindVariables, keyspace, tabletType, key.DestinationKeyRanges(keyRanges), session, notInTransaction, options, nil /* LogStats */) if err == nil { vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows))) return qr, nil } handleError: query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Keyspace": keyspace, "KeyRanges": keyRanges, "TabletType": ltt, "Session": session, "NotInTransaction": notInTransaction, "Options": options, } err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteKeyRanges) return nil, err }
[ "func", "(", "vtg", "*", "VTGate", ")", "ExecuteKeyRanges", "(", "ctx", "context", ".", "Context", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "keyspace", "string", ",", "keyRanges", "[", "]", "*", "topodatapb", ".", "KeyRange", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "session", "*", "vtgatepb", ".", "Session", ",", "notInTransaction", "bool", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "ltt", ":=", "topoproto", ".", "TabletTypeLString", "(", "tabletType", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "keyspace", ",", "ltt", "}", "\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "startTime", ")", "\n\n", "var", "qr", "*", "sqltypes", ".", "Result", "\n", "var", "err", "error", "\n\n", "if", "bvErr", ":=", "sqltypes", ".", "ValidateBindVariables", "(", "bindVariables", ")", ";", "bvErr", "!=", "nil", "{", "err", "=", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "bvErr", ")", "\n", "goto", "handleError", "\n", "}", "\n\n", "sql", "=", "sqlannotation", ".", "AnnotateIfDML", "(", "sql", ",", "nil", ")", "\n\n", "qr", ",", "err", "=", "vtg", ".", "resolver", ".", "Execute", "(", "ctx", ",", "sql", ",", "bindVariables", ",", "keyspace", ",", "tabletType", ",", "key", ".", "DestinationKeyRanges", "(", "keyRanges", ")", ",", "session", ",", "notInTransaction", ",", "options", ",", "nil", "/* LogStats */", ")", "\n", "if", "err", "==", "nil", "{", "vtg", ".", "rowsReturned", ".", "Add", "(", "statsKey", ",", "int64", "(", "len", "(", "qr", ".", "Rows", ")", ")", ")", "\n", "return", "qr", ",", "nil", "\n", "}", "\n\n", "handleError", ":", "query", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "sql", ",", "\"", "\"", ":", "bindVariables", ",", "\"", "\"", ":", "keyspace", ",", "\"", "\"", ":", "keyRanges", ",", "\"", "\"", ":", "ltt", ",", "\"", "\"", ":", "session", ",", "\"", "\"", ":", "notInTransaction", ",", "\"", "\"", ":", "options", ",", "}", "\n", "err", "=", "recordAndAnnotateError", "(", "err", ",", "statsKey", ",", "query", ",", "vtg", ".", "logExecuteKeyRanges", ")", "\n", "return", "nil", ",", "err", "\n", "}" ]
// ExecuteKeyRanges executes a non-streaming query based on the specified keyranges. This is a legacy function.
[ "ExecuteKeyRanges", "executes", "a", "non", "-", "streaming", "query", "based", "on", "the", "specified", "keyranges", ".", "This", "is", "a", "legacy", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L483-L518
train
vitessio/vitess
go/vt/vtgate/vtgate.go
ExecuteBatchShards
func (vtg *VTGate) ExecuteBatchShards(ctx context.Context, queries []*vtgatepb.BoundShardQuery, tabletType topodatapb.TabletType, asTransaction bool, session *vtgatepb.Session, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"ExecuteBatchShards", unambiguousKeyspaceBSQ(queries), ltt} defer vtg.timings.Record(statsKey, startTime) var qrs []sqltypes.Result var err error for _, query := range queries { if bvErr := sqltypes.ValidateBindVariables(query.Query.BindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } } annotateBoundShardQueriesAsUnfriendly(queries) qrs, err = vtg.resolver.ExecuteBatch( ctx, tabletType, asTransaction, session, options, func() (*scatterBatchRequest, error) { return boundShardQueriesToScatterBatchRequest(ctx, vtg.resolver.resolver, queries, tabletType) }) if err == nil { var rowCount int64 for _, qr := range qrs { rowCount += int64(len(qr.Rows)) } vtg.rowsReturned.Add(statsKey, rowCount) return qrs, nil } handleError: query := map[string]interface{}{ "Queries": queries, "TabletType": ltt, "AsTransaction": asTransaction, "Session": session, "Options": options, } err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteBatchShards) return nil, err }
go
func (vtg *VTGate) ExecuteBatchShards(ctx context.Context, queries []*vtgatepb.BoundShardQuery, tabletType topodatapb.TabletType, asTransaction bool, session *vtgatepb.Session, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"ExecuteBatchShards", unambiguousKeyspaceBSQ(queries), ltt} defer vtg.timings.Record(statsKey, startTime) var qrs []sqltypes.Result var err error for _, query := range queries { if bvErr := sqltypes.ValidateBindVariables(query.Query.BindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } } annotateBoundShardQueriesAsUnfriendly(queries) qrs, err = vtg.resolver.ExecuteBatch( ctx, tabletType, asTransaction, session, options, func() (*scatterBatchRequest, error) { return boundShardQueriesToScatterBatchRequest(ctx, vtg.resolver.resolver, queries, tabletType) }) if err == nil { var rowCount int64 for _, qr := range qrs { rowCount += int64(len(qr.Rows)) } vtg.rowsReturned.Add(statsKey, rowCount) return qrs, nil } handleError: query := map[string]interface{}{ "Queries": queries, "TabletType": ltt, "AsTransaction": asTransaction, "Session": session, "Options": options, } err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteBatchShards) return nil, err }
[ "func", "(", "vtg", "*", "VTGate", ")", "ExecuteBatchShards", "(", "ctx", "context", ".", "Context", ",", "queries", "[", "]", "*", "vtgatepb", ".", "BoundShardQuery", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "asTransaction", "bool", ",", "session", "*", "vtgatepb", ".", "Session", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "[", "]", "sqltypes", ".", "Result", ",", "error", ")", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "ltt", ":=", "topoproto", ".", "TabletTypeLString", "(", "tabletType", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "unambiguousKeyspaceBSQ", "(", "queries", ")", ",", "ltt", "}", "\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "startTime", ")", "\n\n", "var", "qrs", "[", "]", "sqltypes", ".", "Result", "\n", "var", "err", "error", "\n\n", "for", "_", ",", "query", ":=", "range", "queries", "{", "if", "bvErr", ":=", "sqltypes", ".", "ValidateBindVariables", "(", "query", ".", "Query", ".", "BindVariables", ")", ";", "bvErr", "!=", "nil", "{", "err", "=", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "bvErr", ")", "\n", "goto", "handleError", "\n", "}", "\n", "}", "\n\n", "annotateBoundShardQueriesAsUnfriendly", "(", "queries", ")", "\n\n", "qrs", ",", "err", "=", "vtg", ".", "resolver", ".", "ExecuteBatch", "(", "ctx", ",", "tabletType", ",", "asTransaction", ",", "session", ",", "options", ",", "func", "(", ")", "(", "*", "scatterBatchRequest", ",", "error", ")", "{", "return", "boundShardQueriesToScatterBatchRequest", "(", "ctx", ",", "vtg", ".", "resolver", ".", "resolver", ",", "queries", ",", "tabletType", ")", "\n", "}", ")", "\n", "if", "err", "==", "nil", "{", "var", "rowCount", "int64", "\n", "for", "_", ",", "qr", ":=", "range", "qrs", "{", "rowCount", "+=", "int64", "(", "len", "(", "qr", ".", "Rows", ")", ")", "\n", "}", "\n", "vtg", ".", "rowsReturned", ".", "Add", "(", "statsKey", ",", "rowCount", ")", "\n", "return", "qrs", ",", "nil", "\n", "}", "\n\n", "handleError", ":", "query", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "queries", ",", "\"", "\"", ":", "ltt", ",", "\"", "\"", ":", "asTransaction", ",", "\"", "\"", ":", "session", ",", "\"", "\"", ":", "options", ",", "}", "\n", "err", "=", "recordAndAnnotateError", "(", "err", ",", "statsKey", ",", "query", ",", "vtg", ".", "logExecuteBatchShards", ")", "\n", "return", "nil", ",", "err", "\n", "}" ]
// ExecuteBatchShards executes a group of queries on the specified shards. This is a legacy function.
[ "ExecuteBatchShards", "executes", "a", "group", "of", "queries", "on", "the", "specified", "shards", ".", "This", "is", "a", "legacy", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L560-L606
train
vitessio/vitess
go/vt/vtgate/vtgate.go
StreamExecuteKeyspaceIds
func (vtg *VTGate) StreamExecuteKeyspaceIds(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyspaceIds [][]byte, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"StreamExecuteKeyspaceIds", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) var err error if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } err = vtg.resolver.StreamExecute( ctx, sql, bindVariables, keyspace, tabletType, key.DestinationKeyspaceIDs(keyspaceIds), options, func(reply *sqltypes.Result) error { vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows))) return callback(reply) }) handleError: if err != nil { query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Keyspace": keyspace, "KeyspaceIds": keyspaceIds, "TabletType": ltt, "Options": options, } return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecuteKeyspaceIds) } return nil }
go
func (vtg *VTGate) StreamExecuteKeyspaceIds(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyspaceIds [][]byte, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"StreamExecuteKeyspaceIds", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) var err error if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil { err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr) goto handleError } err = vtg.resolver.StreamExecute( ctx, sql, bindVariables, keyspace, tabletType, key.DestinationKeyspaceIDs(keyspaceIds), options, func(reply *sqltypes.Result) error { vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows))) return callback(reply) }) handleError: if err != nil { query := map[string]interface{}{ "Sql": sql, "BindVariables": bindVariables, "Keyspace": keyspace, "KeyspaceIds": keyspaceIds, "TabletType": ltt, "Options": options, } return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecuteKeyspaceIds) } return nil }
[ "func", "(", "vtg", "*", "VTGate", ")", "StreamExecuteKeyspaceIds", "(", "ctx", "context", ".", "Context", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "keyspace", "string", ",", "keyspaceIds", "[", "]", "[", "]", "byte", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "options", "*", "querypb", ".", "ExecuteOptions", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "ltt", ":=", "topoproto", ".", "TabletTypeLString", "(", "tabletType", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "keyspace", ",", "ltt", "}", "\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "startTime", ")", "\n\n", "var", "err", "error", "\n\n", "if", "bvErr", ":=", "sqltypes", ".", "ValidateBindVariables", "(", "bindVariables", ")", ";", "bvErr", "!=", "nil", "{", "err", "=", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "bvErr", ")", "\n", "goto", "handleError", "\n", "}", "\n\n", "err", "=", "vtg", ".", "resolver", ".", "StreamExecute", "(", "ctx", ",", "sql", ",", "bindVariables", ",", "keyspace", ",", "tabletType", ",", "key", ".", "DestinationKeyspaceIDs", "(", "keyspaceIds", ")", ",", "options", ",", "func", "(", "reply", "*", "sqltypes", ".", "Result", ")", "error", "{", "vtg", ".", "rowsReturned", ".", "Add", "(", "statsKey", ",", "int64", "(", "len", "(", "reply", ".", "Rows", ")", ")", ")", "\n", "return", "callback", "(", "reply", ")", "\n", "}", ")", "\n\n", "handleError", ":", "if", "err", "!=", "nil", "{", "query", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "sql", ",", "\"", "\"", ":", "bindVariables", ",", "\"", "\"", ":", "keyspace", ",", "\"", "\"", ":", "keyspaceIds", ",", "\"", "\"", ":", "ltt", ",", "\"", "\"", ":", "options", ",", "}", "\n", "return", "recordAndAnnotateError", "(", "err", ",", "statsKey", ",", "query", ",", "vtg", ".", "logStreamExecuteKeyspaceIds", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StreamExecuteKeyspaceIds executes a streaming query on the specified KeyspaceIds. // The KeyspaceIds are resolved to shards using the serving graph. // This function currently temporarily enforces the restriction of executing on // one shard since it cannot merge-sort the results to guarantee ordering of // response which is needed for checkpointing. // The api supports supplying multiple KeyspaceIds to make it future proof. This is a legacy function. // Note we guarantee the callback will not be called concurrently // by mutiple go routines.
[ "StreamExecuteKeyspaceIds", "executes", "a", "streaming", "query", "on", "the", "specified", "KeyspaceIds", ".", "The", "KeyspaceIds", "are", "resolved", "to", "shards", "using", "the", "serving", "graph", ".", "This", "function", "currently", "temporarily", "enforces", "the", "restriction", "of", "executing", "on", "one", "shard", "since", "it", "cannot", "merge", "-", "sort", "the", "results", "to", "guarantee", "ordering", "of", "response", "which", "is", "needed", "for", "checkpointing", ".", "The", "api", "supports", "supplying", "multiple", "KeyspaceIds", "to", "make", "it", "future", "proof", ".", "This", "is", "a", "legacy", "function", ".", "Note", "we", "guarantee", "the", "callback", "will", "not", "be", "called", "concurrently", "by", "mutiple", "go", "routines", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L665-L704
train
vitessio/vitess
go/vt/vtgate/vtgate.go
Begin
func (vtg *VTGate) Begin(ctx context.Context, singledb bool) (*vtgatepb.Session, error) { if !singledb && vtg.txConn.mode == vtgatepb.TransactionMode_SINGLE { return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "multi-db transaction disallowed") } return &vtgatepb.Session{ InTransaction: true, SingleDb: singledb, }, nil }
go
func (vtg *VTGate) Begin(ctx context.Context, singledb bool) (*vtgatepb.Session, error) { if !singledb && vtg.txConn.mode == vtgatepb.TransactionMode_SINGLE { return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "multi-db transaction disallowed") } return &vtgatepb.Session{ InTransaction: true, SingleDb: singledb, }, nil }
[ "func", "(", "vtg", "*", "VTGate", ")", "Begin", "(", "ctx", "context", ".", "Context", ",", "singledb", "bool", ")", "(", "*", "vtgatepb", ".", "Session", ",", "error", ")", "{", "if", "!", "singledb", "&&", "vtg", ".", "txConn", ".", "mode", "==", "vtgatepb", ".", "TransactionMode_SINGLE", "{", "return", "nil", ",", "vterrors", ".", "New", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "vtgatepb", ".", "Session", "{", "InTransaction", ":", "true", ",", "SingleDb", ":", "singledb", ",", "}", ",", "nil", "\n", "}" ]
// Begin begins a transaction. This is a legacy function.
[ "Begin", "begins", "a", "transaction", ".", "This", "is", "a", "legacy", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L800-L808
train
vitessio/vitess
go/vt/vtgate/vtgate.go
Commit
func (vtg *VTGate) Commit(ctx context.Context, twopc bool, session *vtgatepb.Session) error { if session == nil { return formatError(vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "cannot commit: empty session")) } if !session.InTransaction { return formatError(vterrors.New(vtrpcpb.Code_ABORTED, "cannot commit: not in transaction")) } if twopc { session.TransactionMode = vtgatepb.TransactionMode_TWOPC } return formatError(vtg.txConn.Commit(ctx, NewSafeSession(session))) }
go
func (vtg *VTGate) Commit(ctx context.Context, twopc bool, session *vtgatepb.Session) error { if session == nil { return formatError(vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "cannot commit: empty session")) } if !session.InTransaction { return formatError(vterrors.New(vtrpcpb.Code_ABORTED, "cannot commit: not in transaction")) } if twopc { session.TransactionMode = vtgatepb.TransactionMode_TWOPC } return formatError(vtg.txConn.Commit(ctx, NewSafeSession(session))) }
[ "func", "(", "vtg", "*", "VTGate", ")", "Commit", "(", "ctx", "context", ".", "Context", ",", "twopc", "bool", ",", "session", "*", "vtgatepb", ".", "Session", ")", "error", "{", "if", "session", "==", "nil", "{", "return", "formatError", "(", "vterrors", ".", "New", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "!", "session", ".", "InTransaction", "{", "return", "formatError", "(", "vterrors", ".", "New", "(", "vtrpcpb", ".", "Code_ABORTED", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "twopc", "{", "session", ".", "TransactionMode", "=", "vtgatepb", ".", "TransactionMode_TWOPC", "\n", "}", "\n", "return", "formatError", "(", "vtg", ".", "txConn", ".", "Commit", "(", "ctx", ",", "NewSafeSession", "(", "session", ")", ")", ")", "\n", "}" ]
// Commit commits a transaction. This is a legacy function.
[ "Commit", "commits", "a", "transaction", ".", "This", "is", "a", "legacy", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L811-L822
train
vitessio/vitess
go/vt/vtgate/vtgate.go
Rollback
func (vtg *VTGate) Rollback(ctx context.Context, session *vtgatepb.Session) error { return formatError(vtg.txConn.Rollback(ctx, NewSafeSession(session))) }
go
func (vtg *VTGate) Rollback(ctx context.Context, session *vtgatepb.Session) error { return formatError(vtg.txConn.Rollback(ctx, NewSafeSession(session))) }
[ "func", "(", "vtg", "*", "VTGate", ")", "Rollback", "(", "ctx", "context", ".", "Context", ",", "session", "*", "vtgatepb", ".", "Session", ")", "error", "{", "return", "formatError", "(", "vtg", ".", "txConn", ".", "Rollback", "(", "ctx", ",", "NewSafeSession", "(", "session", ")", ")", ")", "\n", "}" ]
// Rollback rolls back a transaction. This is a legacy function.
[ "Rollback", "rolls", "back", "a", "transaction", ".", "This", "is", "a", "legacy", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L825-L827
train
vitessio/vitess
go/vt/vtgate/vtgate.go
ResolveTransaction
func (vtg *VTGate) ResolveTransaction(ctx context.Context, dtid string) error { return formatError(vtg.txConn.Resolve(ctx, dtid)) }
go
func (vtg *VTGate) ResolveTransaction(ctx context.Context, dtid string) error { return formatError(vtg.txConn.Resolve(ctx, dtid)) }
[ "func", "(", "vtg", "*", "VTGate", ")", "ResolveTransaction", "(", "ctx", "context", ".", "Context", ",", "dtid", "string", ")", "error", "{", "return", "formatError", "(", "vtg", ".", "txConn", ".", "Resolve", "(", "ctx", ",", "dtid", ")", ")", "\n", "}" ]
// ResolveTransaction resolves the specified 2PC transaction.
[ "ResolveTransaction", "resolves", "the", "specified", "2PC", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L830-L832
train
vitessio/vitess
go/vt/vtgate/vtgate.go
GetSrvKeyspace
func (vtg *VTGate) GetSrvKeyspace(ctx context.Context, keyspace string) (*topodatapb.SrvKeyspace, error) { return vtg.resolver.toposerv.GetSrvKeyspace(ctx, vtg.resolver.cell, keyspace) }
go
func (vtg *VTGate) GetSrvKeyspace(ctx context.Context, keyspace string) (*topodatapb.SrvKeyspace, error) { return vtg.resolver.toposerv.GetSrvKeyspace(ctx, vtg.resolver.cell, keyspace) }
[ "func", "(", "vtg", "*", "VTGate", ")", "GetSrvKeyspace", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ")", "(", "*", "topodatapb", ".", "SrvKeyspace", ",", "error", ")", "{", "return", "vtg", ".", "resolver", ".", "toposerv", ".", "GetSrvKeyspace", "(", "ctx", ",", "vtg", ".", "resolver", ".", "cell", ",", "keyspace", ")", "\n", "}" ]
// GetSrvKeyspace is part of the vtgate service API.
[ "GetSrvKeyspace", "is", "part", "of", "the", "vtgate", "service", "API", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L939-L941
train
vitessio/vitess
go/vt/vtgate/vtgate.go
MessageStream
func (vtg *VTGate) MessageStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, name string, callback func(*sqltypes.Result) error) error { startTime := time.Now() ltt := topoproto.TabletTypeLString(topodatapb.TabletType_MASTER) statsKey := []string{"MessageStream", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) err := vtg.executor.MessageStream( ctx, keyspace, shard, keyRange, name, callback, ) if err != nil { request := map[string]interface{}{ "Keyspace": keyspace, "Shard": shard, "KeyRange": keyRange, "TabletType": ltt, "MessageName": name, } recordAndAnnotateError(err, statsKey, request, vtg.logMessageStream) } return formatError(err) }
go
func (vtg *VTGate) MessageStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, name string, callback func(*sqltypes.Result) error) error { startTime := time.Now() ltt := topoproto.TabletTypeLString(topodatapb.TabletType_MASTER) statsKey := []string{"MessageStream", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) err := vtg.executor.MessageStream( ctx, keyspace, shard, keyRange, name, callback, ) if err != nil { request := map[string]interface{}{ "Keyspace": keyspace, "Shard": shard, "KeyRange": keyRange, "TabletType": ltt, "MessageName": name, } recordAndAnnotateError(err, statsKey, request, vtg.logMessageStream) } return formatError(err) }
[ "func", "(", "vtg", "*", "VTGate", ")", "MessageStream", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "shard", "string", ",", "keyRange", "*", "topodatapb", ".", "KeyRange", ",", "name", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "ltt", ":=", "topoproto", ".", "TabletTypeLString", "(", "topodatapb", ".", "TabletType_MASTER", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "keyspace", ",", "ltt", "}", "\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "startTime", ")", "\n\n", "err", ":=", "vtg", ".", "executor", ".", "MessageStream", "(", "ctx", ",", "keyspace", ",", "shard", ",", "keyRange", ",", "name", ",", "callback", ",", ")", "\n", "if", "err", "!=", "nil", "{", "request", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "keyspace", ",", "\"", "\"", ":", "shard", ",", "\"", "\"", ":", "keyRange", ",", "\"", "\"", ":", "ltt", ",", "\"", "\"", ":", "name", ",", "}", "\n", "recordAndAnnotateError", "(", "err", ",", "statsKey", ",", "request", ",", "vtg", ".", "logMessageStream", ")", "\n", "}", "\n", "return", "formatError", "(", "err", ")", "\n", "}" ]
// MessageStream is part of the vtgate service API. This is a V2 level API // that's sent to the Resolver. // Note we guarantee the callback will not be called concurrently // by mutiple go routines.
[ "MessageStream", "is", "part", "of", "the", "vtgate", "service", "API", ".", "This", "is", "a", "V2", "level", "API", "that", "s", "sent", "to", "the", "Resolver", ".", "Note", "we", "guarantee", "the", "callback", "will", "not", "be", "called", "concurrently", "by", "mutiple", "go", "routines", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L947-L972
train
vitessio/vitess
go/vt/vtgate/vtgate.go
UpdateStream
func (vtg *VTGate) UpdateStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, tabletType topodatapb.TabletType, timestamp int64, event *querypb.EventToken, callback func(*querypb.StreamEvent, int64) error) error { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"UpdateStream", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) err := vtg.resolver.UpdateStream( ctx, keyspace, shard, keyRange, tabletType, timestamp, event, callback, ) if err != nil { request := map[string]interface{}{ "Keyspace": keyspace, "Shard": shard, "KeyRange": keyRange, "TabletType": ltt, "Timestamp": timestamp, } recordAndAnnotateError(err, statsKey, request, vtg.logUpdateStream) } return formatError(err) }
go
func (vtg *VTGate) UpdateStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, tabletType topodatapb.TabletType, timestamp int64, event *querypb.EventToken, callback func(*querypb.StreamEvent, int64) error) error { startTime := time.Now() ltt := topoproto.TabletTypeLString(tabletType) statsKey := []string{"UpdateStream", keyspace, ltt} defer vtg.timings.Record(statsKey, startTime) err := vtg.resolver.UpdateStream( ctx, keyspace, shard, keyRange, tabletType, timestamp, event, callback, ) if err != nil { request := map[string]interface{}{ "Keyspace": keyspace, "Shard": shard, "KeyRange": keyRange, "TabletType": ltt, "Timestamp": timestamp, } recordAndAnnotateError(err, statsKey, request, vtg.logUpdateStream) } return formatError(err) }
[ "func", "(", "vtg", "*", "VTGate", ")", "UpdateStream", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "shard", "string", ",", "keyRange", "*", "topodatapb", ".", "KeyRange", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "timestamp", "int64", ",", "event", "*", "querypb", ".", "EventToken", ",", "callback", "func", "(", "*", "querypb", ".", "StreamEvent", ",", "int64", ")", "error", ")", "error", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "ltt", ":=", "topoproto", ".", "TabletTypeLString", "(", "tabletType", ")", "\n", "statsKey", ":=", "[", "]", "string", "{", "\"", "\"", ",", "keyspace", ",", "ltt", "}", "\n", "defer", "vtg", ".", "timings", ".", "Record", "(", "statsKey", ",", "startTime", ")", "\n\n", "err", ":=", "vtg", ".", "resolver", ".", "UpdateStream", "(", "ctx", ",", "keyspace", ",", "shard", ",", "keyRange", ",", "tabletType", ",", "timestamp", ",", "event", ",", "callback", ",", ")", "\n", "if", "err", "!=", "nil", "{", "request", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "keyspace", ",", "\"", "\"", ":", "shard", ",", "\"", "\"", ":", "keyRange", ",", "\"", "\"", ":", "ltt", ",", "\"", "\"", ":", "timestamp", ",", "}", "\n", "recordAndAnnotateError", "(", "err", ",", "statsKey", ",", "request", ",", "vtg", ".", "logUpdateStream", ")", "\n", "}", "\n", "return", "formatError", "(", "err", ")", "\n", "}" ]
// UpdateStream is part of the vtgate service API. // Note we guarantee the callback will not be called concurrently // by mutiple go routines, as the current implementation can only target // one shard.
[ "UpdateStream", "is", "part", "of", "the", "vtgate", "service", "API", ".", "Note", "we", "guarantee", "the", "callback", "will", "not", "be", "called", "concurrently", "by", "mutiple", "go", "routines", "as", "the", "current", "implementation", "can", "only", "target", "one", "shard", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L1016-L1043
train
vitessio/vitess
go/vt/vtgate/vtgate.go
annotateBoundKeyspaceIDQueries
func annotateBoundKeyspaceIDQueries(queries []*vtgatepb.BoundKeyspaceIdQuery) { for i, q := range queries { queries[i].Query.Sql = sqlannotation.AnnotateIfDML(q.Query.Sql, q.KeyspaceIds) } }
go
func annotateBoundKeyspaceIDQueries(queries []*vtgatepb.BoundKeyspaceIdQuery) { for i, q := range queries { queries[i].Query.Sql = sqlannotation.AnnotateIfDML(q.Query.Sql, q.KeyspaceIds) } }
[ "func", "annotateBoundKeyspaceIDQueries", "(", "queries", "[", "]", "*", "vtgatepb", ".", "BoundKeyspaceIdQuery", ")", "{", "for", "i", ",", "q", ":=", "range", "queries", "{", "queries", "[", "i", "]", ".", "Query", ".", "Sql", "=", "sqlannotation", ".", "AnnotateIfDML", "(", "q", ".", "Query", ".", "Sql", ",", "q", ".", "KeyspaceIds", ")", "\n", "}", "\n", "}" ]
// Helper function used in ExecuteBatchKeyspaceIds
[ "Helper", "function", "used", "in", "ExecuteBatchKeyspaceIds" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L1114-L1118
train
vitessio/vitess
go/vt/vtgate/vtgate.go
annotateBoundShardQueriesAsUnfriendly
func annotateBoundShardQueriesAsUnfriendly(queries []*vtgatepb.BoundShardQuery) { for i, q := range queries { queries[i].Query.Sql = sqlannotation.AnnotateIfDML(q.Query.Sql, nil) } }
go
func annotateBoundShardQueriesAsUnfriendly(queries []*vtgatepb.BoundShardQuery) { for i, q := range queries { queries[i].Query.Sql = sqlannotation.AnnotateIfDML(q.Query.Sql, nil) } }
[ "func", "annotateBoundShardQueriesAsUnfriendly", "(", "queries", "[", "]", "*", "vtgatepb", ".", "BoundShardQuery", ")", "{", "for", "i", ",", "q", ":=", "range", "queries", "{", "queries", "[", "i", "]", ".", "Query", ".", "Sql", "=", "sqlannotation", ".", "AnnotateIfDML", "(", "q", ".", "Query", ".", "Sql", ",", "nil", ")", "\n", "}", "\n", "}" ]
// Helper function used in ExecuteBatchShards
[ "Helper", "function", "used", "in", "ExecuteBatchShards" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgate.go#L1121-L1125
train