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/mysql/flavor_mysql.go
readBinlogEvent
func (mysqlFlavor) readBinlogEvent(c *Conn) (BinlogEvent, error) { result, err := c.ReadPacket() if err != nil { return nil, err } switch result[0] { case EOFPacket: return nil, NewSQLError(CRServerLost, SSUnknownSQLState, "%v", io.EOF) case ErrPacket: return nil, ParseErrorPacket(result) } return NewMysql56BinlogEvent(result[1:]), nil }
go
func (mysqlFlavor) readBinlogEvent(c *Conn) (BinlogEvent, error) { result, err := c.ReadPacket() if err != nil { return nil, err } switch result[0] { case EOFPacket: return nil, NewSQLError(CRServerLost, SSUnknownSQLState, "%v", io.EOF) case ErrPacket: return nil, ParseErrorPacket(result) } return NewMysql56BinlogEvent(result[1:]), nil }
[ "func", "(", "mysqlFlavor", ")", "readBinlogEvent", "(", "c", "*", "Conn", ")", "(", "BinlogEvent", ",", "error", ")", "{", "result", ",", "err", ":=", "c", ".", "ReadPacket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "switch", "result", "[", "0", "]", "{", "case", "EOFPacket", ":", "return", "nil", ",", "NewSQLError", "(", "CRServerLost", ",", "SSUnknownSQLState", ",", "\"", "\"", ",", "io", ".", "EOF", ")", "\n", "case", "ErrPacket", ":", "return", "nil", ",", "ParseErrorPacket", "(", "result", ")", "\n", "}", "\n", "return", "NewMysql56BinlogEvent", "(", "result", "[", "1", ":", "]", ")", ",", "nil", "\n", "}" ]
// readBinlogEvent is part of the Flavor interface.
[ "readBinlogEvent", "is", "part", "of", "the", "Flavor", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/flavor_mysql.go#L138-L150
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/controller.go
newController
func newController(ctx context.Context, params map[string]string, dbClientFactory func() binlogplayer.DBClient, mysqld mysqlctl.MysqlDaemon, ts *topo.Server, cell, tabletTypesStr string, blpStats *binlogplayer.Stats) (*controller, error) { if blpStats == nil { blpStats = binlogplayer.NewStats() } ct := &controller{ dbClientFactory: dbClientFactory, mysqld: mysqld, blpStats: blpStats, done: make(chan struct{}), } // id id, err := strconv.Atoi(params["id"]) if err != nil { return nil, err } ct.id = uint32(id) // Nothing to do if replication is stopped. if params["state"] == binlogplayer.BlpStopped { ct.cancel = func() {} close(ct.done) return ct, nil } // source, stopPos if err := proto.UnmarshalText(params["source"], &ct.source); err != nil { return nil, err } ct.stopPos = params["stop_pos"] // tabletPicker if v, ok := params["cell"]; ok { cell = v } if v, ok := params["tablet_types"]; ok { tabletTypesStr = v } tp, err := newTabletPicker(ctx, ts, cell, ct.source.Keyspace, ct.source.Shard, tabletTypesStr) if err != nil { return nil, err } ct.tabletPicker = tp // cancel ctx, ct.cancel = context.WithCancel(ctx) go ct.run(ctx) return ct, nil }
go
func newController(ctx context.Context, params map[string]string, dbClientFactory func() binlogplayer.DBClient, mysqld mysqlctl.MysqlDaemon, ts *topo.Server, cell, tabletTypesStr string, blpStats *binlogplayer.Stats) (*controller, error) { if blpStats == nil { blpStats = binlogplayer.NewStats() } ct := &controller{ dbClientFactory: dbClientFactory, mysqld: mysqld, blpStats: blpStats, done: make(chan struct{}), } // id id, err := strconv.Atoi(params["id"]) if err != nil { return nil, err } ct.id = uint32(id) // Nothing to do if replication is stopped. if params["state"] == binlogplayer.BlpStopped { ct.cancel = func() {} close(ct.done) return ct, nil } // source, stopPos if err := proto.UnmarshalText(params["source"], &ct.source); err != nil { return nil, err } ct.stopPos = params["stop_pos"] // tabletPicker if v, ok := params["cell"]; ok { cell = v } if v, ok := params["tablet_types"]; ok { tabletTypesStr = v } tp, err := newTabletPicker(ctx, ts, cell, ct.source.Keyspace, ct.source.Shard, tabletTypesStr) if err != nil { return nil, err } ct.tabletPicker = tp // cancel ctx, ct.cancel = context.WithCancel(ctx) go ct.run(ctx) return ct, nil }
[ "func", "newController", "(", "ctx", "context", ".", "Context", ",", "params", "map", "[", "string", "]", "string", ",", "dbClientFactory", "func", "(", ")", "binlogplayer", ".", "DBClient", ",", "mysqld", "mysqlctl", ".", "MysqlDaemon", ",", "ts", "*", "topo", ".", "Server", ",", "cell", ",", "tabletTypesStr", "string", ",", "blpStats", "*", "binlogplayer", ".", "Stats", ")", "(", "*", "controller", ",", "error", ")", "{", "if", "blpStats", "==", "nil", "{", "blpStats", "=", "binlogplayer", ".", "NewStats", "(", ")", "\n", "}", "\n", "ct", ":=", "&", "controller", "{", "dbClientFactory", ":", "dbClientFactory", ",", "mysqld", ":", "mysqld", ",", "blpStats", ":", "blpStats", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "// id", "id", ",", "err", ":=", "strconv", ".", "Atoi", "(", "params", "[", "\"", "\"", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ct", ".", "id", "=", "uint32", "(", "id", ")", "\n\n", "// Nothing to do if replication is stopped.", "if", "params", "[", "\"", "\"", "]", "==", "binlogplayer", ".", "BlpStopped", "{", "ct", ".", "cancel", "=", "func", "(", ")", "{", "}", "\n", "close", "(", "ct", ".", "done", ")", "\n", "return", "ct", ",", "nil", "\n", "}", "\n\n", "// source, stopPos", "if", "err", ":=", "proto", ".", "UnmarshalText", "(", "params", "[", "\"", "\"", "]", ",", "&", "ct", ".", "source", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ct", ".", "stopPos", "=", "params", "[", "\"", "\"", "]", "\n\n", "// tabletPicker", "if", "v", ",", "ok", ":=", "params", "[", "\"", "\"", "]", ";", "ok", "{", "cell", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "params", "[", "\"", "\"", "]", ";", "ok", "{", "tabletTypesStr", "=", "v", "\n", "}", "\n", "tp", ",", "err", ":=", "newTabletPicker", "(", "ctx", ",", "ts", ",", "cell", ",", "ct", ".", "source", ".", "Keyspace", ",", "ct", ".", "source", ".", "Shard", ",", "tabletTypesStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ct", ".", "tabletPicker", "=", "tp", "\n\n", "// cancel", "ctx", ",", "ct", ".", "cancel", "=", "context", ".", "WithCancel", "(", "ctx", ")", "\n\n", "go", "ct", ".", "run", "(", "ctx", ")", "\n\n", "return", "ct", ",", "nil", "\n", "}" ]
// newController creates a new controller. Unless a stream is explicitly 'Stopped', // this function launches a goroutine to perform continuous vreplication.
[ "newController", "creates", "a", "new", "controller", ".", "Unless", "a", "stream", "is", "explicitly", "Stopped", "this", "function", "launches", "a", "goroutine", "to", "perform", "continuous", "vreplication", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/controller.go#L64-L114
train
vitessio/vitess
go/ioutil2/ioutil.go
WriteFileAtomic
func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error { dir, name := path.Split(filename) f, err := ioutil.TempFile(dir, name) if err != nil { return err } _, err = f.Write(data) if err == nil { err = f.Sync() } if closeErr := f.Close(); err == nil { err = closeErr } if permErr := os.Chmod(f.Name(), perm); err == nil { err = permErr } if err == nil { err = os.Rename(f.Name(), filename) } // Any err should result in full cleanup. if err != nil { os.Remove(f.Name()) } return err }
go
func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error { dir, name := path.Split(filename) f, err := ioutil.TempFile(dir, name) if err != nil { return err } _, err = f.Write(data) if err == nil { err = f.Sync() } if closeErr := f.Close(); err == nil { err = closeErr } if permErr := os.Chmod(f.Name(), perm); err == nil { err = permErr } if err == nil { err = os.Rename(f.Name(), filename) } // Any err should result in full cleanup. if err != nil { os.Remove(f.Name()) } return err }
[ "func", "WriteFileAtomic", "(", "filename", "string", ",", "data", "[", "]", "byte", ",", "perm", "os", ".", "FileMode", ")", "error", "{", "dir", ",", "name", ":=", "path", ".", "Split", "(", "filename", ")", "\n", "f", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "dir", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "f", ".", "Write", "(", "data", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "f", ".", "Sync", "(", ")", "\n", "}", "\n", "if", "closeErr", ":=", "f", ".", "Close", "(", ")", ";", "err", "==", "nil", "{", "err", "=", "closeErr", "\n", "}", "\n", "if", "permErr", ":=", "os", ".", "Chmod", "(", "f", ".", "Name", "(", ")", ",", "perm", ")", ";", "err", "==", "nil", "{", "err", "=", "permErr", "\n", "}", "\n", "if", "err", "==", "nil", "{", "err", "=", "os", ".", "Rename", "(", "f", ".", "Name", "(", ")", ",", "filename", ")", "\n", "}", "\n", "// Any err should result in full cleanup.", "if", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "f", ".", "Name", "(", ")", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// WriteFileAtomic writes the data to a temp file and atomically move if everything else succeeds.
[ "WriteFileAtomic", "writes", "the", "data", "to", "a", "temp", "file", "and", "atomically", "move", "if", "everything", "else", "succeeds", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/ioutil2/ioutil.go#L27-L51
train
vitessio/vitess
go/vt/dbconnpool/pooled_connection.go
Recycle
func (pc *PooledDBConnection) Recycle() { if pc.IsClosed() { pc.pool.Put(nil) } else { pc.pool.Put(pc) } }
go
func (pc *PooledDBConnection) Recycle() { if pc.IsClosed() { pc.pool.Put(nil) } else { pc.pool.Put(pc) } }
[ "func", "(", "pc", "*", "PooledDBConnection", ")", "Recycle", "(", ")", "{", "if", "pc", ".", "IsClosed", "(", ")", "{", "pc", ".", "pool", ".", "Put", "(", "nil", ")", "\n", "}", "else", "{", "pc", ".", "pool", ".", "Put", "(", "pc", ")", "\n", "}", "\n", "}" ]
// Recycle should be called to return the PooledDBConnection to the pool.
[ "Recycle", "should", "be", "called", "to", "return", "the", "PooledDBConnection", "to", "the", "pool", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/pooled_connection.go#L26-L32
train
vitessio/vitess
go/vt/dbconnpool/pooled_connection.go
Reconnect
func (pc *PooledDBConnection) Reconnect() error { pc.DBConnection.Close() newConn, err := NewDBConnection(pc.pool.info, pc.mysqlStats) if err != nil { return err } pc.DBConnection = newConn return nil }
go
func (pc *PooledDBConnection) Reconnect() error { pc.DBConnection.Close() newConn, err := NewDBConnection(pc.pool.info, pc.mysqlStats) if err != nil { return err } pc.DBConnection = newConn return nil }
[ "func", "(", "pc", "*", "PooledDBConnection", ")", "Reconnect", "(", ")", "error", "{", "pc", ".", "DBConnection", ".", "Close", "(", ")", "\n", "newConn", ",", "err", ":=", "NewDBConnection", "(", "pc", ".", "pool", ".", "info", ",", "pc", ".", "mysqlStats", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pc", ".", "DBConnection", "=", "newConn", "\n", "return", "nil", "\n", "}" ]
// Reconnect replaces the existing underlying connection with a new one, // if possible. Recycle should still be called afterwards.
[ "Reconnect", "replaces", "the", "existing", "underlying", "connection", "with", "a", "new", "one", "if", "possible", ".", "Recycle", "should", "still", "be", "called", "afterwards", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/pooled_connection.go#L36-L44
train
vitessio/vitess
go/vt/vttablet/tabletserver/txlimiter/tx_limiter.go
extractKey
func (txl *Impl) extractKey(immediate *querypb.VTGateCallerID, effective *vtrpcpb.CallerID) string { var parts []string if txl.byUsername { if immediate != nil { parts = append(parts, callerid.GetUsername(immediate)) } else { parts = append(parts, unknown) } } if txl.byEffectiveUser { if effective != nil { if txl.byPrincipal { parts = append(parts, callerid.GetPrincipal(effective)) } if txl.byComponent { parts = append(parts, callerid.GetComponent(effective)) } if txl.bySubcomponent { parts = append(parts, callerid.GetSubcomponent(effective)) } } else { parts = append(parts, unknown) } } return strings.Join(parts, "/") }
go
func (txl *Impl) extractKey(immediate *querypb.VTGateCallerID, effective *vtrpcpb.CallerID) string { var parts []string if txl.byUsername { if immediate != nil { parts = append(parts, callerid.GetUsername(immediate)) } else { parts = append(parts, unknown) } } if txl.byEffectiveUser { if effective != nil { if txl.byPrincipal { parts = append(parts, callerid.GetPrincipal(effective)) } if txl.byComponent { parts = append(parts, callerid.GetComponent(effective)) } if txl.bySubcomponent { parts = append(parts, callerid.GetSubcomponent(effective)) } } else { parts = append(parts, unknown) } } return strings.Join(parts, "/") }
[ "func", "(", "txl", "*", "Impl", ")", "extractKey", "(", "immediate", "*", "querypb", ".", "VTGateCallerID", ",", "effective", "*", "vtrpcpb", ".", "CallerID", ")", "string", "{", "var", "parts", "[", "]", "string", "\n", "if", "txl", ".", "byUsername", "{", "if", "immediate", "!=", "nil", "{", "parts", "=", "append", "(", "parts", ",", "callerid", ".", "GetUsername", "(", "immediate", ")", ")", "\n", "}", "else", "{", "parts", "=", "append", "(", "parts", ",", "unknown", ")", "\n", "}", "\n", "}", "\n", "if", "txl", ".", "byEffectiveUser", "{", "if", "effective", "!=", "nil", "{", "if", "txl", ".", "byPrincipal", "{", "parts", "=", "append", "(", "parts", ",", "callerid", ".", "GetPrincipal", "(", "effective", ")", ")", "\n", "}", "\n", "if", "txl", ".", "byComponent", "{", "parts", "=", "append", "(", "parts", ",", "callerid", ".", "GetComponent", "(", "effective", ")", ")", "\n", "}", "\n", "if", "txl", ".", "bySubcomponent", "{", "parts", "=", "append", "(", "parts", ",", "callerid", ".", "GetSubcomponent", "(", "effective", ")", ")", "\n", "}", "\n", "}", "else", "{", "parts", "=", "append", "(", "parts", ",", "unknown", ")", "\n", "}", "\n", "}", "\n\n", "return", "strings", ".", "Join", "(", "parts", ",", "\"", "\"", ")", "\n", "}" ]
// extractKey builds a string key used to differentiate users, based // on fields specified in configuration and their values from caller ID.
[ "extractKey", "builds", "a", "string", "key", "used", "to", "differentiate", "users", "based", "on", "fields", "specified", "in", "configuration", "and", "their", "values", "from", "caller", "ID", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/txlimiter/tx_limiter.go#L152-L178
train
vitessio/vitess
go/vt/vtgate/vindexes/vindex.go
Register
func Register(vindexType string, newVindexFunc NewVindexFunc) { if _, ok := registry[vindexType]; ok { panic(fmt.Sprintf("%s is already registered", vindexType)) } registry[vindexType] = newVindexFunc }
go
func Register(vindexType string, newVindexFunc NewVindexFunc) { if _, ok := registry[vindexType]; ok { panic(fmt.Sprintf("%s is already registered", vindexType)) } registry[vindexType] = newVindexFunc }
[ "func", "Register", "(", "vindexType", "string", ",", "newVindexFunc", "NewVindexFunc", ")", "{", "if", "_", ",", "ok", ":=", "registry", "[", "vindexType", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vindexType", ")", ")", "\n", "}", "\n", "registry", "[", "vindexType", "]", "=", "newVindexFunc", "\n", "}" ]
// Register registers a vindex under the specified vindexType. // A duplicate vindexType will generate a panic. // New vindexes will be created using these functions at the // time of vschema loading.
[ "Register", "registers", "a", "vindex", "under", "the", "specified", "vindexType", ".", "A", "duplicate", "vindexType", "will", "generate", "a", "panic", ".", "New", "vindexes", "will", "be", "created", "using", "these", "functions", "at", "the", "time", "of", "vschema", "loading", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/vindex.go#L116-L121
train
vitessio/vitess
go/vt/vtgate/vindexes/vindex.go
CreateVindex
func CreateVindex(vindexType, name string, params map[string]string) (Vindex, error) { f, ok := registry[vindexType] if !ok { return nil, fmt.Errorf("vindexType %q not found", vindexType) } return f(name, params) }
go
func CreateVindex(vindexType, name string, params map[string]string) (Vindex, error) { f, ok := registry[vindexType] if !ok { return nil, fmt.Errorf("vindexType %q not found", vindexType) } return f(name, params) }
[ "func", "CreateVindex", "(", "vindexType", ",", "name", "string", ",", "params", "map", "[", "string", "]", "string", ")", "(", "Vindex", ",", "error", ")", "{", "f", ",", "ok", ":=", "registry", "[", "vindexType", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vindexType", ")", "\n", "}", "\n", "return", "f", "(", "name", ",", "params", ")", "\n", "}" ]
// CreateVindex creates a vindex of the specified type using the // supplied params. The type must have been previously registered.
[ "CreateVindex", "creates", "a", "vindex", "of", "the", "specified", "type", "using", "the", "supplied", "params", ".", "The", "type", "must", "have", "been", "previously", "registered", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/vindex.go#L125-L131
train
vitessio/vitess
go/vt/dbconfigs/dbconfigs.go
RegisterFlags
func RegisterFlags(userKeys ...string) { registerBaseFlags() for _, userKey := range userKeys { uc := &userConfig{} dbConfigs.userConfigs[userKey] = uc registerPerUserFlags(uc, userKey) } }
go
func RegisterFlags(userKeys ...string) { registerBaseFlags() for _, userKey := range userKeys { uc := &userConfig{} dbConfigs.userConfigs[userKey] = uc registerPerUserFlags(uc, userKey) } }
[ "func", "RegisterFlags", "(", "userKeys", "...", "string", ")", "{", "registerBaseFlags", "(", ")", "\n", "for", "_", ",", "userKey", ":=", "range", "userKeys", "{", "uc", ":=", "&", "userConfig", "{", "}", "\n", "dbConfigs", ".", "userConfigs", "[", "userKey", "]", "=", "uc", "\n", "registerPerUserFlags", "(", "uc", ",", "userKey", ")", "\n", "}", "\n", "}" ]
// RegisterFlags registers the flags for the given DBConfigFlag. // For instance, vttablet will register client, dba and repl. // Returns all registered flags.
[ "RegisterFlags", "registers", "the", "flags", "for", "the", "given", "DBConfigFlag", ".", "For", "instance", "vttablet", "will", "register", "client", "dba", "and", "repl", ".", "Returns", "all", "registered", "flags", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconfigs/dbconfigs.go#L84-L91
train
vitessio/vitess
go/vt/dbconfigs/dbconfigs.go
makeParams
func (dbcfgs *DBConfigs) makeParams(userKey string, withDB bool) *mysql.ConnParams { orig := dbcfgs.userConfigs[userKey] if orig == nil { return &mysql.ConnParams{} } result := orig.param if withDB { result.DbName = dbcfgs.DBName.Get() } return &result }
go
func (dbcfgs *DBConfigs) makeParams(userKey string, withDB bool) *mysql.ConnParams { orig := dbcfgs.userConfigs[userKey] if orig == nil { return &mysql.ConnParams{} } result := orig.param if withDB { result.DbName = dbcfgs.DBName.Get() } return &result }
[ "func", "(", "dbcfgs", "*", "DBConfigs", ")", "makeParams", "(", "userKey", "string", ",", "withDB", "bool", ")", "*", "mysql", ".", "ConnParams", "{", "orig", ":=", "dbcfgs", ".", "userConfigs", "[", "userKey", "]", "\n", "if", "orig", "==", "nil", "{", "return", "&", "mysql", ".", "ConnParams", "{", "}", "\n", "}", "\n", "result", ":=", "orig", ".", "param", "\n", "if", "withDB", "{", "result", ".", "DbName", "=", "dbcfgs", ".", "DBName", ".", "Get", "(", ")", "\n", "}", "\n", "return", "&", "result", "\n", "}" ]
// AppWithDB returns connection parameters for app with dbname set.
[ "AppWithDB", "returns", "connection", "parameters", "for", "app", "with", "dbname", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconfigs/dbconfigs.go#L171-L181
train
vitessio/vitess
go/vt/dbconfigs/dbconfigs.go
Copy
func (dbcfgs *DBConfigs) Copy() *DBConfigs { result := &DBConfigs{userConfigs: make(map[string]*userConfig)} for k, u := range dbcfgs.userConfigs { newu := *u result.userConfigs[k] = &newu } result.DBName.Set(dbcfgs.DBName.Get()) result.SidecarDBName.Set(dbcfgs.SidecarDBName.Get()) return result }
go
func (dbcfgs *DBConfigs) Copy() *DBConfigs { result := &DBConfigs{userConfigs: make(map[string]*userConfig)} for k, u := range dbcfgs.userConfigs { newu := *u result.userConfigs[k] = &newu } result.DBName.Set(dbcfgs.DBName.Get()) result.SidecarDBName.Set(dbcfgs.SidecarDBName.Get()) return result }
[ "func", "(", "dbcfgs", "*", "DBConfigs", ")", "Copy", "(", ")", "*", "DBConfigs", "{", "result", ":=", "&", "DBConfigs", "{", "userConfigs", ":", "make", "(", "map", "[", "string", "]", "*", "userConfig", ")", "}", "\n", "for", "k", ",", "u", ":=", "range", "dbcfgs", ".", "userConfigs", "{", "newu", ":=", "*", "u", "\n", "result", ".", "userConfigs", "[", "k", "]", "=", "&", "newu", "\n", "}", "\n", "result", ".", "DBName", ".", "Set", "(", "dbcfgs", ".", "DBName", ".", "Get", "(", ")", ")", "\n", "result", ".", "SidecarDBName", ".", "Set", "(", "dbcfgs", ".", "SidecarDBName", ".", "Get", "(", ")", ")", "\n", "return", "result", "\n", "}" ]
// Copy returns a copy of the DBConfig.
[ "Copy", "returns", "a", "copy", "of", "the", "DBConfig", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconfigs/dbconfigs.go#L212-L221
train
vitessio/vitess
go/vt/mysqlctl/query.go
getPoolReconnect
func getPoolReconnect(ctx context.Context, pool *dbconnpool.ConnectionPool) (*dbconnpool.PooledDBConnection, error) { conn, err := pool.Get(ctx) if err != nil { return conn, err } // Run a test query to see if this connection is still good. if _, err := conn.ExecuteFetch("SELECT 1", 1, false); err != nil { // If we get a connection error, try to reconnect. if sqlErr, ok := err.(*mysql.SQLError); ok && (sqlErr.Number() == mysql.CRServerGone || sqlErr.Number() == mysql.CRServerLost) { if err := conn.Reconnect(); err != nil { conn.Recycle() return nil, err } return conn, nil } conn.Recycle() return nil, err } return conn, nil }
go
func getPoolReconnect(ctx context.Context, pool *dbconnpool.ConnectionPool) (*dbconnpool.PooledDBConnection, error) { conn, err := pool.Get(ctx) if err != nil { return conn, err } // Run a test query to see if this connection is still good. if _, err := conn.ExecuteFetch("SELECT 1", 1, false); err != nil { // If we get a connection error, try to reconnect. if sqlErr, ok := err.(*mysql.SQLError); ok && (sqlErr.Number() == mysql.CRServerGone || sqlErr.Number() == mysql.CRServerLost) { if err := conn.Reconnect(); err != nil { conn.Recycle() return nil, err } return conn, nil } conn.Recycle() return nil, err } return conn, nil }
[ "func", "getPoolReconnect", "(", "ctx", "context", ".", "Context", ",", "pool", "*", "dbconnpool", ".", "ConnectionPool", ")", "(", "*", "dbconnpool", ".", "PooledDBConnection", ",", "error", ")", "{", "conn", ",", "err", ":=", "pool", ".", "Get", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "conn", ",", "err", "\n", "}", "\n", "// Run a test query to see if this connection is still good.", "if", "_", ",", "err", ":=", "conn", ".", "ExecuteFetch", "(", "\"", "\"", ",", "1", ",", "false", ")", ";", "err", "!=", "nil", "{", "// If we get a connection error, try to reconnect.", "if", "sqlErr", ",", "ok", ":=", "err", ".", "(", "*", "mysql", ".", "SQLError", ")", ";", "ok", "&&", "(", "sqlErr", ".", "Number", "(", ")", "==", "mysql", ".", "CRServerGone", "||", "sqlErr", ".", "Number", "(", ")", "==", "mysql", ".", "CRServerLost", ")", "{", "if", "err", ":=", "conn", ".", "Reconnect", "(", ")", ";", "err", "!=", "nil", "{", "conn", ".", "Recycle", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}", "\n", "conn", ".", "Recycle", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}" ]
// getPoolReconnect gets a connection from a pool, tests it, and reconnects if // the connection is lost.
[ "getPoolReconnect", "gets", "a", "connection", "from", "a", "pool", "tests", "it", "and", "reconnects", "if", "the", "connection", "is", "lost", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/query.go#L34-L53
train
vitessio/vitess
go/vt/mysqlctl/query.go
ExecuteSuperQuery
func (mysqld *Mysqld) ExecuteSuperQuery(ctx context.Context, query string) error { return mysqld.ExecuteSuperQueryList(ctx, []string{query}) }
go
func (mysqld *Mysqld) ExecuteSuperQuery(ctx context.Context, query string) error { return mysqld.ExecuteSuperQueryList(ctx, []string{query}) }
[ "func", "(", "mysqld", "*", "Mysqld", ")", "ExecuteSuperQuery", "(", "ctx", "context", ".", "Context", ",", "query", "string", ")", "error", "{", "return", "mysqld", ".", "ExecuteSuperQueryList", "(", "ctx", ",", "[", "]", "string", "{", "query", "}", ")", "\n", "}" ]
// ExecuteSuperQuery allows the user to execute a query as a super user.
[ "ExecuteSuperQuery", "allows", "the", "user", "to", "execute", "a", "query", "as", "a", "super", "user", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/query.go#L56-L58
train
vitessio/vitess
go/vt/mysqlctl/query.go
ExecuteSuperQueryList
func (mysqld *Mysqld) ExecuteSuperQueryList(ctx context.Context, queryList []string) error { conn, err := getPoolReconnect(ctx, mysqld.dbaPool) if err != nil { return err } defer conn.Recycle() return mysqld.executeSuperQueryListConn(ctx, conn, queryList) }
go
func (mysqld *Mysqld) ExecuteSuperQueryList(ctx context.Context, queryList []string) error { conn, err := getPoolReconnect(ctx, mysqld.dbaPool) if err != nil { return err } defer conn.Recycle() return mysqld.executeSuperQueryListConn(ctx, conn, queryList) }
[ "func", "(", "mysqld", "*", "Mysqld", ")", "ExecuteSuperQueryList", "(", "ctx", "context", ".", "Context", ",", "queryList", "[", "]", "string", ")", "error", "{", "conn", ",", "err", ":=", "getPoolReconnect", "(", "ctx", ",", "mysqld", ".", "dbaPool", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n\n", "return", "mysqld", ".", "executeSuperQueryListConn", "(", "ctx", ",", "conn", ",", "queryList", ")", "\n", "}" ]
// ExecuteSuperQueryList alows the user to execute queries as a super user.
[ "ExecuteSuperQueryList", "alows", "the", "user", "to", "execute", "queries", "as", "a", "super", "user", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/query.go#L61-L69
train
vitessio/vitess
go/vt/mysqlctl/query.go
FetchSuperQuery
func (mysqld *Mysqld) FetchSuperQuery(ctx context.Context, query string) (*sqltypes.Result, error) { conn, connErr := getPoolReconnect(ctx, mysqld.dbaPool) if connErr != nil { return nil, connErr } defer conn.Recycle() log.V(6).Infof("fetch %v", query) qr, err := mysqld.executeFetchContext(ctx, conn, query, 10000, true) if err != nil { return nil, err } return qr, nil }
go
func (mysqld *Mysqld) FetchSuperQuery(ctx context.Context, query string) (*sqltypes.Result, error) { conn, connErr := getPoolReconnect(ctx, mysqld.dbaPool) if connErr != nil { return nil, connErr } defer conn.Recycle() log.V(6).Infof("fetch %v", query) qr, err := mysqld.executeFetchContext(ctx, conn, query, 10000, true) if err != nil { return nil, err } return qr, nil }
[ "func", "(", "mysqld", "*", "Mysqld", ")", "FetchSuperQuery", "(", "ctx", "context", ".", "Context", ",", "query", "string", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "conn", ",", "connErr", ":=", "getPoolReconnect", "(", "ctx", ",", "mysqld", ".", "dbaPool", ")", "\n", "if", "connErr", "!=", "nil", "{", "return", "nil", ",", "connErr", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n", "log", ".", "V", "(", "6", ")", ".", "Infof", "(", "\"", "\"", ",", "query", ")", "\n", "qr", ",", "err", ":=", "mysqld", ".", "executeFetchContext", "(", "ctx", ",", "conn", ",", "query", ",", "10000", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "qr", ",", "nil", "\n", "}" ]
// FetchSuperQuery returns the results of executing a query as a super user.
[ "FetchSuperQuery", "returns", "the", "results", "of", "executing", "a", "query", "as", "a", "super", "user", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/query.go#L82-L94
train
vitessio/vitess
go/vt/mysqlctl/query.go
killConnection
func (mysqld *Mysqld) killConnection(connID int64) error { // There's no other interface that both types of connection implement. // We only care about one method anyway. var killConn interface { ExecuteFetch(query string, maxrows int, wantfields bool) (*sqltypes.Result, error) } // Get another connection with which to kill. // Use background context because the caller's context is likely expired, // which is the reason we're being asked to kill the connection. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() if poolConn, connErr := getPoolReconnect(ctx, mysqld.dbaPool); connErr == nil { // We got a pool connection. defer poolConn.Recycle() killConn = poolConn } else { // We couldn't get a connection from the pool. // It might be because the connection pool is exhausted, // because some connections need to be killed! // Try to open a new connection without the pool. killConn, connErr = mysqld.GetDbaConnection() if connErr != nil { return connErr } } _, err := killConn.ExecuteFetch(fmt.Sprintf("kill %d", connID), 10000, false) return err }
go
func (mysqld *Mysqld) killConnection(connID int64) error { // There's no other interface that both types of connection implement. // We only care about one method anyway. var killConn interface { ExecuteFetch(query string, maxrows int, wantfields bool) (*sqltypes.Result, error) } // Get another connection with which to kill. // Use background context because the caller's context is likely expired, // which is the reason we're being asked to kill the connection. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() if poolConn, connErr := getPoolReconnect(ctx, mysqld.dbaPool); connErr == nil { // We got a pool connection. defer poolConn.Recycle() killConn = poolConn } else { // We couldn't get a connection from the pool. // It might be because the connection pool is exhausted, // because some connections need to be killed! // Try to open a new connection without the pool. killConn, connErr = mysqld.GetDbaConnection() if connErr != nil { return connErr } } _, err := killConn.ExecuteFetch(fmt.Sprintf("kill %d", connID), 10000, false) return err }
[ "func", "(", "mysqld", "*", "Mysqld", ")", "killConnection", "(", "connID", "int64", ")", "error", "{", "// There's no other interface that both types of connection implement.", "// We only care about one method anyway.", "var", "killConn", "interface", "{", "ExecuteFetch", "(", "query", "string", ",", "maxrows", "int", ",", "wantfields", "bool", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "\n", "}", "\n\n", "// Get another connection with which to kill.", "// Use background context because the caller's context is likely expired,", "// which is the reason we're being asked to kill the connection.", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "1", "*", "time", ".", "Second", ")", "\n", "defer", "cancel", "(", ")", "\n", "if", "poolConn", ",", "connErr", ":=", "getPoolReconnect", "(", "ctx", ",", "mysqld", ".", "dbaPool", ")", ";", "connErr", "==", "nil", "{", "// We got a pool connection.", "defer", "poolConn", ".", "Recycle", "(", ")", "\n", "killConn", "=", "poolConn", "\n", "}", "else", "{", "// We couldn't get a connection from the pool.", "// It might be because the connection pool is exhausted,", "// because some connections need to be killed!", "// Try to open a new connection without the pool.", "killConn", ",", "connErr", "=", "mysqld", ".", "GetDbaConnection", "(", ")", "\n", "if", "connErr", "!=", "nil", "{", "return", "connErr", "\n", "}", "\n", "}", "\n\n", "_", ",", "err", ":=", "killConn", ".", "ExecuteFetch", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "connID", ")", ",", "10000", ",", "false", ")", "\n", "return", "err", "\n", "}" ]
// killConnection issues a MySQL KILL command for the given connection ID.
[ "killConnection", "issues", "a", "MySQL", "KILL", "command", "for", "the", "given", "connection", "ID", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/query.go#L153-L182
train
vitessio/vitess
go/vt/mysqlctl/query.go
fetchVariables
func (mysqld *Mysqld) fetchVariables(ctx context.Context, pattern string) (map[string]string, error) { query := fmt.Sprintf("SHOW VARIABLES LIKE '%s'", pattern) qr, err := mysqld.FetchSuperQuery(ctx, query) if err != nil { return nil, err } if len(qr.Fields) != 2 { return nil, fmt.Errorf("query %#v returned %d columns, expected 2", query, len(qr.Fields)) } varMap := make(map[string]string, len(qr.Rows)) for _, row := range qr.Rows { varMap[row[0].ToString()] = row[1].ToString() } return varMap, nil }
go
func (mysqld *Mysqld) fetchVariables(ctx context.Context, pattern string) (map[string]string, error) { query := fmt.Sprintf("SHOW VARIABLES LIKE '%s'", pattern) qr, err := mysqld.FetchSuperQuery(ctx, query) if err != nil { return nil, err } if len(qr.Fields) != 2 { return nil, fmt.Errorf("query %#v returned %d columns, expected 2", query, len(qr.Fields)) } varMap := make(map[string]string, len(qr.Rows)) for _, row := range qr.Rows { varMap[row[0].ToString()] = row[1].ToString() } return varMap, nil }
[ "func", "(", "mysqld", "*", "Mysqld", ")", "fetchVariables", "(", "ctx", "context", ".", "Context", ",", "pattern", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "query", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pattern", ")", "\n", "qr", ",", "err", ":=", "mysqld", ".", "FetchSuperQuery", "(", "ctx", ",", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "qr", ".", "Fields", ")", "!=", "2", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "query", ",", "len", "(", "qr", ".", "Fields", ")", ")", "\n", "}", "\n", "varMap", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "qr", ".", "Rows", ")", ")", "\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "varMap", "[", "row", "[", "0", "]", ".", "ToString", "(", ")", "]", "=", "row", "[", "1", "]", ".", "ToString", "(", ")", "\n", "}", "\n", "return", "varMap", ",", "nil", "\n", "}" ]
// fetchVariables returns a map from MySQL variable names to variable value // for variables that match the given pattern.
[ "fetchVariables", "returns", "a", "map", "from", "MySQL", "variable", "names", "to", "variable", "value", "for", "variables", "that", "match", "the", "given", "pattern", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/query.go#L186-L200
train
vitessio/vitess
go/streamlog/streamlog.go
New
func New(name string, size int) *StreamLogger { return &StreamLogger{ name: name, size: size, subscribed: make(map[chan interface{}]string), } }
go
func New(name string, size int) *StreamLogger { return &StreamLogger{ name: name, size: size, subscribed: make(map[chan interface{}]string), } }
[ "func", "New", "(", "name", "string", ",", "size", "int", ")", "*", "StreamLogger", "{", "return", "&", "StreamLogger", "{", "name", ":", "name", ",", "size", ":", "size", ",", "subscribed", ":", "make", "(", "map", "[", "chan", "interface", "{", "}", "]", "string", ")", ",", "}", "\n", "}" ]
// New returns a new StreamLogger that can stream events to subscribers. // The size parameter defines the channel size for the subscribers.
[ "New", "returns", "a", "new", "StreamLogger", "that", "can", "stream", "events", "to", "subscribers", ".", "The", "size", "parameter", "defines", "the", "channel", "size", "for", "the", "subscribers", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/streamlog/streamlog.go#L77-L83
train
vitessio/vitess
go/streamlog/streamlog.go
Send
func (logger *StreamLogger) Send(message interface{}) { logger.mu.Lock() defer logger.mu.Unlock() for ch, name := range logger.subscribed { select { case ch <- message: deliveredCount.Add([]string{logger.name, name}, 1) default: deliveryDropCount.Add([]string{logger.name, name}, 1) } } sendCount.Add(logger.name, 1) }
go
func (logger *StreamLogger) Send(message interface{}) { logger.mu.Lock() defer logger.mu.Unlock() for ch, name := range logger.subscribed { select { case ch <- message: deliveredCount.Add([]string{logger.name, name}, 1) default: deliveryDropCount.Add([]string{logger.name, name}, 1) } } sendCount.Add(logger.name, 1) }
[ "func", "(", "logger", "*", "StreamLogger", ")", "Send", "(", "message", "interface", "{", "}", ")", "{", "logger", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "logger", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "for", "ch", ",", "name", ":=", "range", "logger", ".", "subscribed", "{", "select", "{", "case", "ch", "<-", "message", ":", "deliveredCount", ".", "Add", "(", "[", "]", "string", "{", "logger", ".", "name", ",", "name", "}", ",", "1", ")", "\n", "default", ":", "deliveryDropCount", ".", "Add", "(", "[", "]", "string", "{", "logger", ".", "name", ",", "name", "}", ",", "1", ")", "\n", "}", "\n", "}", "\n", "sendCount", ".", "Add", "(", "logger", ".", "name", ",", "1", ")", "\n", "}" ]
// Send sends message to all the writers subscribed to logger. Calling // Send does not block.
[ "Send", "sends", "message", "to", "all", "the", "writers", "subscribed", "to", "logger", ".", "Calling", "Send", "does", "not", "block", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/streamlog/streamlog.go#L87-L100
train
vitessio/vitess
go/streamlog/streamlog.go
Subscribe
func (logger *StreamLogger) Subscribe(name string) chan interface{} { logger.mu.Lock() defer logger.mu.Unlock() ch := make(chan interface{}, logger.size) logger.subscribed[ch] = name return ch }
go
func (logger *StreamLogger) Subscribe(name string) chan interface{} { logger.mu.Lock() defer logger.mu.Unlock() ch := make(chan interface{}, logger.size) logger.subscribed[ch] = name return ch }
[ "func", "(", "logger", "*", "StreamLogger", ")", "Subscribe", "(", "name", "string", ")", "chan", "interface", "{", "}", "{", "logger", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "logger", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "ch", ":=", "make", "(", "chan", "interface", "{", "}", ",", "logger", ".", "size", ")", "\n", "logger", ".", "subscribed", "[", "ch", "]", "=", "name", "\n", "return", "ch", "\n", "}" ]
// Subscribe returns a channel which can be used to listen // for messages.
[ "Subscribe", "returns", "a", "channel", "which", "can", "be", "used", "to", "listen", "for", "messages", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/streamlog/streamlog.go#L104-L111
train
vitessio/vitess
go/streamlog/streamlog.go
Unsubscribe
func (logger *StreamLogger) Unsubscribe(ch chan interface{}) { logger.mu.Lock() defer logger.mu.Unlock() delete(logger.subscribed, ch) }
go
func (logger *StreamLogger) Unsubscribe(ch chan interface{}) { logger.mu.Lock() defer logger.mu.Unlock() delete(logger.subscribed, ch) }
[ "func", "(", "logger", "*", "StreamLogger", ")", "Unsubscribe", "(", "ch", "chan", "interface", "{", "}", ")", "{", "logger", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "logger", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "logger", ".", "subscribed", ",", "ch", ")", "\n", "}" ]
// Unsubscribe removes the channel from the subscription.
[ "Unsubscribe", "removes", "the", "channel", "from", "the", "subscription", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/streamlog/streamlog.go#L114-L119
train
vitessio/vitess
go/streamlog/streamlog.go
ServeLogs
func (logger *StreamLogger) ServeLogs(url string, logf LogFormatter) { http.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil { acl.SendError(w, err) return } if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } ch := logger.Subscribe("ServeLogs") defer logger.Unsubscribe(ch) // Notify client that we're set up. Helpful to distinguish low-traffic streams from connection issues. w.WriteHeader(http.StatusOK) w.(http.Flusher).Flush() for message := range ch { if err := logf(w, r.Form, message); err != nil { return } w.(http.Flusher).Flush() } }) log.Infof("Streaming logs from %s at %v.", logger.Name(), url) }
go
func (logger *StreamLogger) ServeLogs(url string, logf LogFormatter) { http.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil { acl.SendError(w, err) return } if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } ch := logger.Subscribe("ServeLogs") defer logger.Unsubscribe(ch) // Notify client that we're set up. Helpful to distinguish low-traffic streams from connection issues. w.WriteHeader(http.StatusOK) w.(http.Flusher).Flush() for message := range ch { if err := logf(w, r.Form, message); err != nil { return } w.(http.Flusher).Flush() } }) log.Infof("Streaming logs from %s at %v.", logger.Name(), url) }
[ "func", "(", "logger", "*", "StreamLogger", ")", "ServeLogs", "(", "url", "string", ",", "logf", "LogFormatter", ")", "{", "http", ".", "HandleFunc", "(", "url", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "acl", ".", "CheckAccessHTTP", "(", "r", ",", "acl", ".", "DEBUGGING", ")", ";", "err", "!=", "nil", "{", "acl", ".", "SendError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "r", ".", "ParseForm", "(", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "}", "\n", "ch", ":=", "logger", ".", "Subscribe", "(", "\"", "\"", ")", "\n", "defer", "logger", ".", "Unsubscribe", "(", "ch", ")", "\n\n", "// Notify client that we're set up. Helpful to distinguish low-traffic streams from connection issues.", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "w", ".", "(", "http", ".", "Flusher", ")", ".", "Flush", "(", ")", "\n\n", "for", "message", ":=", "range", "ch", "{", "if", "err", ":=", "logf", "(", "w", ",", "r", ".", "Form", ",", "message", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "w", ".", "(", "http", ".", "Flusher", ")", ".", "Flush", "(", ")", "\n", "}", "\n", "}", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "logger", ".", "Name", "(", ")", ",", "url", ")", "\n", "}" ]
// ServeLogs registers the URL on which messages will be broadcast. // It is safe to register multiple URLs for the same StreamLogger.
[ "ServeLogs", "registers", "the", "URL", "on", "which", "messages", "will", "be", "broadcast", ".", "It", "is", "safe", "to", "register", "multiple", "URLs", "for", "the", "same", "StreamLogger", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/streamlog/streamlog.go#L128-L152
train
vitessio/vitess
go/streamlog/streamlog.go
LogToFile
func (logger *StreamLogger) LogToFile(path string, logf LogFormatter) (chan interface{}, error) { rotateChan := make(chan os.Signal, 1) signal.Notify(rotateChan, syscall.SIGUSR2) logChan := logger.Subscribe("FileLog") formatParams := map[string][]string{"full": {}} f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return nil, err } go func() { for { select { case record := <-logChan: logf(f, formatParams, record) case <-rotateChan: f.Close() f, _ = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) } } }() return logChan, nil }
go
func (logger *StreamLogger) LogToFile(path string, logf LogFormatter) (chan interface{}, error) { rotateChan := make(chan os.Signal, 1) signal.Notify(rotateChan, syscall.SIGUSR2) logChan := logger.Subscribe("FileLog") formatParams := map[string][]string{"full": {}} f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return nil, err } go func() { for { select { case record := <-logChan: logf(f, formatParams, record) case <-rotateChan: f.Close() f, _ = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) } } }() return logChan, nil }
[ "func", "(", "logger", "*", "StreamLogger", ")", "LogToFile", "(", "path", "string", ",", "logf", "LogFormatter", ")", "(", "chan", "interface", "{", "}", ",", "error", ")", "{", "rotateChan", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "rotateChan", ",", "syscall", ".", "SIGUSR2", ")", "\n\n", "logChan", ":=", "logger", ".", "Subscribe", "(", "\"", "\"", ")", "\n", "formatParams", ":=", "map", "[", "string", "]", "[", "]", "string", "{", "\"", "\"", ":", "{", "}", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_APPEND", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "record", ":=", "<-", "logChan", ":", "logf", "(", "f", ",", "formatParams", ",", "record", ")", "\n", "case", "<-", "rotateChan", ":", "f", ".", "Close", "(", ")", "\n", "f", ",", "_", "=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_APPEND", ",", "0644", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "logChan", ",", "nil", "\n", "}" ]
// LogToFile starts logging to the specified file path and will reopen the // file in response to SIGUSR2. // // Returns the channel used for the subscription which can be used to close // it.
[ "LogToFile", "starts", "logging", "to", "the", "specified", "file", "path", "and", "will", "reopen", "the", "file", "in", "response", "to", "SIGUSR2", ".", "Returns", "the", "channel", "used", "for", "the", "subscription", "which", "can", "be", "used", "to", "close", "it", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/streamlog/streamlog.go#L159-L184
train
vitessio/vitess
go/streamlog/streamlog.go
GetFormatter
func GetFormatter(logger *StreamLogger) LogFormatter { return func(w io.Writer, params url.Values, val interface{}) error { fmter, ok := val.(Formatter) if !ok { _, err := fmt.Fprintf(w, "Error: unexpected value of type %T in %s!", val, logger.Name()) return err } return fmter.Logf(w, params) } }
go
func GetFormatter(logger *StreamLogger) LogFormatter { return func(w io.Writer, params url.Values, val interface{}) error { fmter, ok := val.(Formatter) if !ok { _, err := fmt.Fprintf(w, "Error: unexpected value of type %T in %s!", val, logger.Name()) return err } return fmter.Logf(w, params) } }
[ "func", "GetFormatter", "(", "logger", "*", "StreamLogger", ")", "LogFormatter", "{", "return", "func", "(", "w", "io", ".", "Writer", ",", "params", "url", ".", "Values", ",", "val", "interface", "{", "}", ")", "error", "{", "fmter", ",", "ok", ":=", "val", ".", "(", "Formatter", ")", "\n", "if", "!", "ok", "{", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\"", ",", "val", ",", "logger", ".", "Name", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n", "return", "fmter", ".", "Logf", "(", "w", ",", "params", ")", "\n", "}", "\n", "}" ]
// GetFormatter returns a formatter function for objects conforming to the // Formatter interface
[ "GetFormatter", "returns", "a", "formatter", "function", "for", "objects", "conforming", "to", "the", "Formatter", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/streamlog/streamlog.go#L194-L203
train
vitessio/vitess
go/mysql/mariadb_gtid.go
parseMariadbGTID
func parseMariadbGTID(s string) (GTID, error) { // Split into parts. parts := strings.Split(s, "-") if len(parts) != 3 { return nil, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid MariaDB GTID (%v): expecting Domain-Server-Sequence", s) } // Parse Domain ID. Domain, err := strconv.ParseUint(parts[0], 10, 32) if err != nil { return nil, vterrors.Wrapf(err, "invalid MariaDB GTID Domain ID (%v)", parts[0]) } // Parse Server ID. Server, err := strconv.ParseUint(parts[1], 10, 32) if err != nil { return nil, vterrors.Wrapf(err, "invalid MariaDB GTID Server ID (%v)", parts[1]) } // Parse Sequence number. Sequence, err := strconv.ParseUint(parts[2], 10, 64) if err != nil { return nil, vterrors.Wrapf(err, "invalid MariaDB GTID Sequence number (%v)", parts[2]) } return MariadbGTID{ Domain: uint32(Domain), Server: uint32(Server), Sequence: Sequence, }, nil }
go
func parseMariadbGTID(s string) (GTID, error) { // Split into parts. parts := strings.Split(s, "-") if len(parts) != 3 { return nil, vterrors.Errorf(vtrpc.Code_INTERNAL, "invalid MariaDB GTID (%v): expecting Domain-Server-Sequence", s) } // Parse Domain ID. Domain, err := strconv.ParseUint(parts[0], 10, 32) if err != nil { return nil, vterrors.Wrapf(err, "invalid MariaDB GTID Domain ID (%v)", parts[0]) } // Parse Server ID. Server, err := strconv.ParseUint(parts[1], 10, 32) if err != nil { return nil, vterrors.Wrapf(err, "invalid MariaDB GTID Server ID (%v)", parts[1]) } // Parse Sequence number. Sequence, err := strconv.ParseUint(parts[2], 10, 64) if err != nil { return nil, vterrors.Wrapf(err, "invalid MariaDB GTID Sequence number (%v)", parts[2]) } return MariadbGTID{ Domain: uint32(Domain), Server: uint32(Server), Sequence: Sequence, }, nil }
[ "func", "parseMariadbGTID", "(", "s", "string", ")", "(", "GTID", ",", "error", ")", "{", "// Split into parts.", "parts", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "!=", "3", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "s", ")", "\n", "}", "\n\n", "// Parse Domain ID.", "Domain", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "parts", "[", "0", "]", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "parts", "[", "0", "]", ")", "\n", "}", "\n\n", "// Parse Server ID.", "Server", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "parts", "[", "1", "]", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "parts", "[", "1", "]", ")", "\n", "}", "\n\n", "// Parse Sequence number.", "Sequence", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "parts", "[", "2", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "parts", "[", "2", "]", ")", "\n", "}", "\n\n", "return", "MariadbGTID", "{", "Domain", ":", "uint32", "(", "Domain", ")", ",", "Server", ":", "uint32", "(", "Server", ")", ",", "Sequence", ":", "Sequence", ",", "}", ",", "nil", "\n", "}" ]
// parseMariadbGTID is registered as a GTID parser.
[ "parseMariadbGTID", "is", "registered", "as", "a", "GTID", "parser", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mariadb_gtid.go#L31-L61
train
vitessio/vitess
go/mysql/mariadb_gtid.go
parseMariadbGTIDSet
func parseMariadbGTIDSet(s string) (GTIDSet, error) { gtidStrings := strings.Split(s, ",") gtidSet := make(MariadbGTIDSet, len(gtidStrings)) for i, gtidString := range gtidStrings { gtid, err := parseMariadbGTID(gtidString) if err != nil { return nil, err } gtidSet[i] = gtid.(MariadbGTID) } return gtidSet, nil }
go
func parseMariadbGTIDSet(s string) (GTIDSet, error) { gtidStrings := strings.Split(s, ",") gtidSet := make(MariadbGTIDSet, len(gtidStrings)) for i, gtidString := range gtidStrings { gtid, err := parseMariadbGTID(gtidString) if err != nil { return nil, err } gtidSet[i] = gtid.(MariadbGTID) } return gtidSet, nil }
[ "func", "parseMariadbGTIDSet", "(", "s", "string", ")", "(", "GTIDSet", ",", "error", ")", "{", "gtidStrings", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "gtidSet", ":=", "make", "(", "MariadbGTIDSet", ",", "len", "(", "gtidStrings", ")", ")", "\n", "for", "i", ",", "gtidString", ":=", "range", "gtidStrings", "{", "gtid", ",", "err", ":=", "parseMariadbGTID", "(", "gtidString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "gtidSet", "[", "i", "]", "=", "gtid", ".", "(", "MariadbGTID", ")", "\n", "}", "\n", "return", "gtidSet", ",", "nil", "\n", "}" ]
// parseMariadbGTIDSet is registered as a GTIDSet parser.
[ "parseMariadbGTIDSet", "is", "registered", "as", "a", "GTIDSet", "parser", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mariadb_gtid.go#L64-L75
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_executor.go
Prepare
func (txe *TxExecutor) Prepare(transactionID int64, dtid string) error { if !txe.te.twopcEnabled { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } defer tabletenv.QueryStats.Record("PREPARE", time.Now()) txe.logStats.TransactionID = transactionID conn, err := txe.te.txPool.Get(transactionID, "for prepare") if err != nil { return err } // If no queries were executed, we just rollback. if len(conn.Queries) == 0 { txe.te.txPool.LocalConclude(txe.ctx, conn) return nil } err = txe.te.preparedPool.Put(conn, dtid) if err != nil { txe.te.txPool.localRollback(txe.ctx, conn) return vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED, "prepare failed for transaction %d: %v", transactionID, err) } localConn, _, err := txe.te.txPool.LocalBegin(txe.ctx, &querypb.ExecuteOptions{}) if err != nil { return err } defer txe.te.txPool.LocalConclude(txe.ctx, localConn) err = txe.te.twoPC.SaveRedo(txe.ctx, localConn, dtid, conn.Queries) if err != nil { return err } _, err = txe.te.txPool.LocalCommit(txe.ctx, localConn, txe.messager) if err != nil { return err } return nil }
go
func (txe *TxExecutor) Prepare(transactionID int64, dtid string) error { if !txe.te.twopcEnabled { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } defer tabletenv.QueryStats.Record("PREPARE", time.Now()) txe.logStats.TransactionID = transactionID conn, err := txe.te.txPool.Get(transactionID, "for prepare") if err != nil { return err } // If no queries were executed, we just rollback. if len(conn.Queries) == 0 { txe.te.txPool.LocalConclude(txe.ctx, conn) return nil } err = txe.te.preparedPool.Put(conn, dtid) if err != nil { txe.te.txPool.localRollback(txe.ctx, conn) return vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED, "prepare failed for transaction %d: %v", transactionID, err) } localConn, _, err := txe.te.txPool.LocalBegin(txe.ctx, &querypb.ExecuteOptions{}) if err != nil { return err } defer txe.te.txPool.LocalConclude(txe.ctx, localConn) err = txe.te.twoPC.SaveRedo(txe.ctx, localConn, dtid, conn.Queries) if err != nil { return err } _, err = txe.te.txPool.LocalCommit(txe.ctx, localConn, txe.messager) if err != nil { return err } return nil }
[ "func", "(", "txe", "*", "TxExecutor", ")", "Prepare", "(", "transactionID", "int64", ",", "dtid", "string", ")", "error", "{", "if", "!", "txe", ".", "te", ".", "twopcEnabled", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "tabletenv", ".", "QueryStats", ".", "Record", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ")", "\n", "txe", ".", "logStats", ".", "TransactionID", "=", "transactionID", "\n\n", "conn", ",", "err", ":=", "txe", ".", "te", ".", "txPool", ".", "Get", "(", "transactionID", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// If no queries were executed, we just rollback.", "if", "len", "(", "conn", ".", "Queries", ")", "==", "0", "{", "txe", ".", "te", ".", "txPool", ".", "LocalConclude", "(", "txe", ".", "ctx", ",", "conn", ")", "\n", "return", "nil", "\n", "}", "\n\n", "err", "=", "txe", ".", "te", ".", "preparedPool", ".", "Put", "(", "conn", ",", "dtid", ")", "\n", "if", "err", "!=", "nil", "{", "txe", ".", "te", ".", "txPool", ".", "localRollback", "(", "txe", ".", "ctx", ",", "conn", ")", "\n", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_RESOURCE_EXHAUSTED", ",", "\"", "\"", ",", "transactionID", ",", "err", ")", "\n", "}", "\n\n", "localConn", ",", "_", ",", "err", ":=", "txe", ".", "te", ".", "txPool", ".", "LocalBegin", "(", "txe", ".", "ctx", ",", "&", "querypb", ".", "ExecuteOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "txe", ".", "te", ".", "txPool", ".", "LocalConclude", "(", "txe", ".", "ctx", ",", "localConn", ")", "\n\n", "err", "=", "txe", ".", "te", ".", "twoPC", ".", "SaveRedo", "(", "txe", ".", "ctx", ",", "localConn", ",", "dtid", ",", "conn", ".", "Queries", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "_", ",", "err", "=", "txe", ".", "te", ".", "txPool", ".", "LocalCommit", "(", "txe", ".", "ctx", ",", "localConn", ",", "txe", ".", "messager", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Prepare performs a prepare on a connection including the redo log work. // If there is any failure, an error is returned. No cleanup is performed. // A subsequent call to RollbackPrepared, which is required by the 2PC // protocol, will perform all the cleanup.
[ "Prepare", "performs", "a", "prepare", "on", "a", "connection", "including", "the", "redo", "log", "work", ".", "If", "there", "is", "any", "failure", "an", "error", "is", "returned", ".", "No", "cleanup", "is", "performed", ".", "A", "subsequent", "call", "to", "RollbackPrepared", "which", "is", "required", "by", "the", "2PC", "protocol", "will", "perform", "all", "the", "cleanup", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_executor.go#L47-L88
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_executor.go
CommitPrepared
func (txe *TxExecutor) CommitPrepared(dtid string) error { if !txe.te.twopcEnabled { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } defer tabletenv.QueryStats.Record("COMMIT_PREPARED", time.Now()) conn, err := txe.te.preparedPool.FetchForCommit(dtid) if err != nil { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "cannot commit dtid %s, state: %v", dtid, err) } if conn == nil { return nil } // We have to use a context that will never give up, // even if the original context expires. ctx := trace.CopySpan(context.Background(), txe.ctx) defer txe.te.txPool.LocalConclude(ctx, conn) err = txe.te.twoPC.DeleteRedo(ctx, conn, dtid) if err != nil { txe.markFailed(ctx, dtid) return err } _, err = txe.te.txPool.LocalCommit(ctx, conn, txe.messager) if err != nil { txe.markFailed(ctx, dtid) return err } txe.te.preparedPool.Forget(dtid) return nil }
go
func (txe *TxExecutor) CommitPrepared(dtid string) error { if !txe.te.twopcEnabled { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } defer tabletenv.QueryStats.Record("COMMIT_PREPARED", time.Now()) conn, err := txe.te.preparedPool.FetchForCommit(dtid) if err != nil { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "cannot commit dtid %s, state: %v", dtid, err) } if conn == nil { return nil } // We have to use a context that will never give up, // even if the original context expires. ctx := trace.CopySpan(context.Background(), txe.ctx) defer txe.te.txPool.LocalConclude(ctx, conn) err = txe.te.twoPC.DeleteRedo(ctx, conn, dtid) if err != nil { txe.markFailed(ctx, dtid) return err } _, err = txe.te.txPool.LocalCommit(ctx, conn, txe.messager) if err != nil { txe.markFailed(ctx, dtid) return err } txe.te.preparedPool.Forget(dtid) return nil }
[ "func", "(", "txe", "*", "TxExecutor", ")", "CommitPrepared", "(", "dtid", "string", ")", "error", "{", "if", "!", "txe", ".", "te", ".", "twopcEnabled", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "tabletenv", ".", "QueryStats", ".", "Record", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ")", "\n", "conn", ",", "err", ":=", "txe", ".", "te", ".", "preparedPool", ".", "FetchForCommit", "(", "dtid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "dtid", ",", "err", ")", "\n", "}", "\n", "if", "conn", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "// We have to use a context that will never give up,", "// even if the original context expires.", "ctx", ":=", "trace", ".", "CopySpan", "(", "context", ".", "Background", "(", ")", ",", "txe", ".", "ctx", ")", "\n", "defer", "txe", ".", "te", ".", "txPool", ".", "LocalConclude", "(", "ctx", ",", "conn", ")", "\n", "err", "=", "txe", ".", "te", ".", "twoPC", ".", "DeleteRedo", "(", "ctx", ",", "conn", ",", "dtid", ")", "\n", "if", "err", "!=", "nil", "{", "txe", ".", "markFailed", "(", "ctx", ",", "dtid", ")", "\n", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "txe", ".", "te", ".", "txPool", ".", "LocalCommit", "(", "ctx", ",", "conn", ",", "txe", ".", "messager", ")", "\n", "if", "err", "!=", "nil", "{", "txe", ".", "markFailed", "(", "ctx", ",", "dtid", ")", "\n", "return", "err", "\n", "}", "\n", "txe", ".", "te", ".", "preparedPool", ".", "Forget", "(", "dtid", ")", "\n", "return", "nil", "\n", "}" ]
// CommitPrepared commits a prepared transaction. If the operation // fails, an error counter is incremented and the transaction is // marked as failed in the redo log.
[ "CommitPrepared", "commits", "a", "prepared", "transaction", ".", "If", "the", "operation", "fails", "an", "error", "counter", "is", "incremented", "and", "the", "transaction", "is", "marked", "as", "failed", "in", "the", "redo", "log", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_executor.go#L93-L121
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_executor.go
markFailed
func (txe *TxExecutor) markFailed(ctx context.Context, dtid string) { tabletenv.InternalErrors.Add("TwopcCommit", 1) txe.te.preparedPool.SetFailed(dtid) conn, _, err := txe.te.txPool.LocalBegin(ctx, &querypb.ExecuteOptions{}) if err != nil { log.Errorf("markFailed: Begin failed for dtid %s: %v", dtid, err) return } defer txe.te.txPool.LocalConclude(ctx, conn) if err = txe.te.twoPC.UpdateRedo(ctx, conn, dtid, RedoStateFailed); err != nil { log.Errorf("markFailed: UpdateRedo failed for dtid %s: %v", dtid, err) return } if _, err = txe.te.txPool.LocalCommit(ctx, conn, txe.messager); err != nil { log.Errorf("markFailed: Commit failed for dtid %s: %v", dtid, err) } }
go
func (txe *TxExecutor) markFailed(ctx context.Context, dtid string) { tabletenv.InternalErrors.Add("TwopcCommit", 1) txe.te.preparedPool.SetFailed(dtid) conn, _, err := txe.te.txPool.LocalBegin(ctx, &querypb.ExecuteOptions{}) if err != nil { log.Errorf("markFailed: Begin failed for dtid %s: %v", dtid, err) return } defer txe.te.txPool.LocalConclude(ctx, conn) if err = txe.te.twoPC.UpdateRedo(ctx, conn, dtid, RedoStateFailed); err != nil { log.Errorf("markFailed: UpdateRedo failed for dtid %s: %v", dtid, err) return } if _, err = txe.te.txPool.LocalCommit(ctx, conn, txe.messager); err != nil { log.Errorf("markFailed: Commit failed for dtid %s: %v", dtid, err) } }
[ "func", "(", "txe", "*", "TxExecutor", ")", "markFailed", "(", "ctx", "context", ".", "Context", ",", "dtid", "string", ")", "{", "tabletenv", ".", "InternalErrors", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "txe", ".", "te", ".", "preparedPool", ".", "SetFailed", "(", "dtid", ")", "\n", "conn", ",", "_", ",", "err", ":=", "txe", ".", "te", ".", "txPool", ".", "LocalBegin", "(", "ctx", ",", "&", "querypb", ".", "ExecuteOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "txe", ".", "te", ".", "txPool", ".", "LocalConclude", "(", "ctx", ",", "conn", ")", "\n\n", "if", "err", "=", "txe", ".", "te", ".", "twoPC", ".", "UpdateRedo", "(", "ctx", ",", "conn", ",", "dtid", ",", "RedoStateFailed", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "if", "_", ",", "err", "=", "txe", ".", "te", ".", "txPool", ".", "LocalCommit", "(", "ctx", ",", "conn", ",", "txe", ".", "messager", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "dtid", ",", "err", ")", "\n", "}", "\n", "}" ]
// markFailed does the necessary work to mark a CommitPrepared // as failed. It marks the dtid as failed in the prepared pool, // increments the InternalErros counter, and also changes the // state of the transaction in the redo log as failed. If the // state change does not succeed, it just logs the event. // The function uses the passed in context that has no timeout // instead of TxExecutor's context.
[ "markFailed", "does", "the", "necessary", "work", "to", "mark", "a", "CommitPrepared", "as", "failed", ".", "It", "marks", "the", "dtid", "as", "failed", "in", "the", "prepared", "pool", "increments", "the", "InternalErros", "counter", "and", "also", "changes", "the", "state", "of", "the", "transaction", "in", "the", "redo", "log", "as", "failed", ".", "If", "the", "state", "change", "does", "not", "succeed", "it", "just", "logs", "the", "event", ".", "The", "function", "uses", "the", "passed", "in", "context", "that", "has", "no", "timeout", "instead", "of", "TxExecutor", "s", "context", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_executor.go#L130-L148
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_executor.go
RollbackPrepared
func (txe *TxExecutor) RollbackPrepared(dtid string, originalID int64) error { if !txe.te.twopcEnabled { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } defer tabletenv.QueryStats.Record("ROLLBACK_PREPARED", time.Now()) conn, _, err := txe.te.txPool.LocalBegin(txe.ctx, &querypb.ExecuteOptions{}) if err != nil { goto returnConn } defer txe.te.txPool.LocalConclude(txe.ctx, conn) err = txe.te.twoPC.DeleteRedo(txe.ctx, conn, dtid) if err != nil { goto returnConn } _, err = txe.te.txPool.LocalCommit(txe.ctx, conn, txe.messager) returnConn: if preparedConn := txe.te.preparedPool.FetchForRollback(dtid); preparedConn != nil { txe.te.txPool.LocalConclude(txe.ctx, preparedConn) } if originalID != 0 { txe.te.txPool.Rollback(txe.ctx, originalID) } return err }
go
func (txe *TxExecutor) RollbackPrepared(dtid string, originalID int64) error { if !txe.te.twopcEnabled { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } defer tabletenv.QueryStats.Record("ROLLBACK_PREPARED", time.Now()) conn, _, err := txe.te.txPool.LocalBegin(txe.ctx, &querypb.ExecuteOptions{}) if err != nil { goto returnConn } defer txe.te.txPool.LocalConclude(txe.ctx, conn) err = txe.te.twoPC.DeleteRedo(txe.ctx, conn, dtid) if err != nil { goto returnConn } _, err = txe.te.txPool.LocalCommit(txe.ctx, conn, txe.messager) returnConn: if preparedConn := txe.te.preparedPool.FetchForRollback(dtid); preparedConn != nil { txe.te.txPool.LocalConclude(txe.ctx, preparedConn) } if originalID != 0 { txe.te.txPool.Rollback(txe.ctx, originalID) } return err }
[ "func", "(", "txe", "*", "TxExecutor", ")", "RollbackPrepared", "(", "dtid", "string", ",", "originalID", "int64", ")", "error", "{", "if", "!", "txe", ".", "te", ".", "twopcEnabled", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "tabletenv", ".", "QueryStats", ".", "Record", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ")", "\n", "conn", ",", "_", ",", "err", ":=", "txe", ".", "te", ".", "txPool", ".", "LocalBegin", "(", "txe", ".", "ctx", ",", "&", "querypb", ".", "ExecuteOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "goto", "returnConn", "\n", "}", "\n", "defer", "txe", ".", "te", ".", "txPool", ".", "LocalConclude", "(", "txe", ".", "ctx", ",", "conn", ")", "\n\n", "err", "=", "txe", ".", "te", ".", "twoPC", ".", "DeleteRedo", "(", "txe", ".", "ctx", ",", "conn", ",", "dtid", ")", "\n", "if", "err", "!=", "nil", "{", "goto", "returnConn", "\n", "}", "\n\n", "_", ",", "err", "=", "txe", ".", "te", ".", "txPool", ".", "LocalCommit", "(", "txe", ".", "ctx", ",", "conn", ",", "txe", ".", "messager", ")", "\n\n", "returnConn", ":", "if", "preparedConn", ":=", "txe", ".", "te", ".", "preparedPool", ".", "FetchForRollback", "(", "dtid", ")", ";", "preparedConn", "!=", "nil", "{", "txe", ".", "te", ".", "txPool", ".", "LocalConclude", "(", "txe", ".", "ctx", ",", "preparedConn", ")", "\n", "}", "\n", "if", "originalID", "!=", "0", "{", "txe", ".", "te", ".", "txPool", ".", "Rollback", "(", "txe", ".", "ctx", ",", "originalID", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// RollbackPrepared rolls back a prepared transaction. This function handles // the case of an incomplete prepare. // // If the prepare completely failed, it will just rollback the original // transaction identified by originalID. // // If the connection was moved to the prepared pool, but redo log // creation failed, then it will rollback that transaction and // return the conn to the txPool. // // If prepare was fully successful, it will also delete the redo log. // If the redo log deletion fails, it returns an error indicating that // a retry is needed. // // In recovery mode, the original transaction id will not be available. // If so, it must be set to 0, and the function will not attempt that // step. If the original transaction is still alive, the transaction // killer will be the one to eventually roll it back.
[ "RollbackPrepared", "rolls", "back", "a", "prepared", "transaction", ".", "This", "function", "handles", "the", "case", "of", "an", "incomplete", "prepare", ".", "If", "the", "prepare", "completely", "failed", "it", "will", "just", "rollback", "the", "original", "transaction", "identified", "by", "originalID", ".", "If", "the", "connection", "was", "moved", "to", "the", "prepared", "pool", "but", "redo", "log", "creation", "failed", "then", "it", "will", "rollback", "that", "transaction", "and", "return", "the", "conn", "to", "the", "txPool", ".", "If", "prepare", "was", "fully", "successful", "it", "will", "also", "delete", "the", "redo", "log", ".", "If", "the", "redo", "log", "deletion", "fails", "it", "returns", "an", "error", "indicating", "that", "a", "retry", "is", "needed", ".", "In", "recovery", "mode", "the", "original", "transaction", "id", "will", "not", "be", "available", ".", "If", "so", "it", "must", "be", "set", "to", "0", "and", "the", "function", "will", "not", "attempt", "that", "step", ".", "If", "the", "original", "transaction", "is", "still", "alive", "the", "transaction", "killer", "will", "be", "the", "one", "to", "eventually", "roll", "it", "back", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_executor.go#L168-L195
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_executor.go
ReadTwopcInflight
func (txe *TxExecutor) ReadTwopcInflight() (distributed []*DistributedTx, prepared, failed []*PreparedTx, err error) { if !txe.te.twopcEnabled { return nil, nil, nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } prepared, failed, err = txe.te.twoPC.ReadAllRedo(txe.ctx) if err != nil { return nil, nil, nil, vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "Could not read redo: %v", err) } distributed, err = txe.te.twoPC.ReadAllTransactions(txe.ctx) if err != nil { return nil, nil, nil, vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "Could not read redo: %v", err) } return distributed, prepared, failed, nil }
go
func (txe *TxExecutor) ReadTwopcInflight() (distributed []*DistributedTx, prepared, failed []*PreparedTx, err error) { if !txe.te.twopcEnabled { return nil, nil, nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "2pc is not enabled") } prepared, failed, err = txe.te.twoPC.ReadAllRedo(txe.ctx) if err != nil { return nil, nil, nil, vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "Could not read redo: %v", err) } distributed, err = txe.te.twoPC.ReadAllTransactions(txe.ctx) if err != nil { return nil, nil, nil, vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "Could not read redo: %v", err) } return distributed, prepared, failed, nil }
[ "func", "(", "txe", "*", "TxExecutor", ")", "ReadTwopcInflight", "(", ")", "(", "distributed", "[", "]", "*", "DistributedTx", ",", "prepared", ",", "failed", "[", "]", "*", "PreparedTx", ",", "err", "error", ")", "{", "if", "!", "txe", ".", "te", ".", "twopcEnabled", "{", "return", "nil", ",", "nil", ",", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "prepared", ",", "failed", ",", "err", "=", "txe", ".", "te", ".", "twoPC", ".", "ReadAllRedo", "(", "txe", ".", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNKNOWN", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "distributed", ",", "err", "=", "txe", ".", "te", ".", "twoPC", ".", "ReadAllTransactions", "(", "txe", ".", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNKNOWN", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "distributed", ",", "prepared", ",", "failed", ",", "nil", "\n", "}" ]
// ReadTwopcInflight returns info about all in-flight 2pc transactions.
[ "ReadTwopcInflight", "returns", "info", "about", "all", "in", "-", "flight", "2pc", "transactions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_executor.go#L303-L316
train
vitessio/vitess
go/vt/vtgate/engine/update.go
MarshalJSON
func (upd *Update) MarshalJSON() ([]byte, error) { var tname, vindexName string if upd.Table != nil { tname = upd.Table.Name.String() } if upd.Vindex != nil { vindexName = upd.Vindex.String() } marshalUpdate := struct { Opcode UpdateOpcode Keyspace *vindexes.Keyspace `json:",omitempty"` Query string `json:",omitempty"` Vindex string `json:",omitempty"` Values []sqltypes.PlanValue `json:",omitempty"` ChangedVindexValues map[string][]sqltypes.PlanValue `json:",omitempty"` Table string `json:",omitempty"` OwnedVindexQuery string `json:",omitempty"` MultiShardAutocommit bool `json:",omitempty"` QueryTimeout int `json:",omitempty"` }{ Opcode: upd.Opcode, Keyspace: upd.Keyspace, Query: upd.Query, Vindex: vindexName, Values: upd.Values, ChangedVindexValues: upd.ChangedVindexValues, Table: tname, OwnedVindexQuery: upd.OwnedVindexQuery, MultiShardAutocommit: upd.MultiShardAutocommit, QueryTimeout: upd.QueryTimeout, } return jsonutil.MarshalNoEscape(marshalUpdate) }
go
func (upd *Update) MarshalJSON() ([]byte, error) { var tname, vindexName string if upd.Table != nil { tname = upd.Table.Name.String() } if upd.Vindex != nil { vindexName = upd.Vindex.String() } marshalUpdate := struct { Opcode UpdateOpcode Keyspace *vindexes.Keyspace `json:",omitempty"` Query string `json:",omitempty"` Vindex string `json:",omitempty"` Values []sqltypes.PlanValue `json:",omitempty"` ChangedVindexValues map[string][]sqltypes.PlanValue `json:",omitempty"` Table string `json:",omitempty"` OwnedVindexQuery string `json:",omitempty"` MultiShardAutocommit bool `json:",omitempty"` QueryTimeout int `json:",omitempty"` }{ Opcode: upd.Opcode, Keyspace: upd.Keyspace, Query: upd.Query, Vindex: vindexName, Values: upd.Values, ChangedVindexValues: upd.ChangedVindexValues, Table: tname, OwnedVindexQuery: upd.OwnedVindexQuery, MultiShardAutocommit: upd.MultiShardAutocommit, QueryTimeout: upd.QueryTimeout, } return jsonutil.MarshalNoEscape(marshalUpdate) }
[ "func", "(", "upd", "*", "Update", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "tname", ",", "vindexName", "string", "\n", "if", "upd", ".", "Table", "!=", "nil", "{", "tname", "=", "upd", ".", "Table", ".", "Name", ".", "String", "(", ")", "\n", "}", "\n", "if", "upd", ".", "Vindex", "!=", "nil", "{", "vindexName", "=", "upd", ".", "Vindex", ".", "String", "(", ")", "\n", "}", "\n", "marshalUpdate", ":=", "struct", "{", "Opcode", "UpdateOpcode", "\n", "Keyspace", "*", "vindexes", ".", "Keyspace", "`json:\",omitempty\"`", "\n", "Query", "string", "`json:\",omitempty\"`", "\n", "Vindex", "string", "`json:\",omitempty\"`", "\n", "Values", "[", "]", "sqltypes", ".", "PlanValue", "`json:\",omitempty\"`", "\n", "ChangedVindexValues", "map", "[", "string", "]", "[", "]", "sqltypes", ".", "PlanValue", "`json:\",omitempty\"`", "\n", "Table", "string", "`json:\",omitempty\"`", "\n", "OwnedVindexQuery", "string", "`json:\",omitempty\"`", "\n", "MultiShardAutocommit", "bool", "`json:\",omitempty\"`", "\n", "QueryTimeout", "int", "`json:\",omitempty\"`", "\n", "}", "{", "Opcode", ":", "upd", ".", "Opcode", ",", "Keyspace", ":", "upd", ".", "Keyspace", ",", "Query", ":", "upd", ".", "Query", ",", "Vindex", ":", "vindexName", ",", "Values", ":", "upd", ".", "Values", ",", "ChangedVindexValues", ":", "upd", ".", "ChangedVindexValues", ",", "Table", ":", "tname", ",", "OwnedVindexQuery", ":", "upd", ".", "OwnedVindexQuery", ",", "MultiShardAutocommit", ":", "upd", ".", "MultiShardAutocommit", ",", "QueryTimeout", ":", "upd", ".", "QueryTimeout", ",", "}", "\n", "return", "jsonutil", ".", "MarshalNoEscape", "(", "marshalUpdate", ")", "\n", "}" ]
// MarshalJSON serializes the Update into a JSON representation. // It's used for testing and diagnostics.
[ "MarshalJSON", "serializes", "the", "Update", "into", "a", "JSON", "representation", ".", "It", "s", "used", "for", "testing", "and", "diagnostics", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/update.go#L77-L109
train
vitessio/vitess
go/vt/mysqlctl/mysqlctlclient/interface.go
New
func New(network, addr string) (MysqlctlClient, error) { factory, ok := factories[*protocol] if !ok { return nil, fmt.Errorf("unknown mysqlctl client protocol: %v", *protocol) } return factory(network, addr) }
go
func New(network, addr string) (MysqlctlClient, error) { factory, ok := factories[*protocol] if !ok { return nil, fmt.Errorf("unknown mysqlctl client protocol: %v", *protocol) } return factory(network, addr) }
[ "func", "New", "(", "network", ",", "addr", "string", ")", "(", "MysqlctlClient", ",", "error", ")", "{", "factory", ",", "ok", ":=", "factories", "[", "*", "protocol", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "*", "protocol", ")", "\n", "}", "\n", "return", "factory", "(", "network", ",", "addr", ")", "\n", "}" ]
// New creates a client implementation as specified by a flag.
[ "New", "creates", "a", "client", "implementation", "as", "specified", "by", "a", "flag", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/mysqlctlclient/interface.go#L66-L72
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
NewStreamHealthQueryService
func NewStreamHealthQueryService(target querypb.Target) *StreamHealthQueryService { return &StreamHealthQueryService{ QueryService: ErrorQueryService, healthResponses: make(chan *querypb.StreamHealthResponse, 1000), target: target, } }
go
func NewStreamHealthQueryService(target querypb.Target) *StreamHealthQueryService { return &StreamHealthQueryService{ QueryService: ErrorQueryService, healthResponses: make(chan *querypb.StreamHealthResponse, 1000), target: target, } }
[ "func", "NewStreamHealthQueryService", "(", "target", "querypb", ".", "Target", ")", "*", "StreamHealthQueryService", "{", "return", "&", "StreamHealthQueryService", "{", "QueryService", ":", "ErrorQueryService", ",", "healthResponses", ":", "make", "(", "chan", "*", "querypb", ".", "StreamHealthResponse", ",", "1000", ")", ",", "target", ":", "target", ",", "}", "\n", "}" ]
// NewStreamHealthQueryService creates a new fake query service for the target.
[ "NewStreamHealthQueryService", "creates", "a", "new", "fake", "query", "service", "for", "the", "target", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L50-L56
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
Begin
func (q *StreamHealthQueryService) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (int64, error) { return 0, nil }
go
func (q *StreamHealthQueryService) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (int64, error) { return 0, nil }
[ "func", "(", "q", "*", "StreamHealthQueryService", ")", "Begin", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "int64", ",", "error", ")", "{", "return", "0", ",", "nil", "\n", "}" ]
// Begin implemented as a no op
[ "Begin", "implemented", "as", "a", "no", "op" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L59-L61
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
Execute
func (q *StreamHealthQueryService) Execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID int64, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { return &sqltypes.Result{}, nil }
go
func (q *StreamHealthQueryService) Execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID int64, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { return &sqltypes.Result{}, nil }
[ "func", "(", "q", "*", "StreamHealthQueryService", ")", "Execute", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "transactionID", "int64", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "return", "&", "sqltypes", ".", "Result", "{", "}", ",", "nil", "\n", "}" ]
// Execute implemented as a no op
[ "Execute", "implemented", "as", "a", "no", "op" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L64-L66
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
AddDefaultHealthResponse
func (q *StreamHealthQueryService) AddDefaultHealthResponse() { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: true, RealtimeStats: &querypb.RealtimeStats{ SecondsBehindMaster: DefaultSecondsBehindMaster, }, } }
go
func (q *StreamHealthQueryService) AddDefaultHealthResponse() { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: true, RealtimeStats: &querypb.RealtimeStats{ SecondsBehindMaster: DefaultSecondsBehindMaster, }, } }
[ "func", "(", "q", "*", "StreamHealthQueryService", ")", "AddDefaultHealthResponse", "(", ")", "{", "q", ".", "healthResponses", "<-", "&", "querypb", ".", "StreamHealthResponse", "{", "Target", ":", "proto", ".", "Clone", "(", "&", "q", ".", "target", ")", ".", "(", "*", "querypb", ".", "Target", ")", ",", "Serving", ":", "true", ",", "RealtimeStats", ":", "&", "querypb", ".", "RealtimeStats", "{", "SecondsBehindMaster", ":", "DefaultSecondsBehindMaster", ",", "}", ",", "}", "\n", "}" ]
// AddDefaultHealthResponse adds a faked health response to the buffer channel. // The response will have default values typical for a healthy tablet.
[ "AddDefaultHealthResponse", "adds", "a", "faked", "health", "response", "to", "the", "buffer", "channel", ".", "The", "response", "will", "have", "default", "values", "typical", "for", "a", "healthy", "tablet", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L80-L88
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
AddHealthResponseWithQPS
func (q *StreamHealthQueryService) AddHealthResponseWithQPS(qps float64) { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: true, RealtimeStats: &querypb.RealtimeStats{ Qps: qps, SecondsBehindMaster: DefaultSecondsBehindMaster, }, } }
go
func (q *StreamHealthQueryService) AddHealthResponseWithQPS(qps float64) { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: true, RealtimeStats: &querypb.RealtimeStats{ Qps: qps, SecondsBehindMaster: DefaultSecondsBehindMaster, }, } }
[ "func", "(", "q", "*", "StreamHealthQueryService", ")", "AddHealthResponseWithQPS", "(", "qps", "float64", ")", "{", "q", ".", "healthResponses", "<-", "&", "querypb", ".", "StreamHealthResponse", "{", "Target", ":", "proto", ".", "Clone", "(", "&", "q", ".", "target", ")", ".", "(", "*", "querypb", ".", "Target", ")", ",", "Serving", ":", "true", ",", "RealtimeStats", ":", "&", "querypb", ".", "RealtimeStats", "{", "Qps", ":", "qps", ",", "SecondsBehindMaster", ":", "DefaultSecondsBehindMaster", ",", "}", ",", "}", "\n", "}" ]
// AddHealthResponseWithQPS adds a faked health response to the buffer channel. // Only "qps" is different in this message.
[ "AddHealthResponseWithQPS", "adds", "a", "faked", "health", "response", "to", "the", "buffer", "channel", ".", "Only", "qps", "is", "different", "in", "this", "message", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L92-L101
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
AddHealthResponseWithSecondsBehindMaster
func (q *StreamHealthQueryService) AddHealthResponseWithSecondsBehindMaster(replicationLag uint32) { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: true, RealtimeStats: &querypb.RealtimeStats{ SecondsBehindMaster: replicationLag, }, } }
go
func (q *StreamHealthQueryService) AddHealthResponseWithSecondsBehindMaster(replicationLag uint32) { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: true, RealtimeStats: &querypb.RealtimeStats{ SecondsBehindMaster: replicationLag, }, } }
[ "func", "(", "q", "*", "StreamHealthQueryService", ")", "AddHealthResponseWithSecondsBehindMaster", "(", "replicationLag", "uint32", ")", "{", "q", ".", "healthResponses", "<-", "&", "querypb", ".", "StreamHealthResponse", "{", "Target", ":", "proto", ".", "Clone", "(", "&", "q", ".", "target", ")", ".", "(", "*", "querypb", ".", "Target", ")", ",", "Serving", ":", "true", ",", "RealtimeStats", ":", "&", "querypb", ".", "RealtimeStats", "{", "SecondsBehindMaster", ":", "replicationLag", ",", "}", ",", "}", "\n", "}" ]
// AddHealthResponseWithSecondsBehindMaster adds a faked health response to the // buffer channel. Only "seconds_behind_master" is different in this message.
[ "AddHealthResponseWithSecondsBehindMaster", "adds", "a", "faked", "health", "response", "to", "the", "buffer", "channel", ".", "Only", "seconds_behind_master", "is", "different", "in", "this", "message", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L105-L113
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
AddHealthResponseWithNotServing
func (q *StreamHealthQueryService) AddHealthResponseWithNotServing() { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: false, RealtimeStats: &querypb.RealtimeStats{ SecondsBehindMaster: DefaultSecondsBehindMaster, }, } }
go
func (q *StreamHealthQueryService) AddHealthResponseWithNotServing() { q.healthResponses <- &querypb.StreamHealthResponse{ Target: proto.Clone(&q.target).(*querypb.Target), Serving: false, RealtimeStats: &querypb.RealtimeStats{ SecondsBehindMaster: DefaultSecondsBehindMaster, }, } }
[ "func", "(", "q", "*", "StreamHealthQueryService", ")", "AddHealthResponseWithNotServing", "(", ")", "{", "q", ".", "healthResponses", "<-", "&", "querypb", ".", "StreamHealthResponse", "{", "Target", ":", "proto", ".", "Clone", "(", "&", "q", ".", "target", ")", ".", "(", "*", "querypb", ".", "Target", ")", ",", "Serving", ":", "false", ",", "RealtimeStats", ":", "&", "querypb", ".", "RealtimeStats", "{", "SecondsBehindMaster", ":", "DefaultSecondsBehindMaster", ",", "}", ",", "}", "\n", "}" ]
// AddHealthResponseWithNotServing adds a faked health response to the // buffer channel. Only "Serving" is different in this message.
[ "AddHealthResponseWithNotServing", "adds", "a", "faked", "health", "response", "to", "the", "buffer", "channel", ".", "Only", "Serving", "is", "different", "in", "this", "message", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L117-L125
train
vitessio/vitess
go/vt/vttablet/queryservice/fakes/stream_health_query_service.go
UpdateType
func (q *StreamHealthQueryService) UpdateType(tabletType topodatapb.TabletType) { q.target.TabletType = tabletType }
go
func (q *StreamHealthQueryService) UpdateType(tabletType topodatapb.TabletType) { q.target.TabletType = tabletType }
[ "func", "(", "q", "*", "StreamHealthQueryService", ")", "UpdateType", "(", "tabletType", "topodatapb", ".", "TabletType", ")", "{", "q", ".", "target", ".", "TabletType", "=", "tabletType", "\n", "}" ]
// UpdateType changes the type of the query service. // Only newly sent health messages will use the new type.
[ "UpdateType", "changes", "the", "type", "of", "the", "query", "service", ".", "Only", "newly", "sent", "health", "messages", "will", "use", "the", "new", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/fakes/stream_health_query_service.go#L129-L131
train
vitessio/vitess
go/vt/topo/topoproto/shard.go
SourceShardString
func SourceShardString(source *topodatapb.Shard_SourceShard) string { return fmt.Sprintf("SourceShard(%v,%v/%v)", source.Uid, source.Keyspace, source.Shard) }
go
func SourceShardString(source *topodatapb.Shard_SourceShard) string { return fmt.Sprintf("SourceShard(%v,%v/%v)", source.Uid, source.Keyspace, source.Shard) }
[ "func", "SourceShardString", "(", "source", "*", "topodatapb", ".", "Shard_SourceShard", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "source", ".", "Uid", ",", "source", ".", "Keyspace", ",", "source", ".", "Shard", ")", "\n", "}" ]
// SourceShardString returns a printable view of a SourceShard.
[ "SourceShardString", "returns", "a", "printable", "view", "of", "a", "SourceShard", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/shard.go#L46-L48
train
vitessio/vitess
go/vt/topo/topoproto/shard.go
SourceShardAsHTML
func SourceShardAsHTML(source *topodatapb.Shard_SourceShard) template.HTML { result := fmt.Sprintf("<b>Uid</b>: %v</br>\n<b>Source</b>: %v/%v</br>\n", source.Uid, source.Keyspace, source.Shard) if key.KeyRangeIsPartial(source.KeyRange) { result += fmt.Sprintf("<b>KeyRange</b>: %v-%v</br>\n", hex.EncodeToString(source.KeyRange.Start), hex.EncodeToString(source.KeyRange.End)) } if len(source.Tables) > 0 { result += fmt.Sprintf("<b>Tables</b>: %v</br>\n", strings.Join(source.Tables, " ")) } return template.HTML(result) }
go
func SourceShardAsHTML(source *topodatapb.Shard_SourceShard) template.HTML { result := fmt.Sprintf("<b>Uid</b>: %v</br>\n<b>Source</b>: %v/%v</br>\n", source.Uid, source.Keyspace, source.Shard) if key.KeyRangeIsPartial(source.KeyRange) { result += fmt.Sprintf("<b>KeyRange</b>: %v-%v</br>\n", hex.EncodeToString(source.KeyRange.Start), hex.EncodeToString(source.KeyRange.End)) } if len(source.Tables) > 0 { result += fmt.Sprintf("<b>Tables</b>: %v</br>\n", strings.Join(source.Tables, " ")) } return template.HTML(result) }
[ "func", "SourceShardAsHTML", "(", "source", "*", "topodatapb", ".", "Shard_SourceShard", ")", "template", ".", "HTML", "{", "result", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "source", ".", "Uid", ",", "source", ".", "Keyspace", ",", "source", ".", "Shard", ")", "\n", "if", "key", ".", "KeyRangeIsPartial", "(", "source", ".", "KeyRange", ")", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "hex", ".", "EncodeToString", "(", "source", ".", "KeyRange", ".", "Start", ")", ",", "hex", ".", "EncodeToString", "(", "source", ".", "KeyRange", ".", "End", ")", ")", "\n", "}", "\n", "if", "len", "(", "source", ".", "Tables", ")", ">", "0", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "strings", ".", "Join", "(", "source", ".", "Tables", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "template", ".", "HTML", "(", "result", ")", "\n", "}" ]
// SourceShardAsHTML returns a HTML version of the object.
[ "SourceShardAsHTML", "returns", "a", "HTML", "version", "of", "the", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/shard.go#L51-L63
train
vitessio/vitess
go/vt/worker/chunk.go
String
func (c chunk) String() string { // Pad the chunk number such that all log messages align nicely. digits := digits(c.total) return fmt.Sprintf("%*d/%d", digits, c.number, c.total) }
go
func (c chunk) String() string { // Pad the chunk number such that all log messages align nicely. digits := digits(c.total) return fmt.Sprintf("%*d/%d", digits, c.number, c.total) }
[ "func", "(", "c", "chunk", ")", "String", "(", ")", "string", "{", "// Pad the chunk number such that all log messages align nicely.", "digits", ":=", "digits", "(", "c", ".", "total", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "digits", ",", "c", ".", "number", ",", "c", ".", "total", ")", "\n", "}" ]
// String returns a human-readable presentation of the chunk range.
[ "String", "returns", "a", "human", "-", "readable", "presentation", "of", "the", "chunk", "range", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/chunk.go#L56-L60
train
vitessio/vitess
go/vt/vttablet/tmclient/rpc_client_api.go
NewTabletManagerClient
func NewTabletManagerClient() TabletManagerClient { f, ok := tabletManagerClientFactories[*TabletManagerProtocol] if !ok { log.Exitf("No TabletManagerProtocol registered with name %s", *TabletManagerProtocol) } return f() }
go
func NewTabletManagerClient() TabletManagerClient { f, ok := tabletManagerClientFactories[*TabletManagerProtocol] if !ok { log.Exitf("No TabletManagerProtocol registered with name %s", *TabletManagerProtocol) } return f() }
[ "func", "NewTabletManagerClient", "(", ")", "TabletManagerClient", "{", "f", ",", "ok", ":=", "tabletManagerClientFactories", "[", "*", "TabletManagerProtocol", "]", "\n", "if", "!", "ok", "{", "log", ".", "Exitf", "(", "\"", "\"", ",", "*", "TabletManagerProtocol", ")", "\n", "}", "\n\n", "return", "f", "(", ")", "\n", "}" ]
// NewTabletManagerClient creates a new TabletManagerClient. Should be // called after flags are parsed.
[ "NewTabletManagerClient", "creates", "a", "new", "TabletManagerClient", ".", "Should", "be", "called", "after", "flags", "are", "parsed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tmclient/rpc_client_api.go#L235-L242
train
vitessio/vitess
go/vt/sqlparser/comments.go
leadingCommentEnd
func leadingCommentEnd(text string) (end int) { hasComment := false pos := 0 for pos < len(text) { // Eat up any whitespace. Trailing whitespace will be considered part of // the leading comments. nextVisibleOffset := strings.IndexFunc(text[pos:], isNonSpace) if nextVisibleOffset < 0 { break } pos += nextVisibleOffset remainingText := text[pos:] // Found visible characters. Look for '/*' at the beginning // and '*/' somewhere after that. if len(remainingText) < 4 || remainingText[:2] != "/*" { break } commentLength := 4 + strings.Index(remainingText[2:], "*/") if commentLength < 4 { // Missing end comment :/ break } hasComment = true pos += commentLength } if hasComment { return pos } return 0 }
go
func leadingCommentEnd(text string) (end int) { hasComment := false pos := 0 for pos < len(text) { // Eat up any whitespace. Trailing whitespace will be considered part of // the leading comments. nextVisibleOffset := strings.IndexFunc(text[pos:], isNonSpace) if nextVisibleOffset < 0 { break } pos += nextVisibleOffset remainingText := text[pos:] // Found visible characters. Look for '/*' at the beginning // and '*/' somewhere after that. if len(remainingText) < 4 || remainingText[:2] != "/*" { break } commentLength := 4 + strings.Index(remainingText[2:], "*/") if commentLength < 4 { // Missing end comment :/ break } hasComment = true pos += commentLength } if hasComment { return pos } return 0 }
[ "func", "leadingCommentEnd", "(", "text", "string", ")", "(", "end", "int", ")", "{", "hasComment", ":=", "false", "\n", "pos", ":=", "0", "\n", "for", "pos", "<", "len", "(", "text", ")", "{", "// Eat up any whitespace. Trailing whitespace will be considered part of", "// the leading comments.", "nextVisibleOffset", ":=", "strings", ".", "IndexFunc", "(", "text", "[", "pos", ":", "]", ",", "isNonSpace", ")", "\n", "if", "nextVisibleOffset", "<", "0", "{", "break", "\n", "}", "\n", "pos", "+=", "nextVisibleOffset", "\n", "remainingText", ":=", "text", "[", "pos", ":", "]", "\n\n", "// Found visible characters. Look for '/*' at the beginning", "// and '*/' somewhere after that.", "if", "len", "(", "remainingText", ")", "<", "4", "||", "remainingText", "[", ":", "2", "]", "!=", "\"", "\"", "{", "break", "\n", "}", "\n", "commentLength", ":=", "4", "+", "strings", ".", "Index", "(", "remainingText", "[", "2", ":", "]", ",", "\"", "\"", ")", "\n", "if", "commentLength", "<", "4", "{", "// Missing end comment :/", "break", "\n", "}", "\n\n", "hasComment", "=", "true", "\n", "pos", "+=", "commentLength", "\n", "}", "\n\n", "if", "hasComment", "{", "return", "pos", "\n", "}", "\n", "return", "0", "\n", "}" ]
// leadingCommentEnd returns the first index after all leading comments, or // 0 if there are no leading comments.
[ "leadingCommentEnd", "returns", "the", "first", "index", "after", "all", "leading", "comments", "or", "0", "if", "there", "are", "no", "leading", "comments", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/comments.go#L43-L75
train
vitessio/vitess
go/vt/sqlparser/comments.go
trailingCommentStart
func trailingCommentStart(text string) (start int) { hasComment := false reducedLen := len(text) for reducedLen > 0 { // Eat up any whitespace. Leading whitespace will be considered part of // the trailing comments. nextReducedLen := strings.LastIndexFunc(text[:reducedLen], isNonSpace) + 1 if nextReducedLen == 0 { break } reducedLen = nextReducedLen if reducedLen < 4 || text[reducedLen-2:reducedLen] != "*/" { break } // Find the beginning of the comment startCommentPos := strings.LastIndex(text[:reducedLen-2], "/*") if startCommentPos < 0 { // Badly formatted sql :/ break } hasComment = true reducedLen = startCommentPos } if hasComment { return reducedLen } return len(text) }
go
func trailingCommentStart(text string) (start int) { hasComment := false reducedLen := len(text) for reducedLen > 0 { // Eat up any whitespace. Leading whitespace will be considered part of // the trailing comments. nextReducedLen := strings.LastIndexFunc(text[:reducedLen], isNonSpace) + 1 if nextReducedLen == 0 { break } reducedLen = nextReducedLen if reducedLen < 4 || text[reducedLen-2:reducedLen] != "*/" { break } // Find the beginning of the comment startCommentPos := strings.LastIndex(text[:reducedLen-2], "/*") if startCommentPos < 0 { // Badly formatted sql :/ break } hasComment = true reducedLen = startCommentPos } if hasComment { return reducedLen } return len(text) }
[ "func", "trailingCommentStart", "(", "text", "string", ")", "(", "start", "int", ")", "{", "hasComment", ":=", "false", "\n", "reducedLen", ":=", "len", "(", "text", ")", "\n", "for", "reducedLen", ">", "0", "{", "// Eat up any whitespace. Leading whitespace will be considered part of", "// the trailing comments.", "nextReducedLen", ":=", "strings", ".", "LastIndexFunc", "(", "text", "[", ":", "reducedLen", "]", ",", "isNonSpace", ")", "+", "1", "\n", "if", "nextReducedLen", "==", "0", "{", "break", "\n", "}", "\n", "reducedLen", "=", "nextReducedLen", "\n", "if", "reducedLen", "<", "4", "||", "text", "[", "reducedLen", "-", "2", ":", "reducedLen", "]", "!=", "\"", "\"", "{", "break", "\n", "}", "\n\n", "// Find the beginning of the comment", "startCommentPos", ":=", "strings", ".", "LastIndex", "(", "text", "[", ":", "reducedLen", "-", "2", "]", ",", "\"", "\"", ")", "\n", "if", "startCommentPos", "<", "0", "{", "// Badly formatted sql :/", "break", "\n", "}", "\n\n", "hasComment", "=", "true", "\n", "reducedLen", "=", "startCommentPos", "\n", "}", "\n\n", "if", "hasComment", "{", "return", "reducedLen", "\n", "}", "\n", "return", "len", "(", "text", ")", "\n", "}" ]
// trailingCommentStart returns the first index of trailing comments. // If there are no trailing comments, returns the length of the input string.
[ "trailingCommentStart", "returns", "the", "first", "index", "of", "trailing", "comments", ".", "If", "there", "are", "no", "trailing", "comments", "returns", "the", "length", "of", "the", "input", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/comments.go#L79-L109
train
vitessio/vitess
go/vt/sqlparser/comments.go
StripLeadingComments
func StripLeadingComments(sql string) string { sql = strings.TrimFunc(sql, unicode.IsSpace) for hasCommentPrefix(sql) { switch sql[0] { case '/': // Multi line comment index := strings.Index(sql, "*/") if index <= 1 { return sql } // don't strip /*! ... */ or /*!50700 ... */ if len(sql) > 2 && sql[2] == '!' { return sql } sql = sql[index+2:] case '-': // Single line comment index := strings.Index(sql, "\n") if index == -1 { return "" } sql = sql[index+1:] } sql = strings.TrimFunc(sql, unicode.IsSpace) } return sql }
go
func StripLeadingComments(sql string) string { sql = strings.TrimFunc(sql, unicode.IsSpace) for hasCommentPrefix(sql) { switch sql[0] { case '/': // Multi line comment index := strings.Index(sql, "*/") if index <= 1 { return sql } // don't strip /*! ... */ or /*!50700 ... */ if len(sql) > 2 && sql[2] == '!' { return sql } sql = sql[index+2:] case '-': // Single line comment index := strings.Index(sql, "\n") if index == -1 { return "" } sql = sql[index+1:] } sql = strings.TrimFunc(sql, unicode.IsSpace) } return sql }
[ "func", "StripLeadingComments", "(", "sql", "string", ")", "string", "{", "sql", "=", "strings", ".", "TrimFunc", "(", "sql", ",", "unicode", ".", "IsSpace", ")", "\n\n", "for", "hasCommentPrefix", "(", "sql", ")", "{", "switch", "sql", "[", "0", "]", "{", "case", "'/'", ":", "// Multi line comment", "index", ":=", "strings", ".", "Index", "(", "sql", ",", "\"", "\"", ")", "\n", "if", "index", "<=", "1", "{", "return", "sql", "\n", "}", "\n", "// don't strip /*! ... */ or /*!50700 ... */", "if", "len", "(", "sql", ")", ">", "2", "&&", "sql", "[", "2", "]", "==", "'!'", "{", "return", "sql", "\n", "}", "\n", "sql", "=", "sql", "[", "index", "+", "2", ":", "]", "\n", "case", "'-'", ":", "// Single line comment", "index", ":=", "strings", ".", "Index", "(", "sql", ",", "\"", "\\n", "\"", ")", "\n", "if", "index", "==", "-", "1", "{", "return", "\"", "\"", "\n", "}", "\n", "sql", "=", "sql", "[", "index", "+", "1", ":", "]", "\n", "}", "\n\n", "sql", "=", "strings", ".", "TrimFunc", "(", "sql", ",", "unicode", ".", "IsSpace", ")", "\n", "}", "\n\n", "return", "sql", "\n", "}" ]
// StripLeadingComments trims the SQL string and removes any leading comments
[ "StripLeadingComments", "trims", "the", "SQL", "string", "and", "removes", "any", "leading", "comments" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/comments.go#L130-L159
train
vitessio/vitess
go/vt/sqlparser/comments.go
StripComments
func StripComments(sql string) string { sql = StripLeadingComments(sql) // handle -- or /* ... */ at the beginning for { start := strings.Index(sql, "/*") if start == -1 { break } end := strings.Index(sql, "*/") if end <= 1 { break } sql = sql[:start] + sql[end+2:] } sql = strings.TrimFunc(sql, unicode.IsSpace) return sql }
go
func StripComments(sql string) string { sql = StripLeadingComments(sql) // handle -- or /* ... */ at the beginning for { start := strings.Index(sql, "/*") if start == -1 { break } end := strings.Index(sql, "*/") if end <= 1 { break } sql = sql[:start] + sql[end+2:] } sql = strings.TrimFunc(sql, unicode.IsSpace) return sql }
[ "func", "StripComments", "(", "sql", "string", ")", "string", "{", "sql", "=", "StripLeadingComments", "(", "sql", ")", "// handle -- or /* ... */ at the beginning", "\n\n", "for", "{", "start", ":=", "strings", ".", "Index", "(", "sql", ",", "\"", "\"", ")", "\n", "if", "start", "==", "-", "1", "{", "break", "\n", "}", "\n", "end", ":=", "strings", ".", "Index", "(", "sql", ",", "\"", "\"", ")", "\n", "if", "end", "<=", "1", "{", "break", "\n", "}", "\n", "sql", "=", "sql", "[", ":", "start", "]", "+", "sql", "[", "end", "+", "2", ":", "]", "\n", "}", "\n\n", "sql", "=", "strings", ".", "TrimFunc", "(", "sql", ",", "unicode", ".", "IsSpace", ")", "\n\n", "return", "sql", "\n", "}" ]
// StripComments removes all comments from the string regardless // of where they occur
[ "StripComments", "removes", "all", "comments", "from", "the", "string", "regardless", "of", "where", "they", "occur" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/comments.go#L167-L185
train
vitessio/vitess
go/vt/sqlparser/comments.go
SkipQueryPlanCacheDirective
func SkipQueryPlanCacheDirective(stmt Statement) bool { switch stmt := stmt.(type) { case *Select: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } case *Insert: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } case *Update: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } case *Delete: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } default: return false } return false }
go
func SkipQueryPlanCacheDirective(stmt Statement) bool { switch stmt := stmt.(type) { case *Select: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } case *Insert: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } case *Update: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } case *Delete: directives := ExtractCommentDirectives(stmt.Comments) if directives.IsSet(DirectiveSkipQueryPlanCache) { return true } default: return false } return false }
[ "func", "SkipQueryPlanCacheDirective", "(", "stmt", "Statement", ")", "bool", "{", "switch", "stmt", ":=", "stmt", ".", "(", "type", ")", "{", "case", "*", "Select", ":", "directives", ":=", "ExtractCommentDirectives", "(", "stmt", ".", "Comments", ")", "\n", "if", "directives", ".", "IsSet", "(", "DirectiveSkipQueryPlanCache", ")", "{", "return", "true", "\n", "}", "\n", "case", "*", "Insert", ":", "directives", ":=", "ExtractCommentDirectives", "(", "stmt", ".", "Comments", ")", "\n", "if", "directives", ".", "IsSet", "(", "DirectiveSkipQueryPlanCache", ")", "{", "return", "true", "\n", "}", "\n", "case", "*", "Update", ":", "directives", ":=", "ExtractCommentDirectives", "(", "stmt", ".", "Comments", ")", "\n", "if", "directives", ".", "IsSet", "(", "DirectiveSkipQueryPlanCache", ")", "{", "return", "true", "\n", "}", "\n", "case", "*", "Delete", ":", "directives", ":=", "ExtractCommentDirectives", "(", "stmt", ".", "Comments", ")", "\n", "if", "directives", ".", "IsSet", "(", "DirectiveSkipQueryPlanCache", ")", "{", "return", "true", "\n", "}", "\n", "default", ":", "return", "false", "\n", "}", "\n", "return", "false", "\n", "}" ]
// SkipQueryPlanCacheDirective returns true if skip query plan cache directive is set to true in query.
[ "SkipQueryPlanCacheDirective", "returns", "true", "if", "skip", "query", "plan", "cache", "directive", "is", "set", "to", "true", "in", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/comments.go#L291-L317
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/ddl.go
DDLParse
func DDLParse(sql string) (plan *DDLPlan) { statement, err := sqlparser.Parse(sql) if err != nil { return &DDLPlan{Action: ""} } stmt, ok := statement.(*sqlparser.DDL) if !ok { return &DDLPlan{Action: ""} } return &DDLPlan{ Action: stmt.Action, } }
go
func DDLParse(sql string) (plan *DDLPlan) { statement, err := sqlparser.Parse(sql) if err != nil { return &DDLPlan{Action: ""} } stmt, ok := statement.(*sqlparser.DDL) if !ok { return &DDLPlan{Action: ""} } return &DDLPlan{ Action: stmt.Action, } }
[ "func", "DDLParse", "(", "sql", "string", ")", "(", "plan", "*", "DDLPlan", ")", "{", "statement", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "DDLPlan", "{", "Action", ":", "\"", "\"", "}", "\n", "}", "\n", "stmt", ",", "ok", ":=", "statement", ".", "(", "*", "sqlparser", ".", "DDL", ")", "\n", "if", "!", "ok", "{", "return", "&", "DDLPlan", "{", "Action", ":", "\"", "\"", "}", "\n", "}", "\n", "return", "&", "DDLPlan", "{", "Action", ":", "stmt", ".", "Action", ",", "}", "\n", "}" ]
// DDLParse parses a DDL and produces a DDLPlan.
[ "DDLParse", "parses", "a", "DDL", "and", "produces", "a", "DDLPlan", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/ddl.go#L30-L42
train
vitessio/vitess
go/vt/vtctl/vtctl.go
tabletParamsToTabletAliases
func tabletParamsToTabletAliases(params []string) ([]*topodatapb.TabletAlias, error) { result := make([]*topodatapb.TabletAlias, len(params)) var err error for i, param := range params { result[i], err = topoproto.ParseTabletAlias(param) if err != nil { return nil, err } } return result, nil }
go
func tabletParamsToTabletAliases(params []string) ([]*topodatapb.TabletAlias, error) { result := make([]*topodatapb.TabletAlias, len(params)) var err error for i, param := range params { result[i], err = topoproto.ParseTabletAlias(param) if err != nil { return nil, err } } return result, nil }
[ "func", "tabletParamsToTabletAliases", "(", "params", "[", "]", "string", ")", "(", "[", "]", "*", "topodatapb", ".", "TabletAlias", ",", "error", ")", "{", "result", ":=", "make", "(", "[", "]", "*", "topodatapb", ".", "TabletAlias", ",", "len", "(", "params", ")", ")", "\n", "var", "err", "error", "\n", "for", "i", ",", "param", ":=", "range", "params", "{", "result", "[", "i", "]", ",", "err", "=", "topoproto", ".", "ParseTabletAlias", "(", "param", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// tabletParamsToTabletAliases takes multiple params and converts them // to tablet aliases.
[ "tabletParamsToTabletAliases", "takes", "multiple", "params", "and", "converts", "them", "to", "tablet", "aliases", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/vtctl.go#L603-L613
train
vitessio/vitess
go/vt/vtctl/vtctl.go
parseTabletType
func parseTabletType(param string, types []topodatapb.TabletType) (topodatapb.TabletType, error) { tabletType, err := topoproto.ParseTabletType(param) if err != nil { return topodatapb.TabletType_UNKNOWN, fmt.Errorf("invalid tablet type %v: %v", param, err) } if !topoproto.IsTypeInList(topodatapb.TabletType(tabletType), types) { return topodatapb.TabletType_UNKNOWN, fmt.Errorf("type %v is not one of: %v", tabletType, strings.Join(topoproto.MakeStringTypeList(types), " ")) } return tabletType, nil }
go
func parseTabletType(param string, types []topodatapb.TabletType) (topodatapb.TabletType, error) { tabletType, err := topoproto.ParseTabletType(param) if err != nil { return topodatapb.TabletType_UNKNOWN, fmt.Errorf("invalid tablet type %v: %v", param, err) } if !topoproto.IsTypeInList(topodatapb.TabletType(tabletType), types) { return topodatapb.TabletType_UNKNOWN, fmt.Errorf("type %v is not one of: %v", tabletType, strings.Join(topoproto.MakeStringTypeList(types), " ")) } return tabletType, nil }
[ "func", "parseTabletType", "(", "param", "string", ",", "types", "[", "]", "topodatapb", ".", "TabletType", ")", "(", "topodatapb", ".", "TabletType", ",", "error", ")", "{", "tabletType", ",", "err", ":=", "topoproto", ".", "ParseTabletType", "(", "param", ")", "\n", "if", "err", "!=", "nil", "{", "return", "topodatapb", ".", "TabletType_UNKNOWN", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "param", ",", "err", ")", "\n", "}", "\n", "if", "!", "topoproto", ".", "IsTypeInList", "(", "topodatapb", ".", "TabletType", "(", "tabletType", ")", ",", "types", ")", "{", "return", "topodatapb", ".", "TabletType_UNKNOWN", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tabletType", ",", "strings", ".", "Join", "(", "topoproto", ".", "MakeStringTypeList", "(", "types", ")", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "tabletType", ",", "nil", "\n", "}" ]
// parseTabletType parses the string tablet type and verifies // it is an accepted one
[ "parseTabletType", "parses", "the", "string", "tablet", "type", "and", "verifies", "it", "is", "an", "accepted", "one" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/vtctl.go#L617-L626
train
vitessio/vitess
go/vt/vtctl/vtctl.go
printJSON
func printJSON(logger logutil.Logger, val interface{}) error { data, err := MarshalJSON(val) if err != nil { return fmt.Errorf("cannot marshal data: %v", err) } logger.Printf("%v\n", string(data)) return nil }
go
func printJSON(logger logutil.Logger, val interface{}) error { data, err := MarshalJSON(val) if err != nil { return fmt.Errorf("cannot marshal data: %v", err) } logger.Printf("%v\n", string(data)) return nil }
[ "func", "printJSON", "(", "logger", "logutil", ".", "Logger", ",", "val", "interface", "{", "}", ")", "error", "{", "data", ",", "err", ":=", "MarshalJSON", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "string", "(", "data", ")", ")", "\n", "return", "nil", "\n", "}" ]
// printJSON will print the JSON version of the structure to the logger.
[ "printJSON", "will", "print", "the", "JSON", "version", "of", "the", "structure", "to", "the", "logger", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/vtctl.go#L2531-L2538
train
vitessio/vitess
go/vt/vtctl/vtctl.go
RunCommand
func RunCommand(ctx context.Context, wr *wrangler.Wrangler, args []string) error { if len(args) == 0 { wr.Logger().Printf("No command specified. Please see the list below:\n\n") PrintAllCommands(wr.Logger()) return fmt.Errorf("no command was specified") } action := args[0] actionLowerCase := strings.ToLower(action) for _, group := range commands { for _, cmd := range group.commands { if strings.ToLower(cmd.name) == actionLowerCase { subFlags := flag.NewFlagSet(action, flag.ContinueOnError) subFlags.SetOutput(logutil.NewLoggerWriter(wr.Logger())) subFlags.Usage = func() { wr.Logger().Printf("Usage: %s %s\n\n", action, cmd.params) wr.Logger().Printf("%s\n\n", cmd.help) subFlags.PrintDefaults() } return cmd.method(ctx, wr, subFlags, args[1:]) } } } wr.Logger().Printf("Unknown command: %v\n", action) return ErrUnknownCommand }
go
func RunCommand(ctx context.Context, wr *wrangler.Wrangler, args []string) error { if len(args) == 0 { wr.Logger().Printf("No command specified. Please see the list below:\n\n") PrintAllCommands(wr.Logger()) return fmt.Errorf("no command was specified") } action := args[0] actionLowerCase := strings.ToLower(action) for _, group := range commands { for _, cmd := range group.commands { if strings.ToLower(cmd.name) == actionLowerCase { subFlags := flag.NewFlagSet(action, flag.ContinueOnError) subFlags.SetOutput(logutil.NewLoggerWriter(wr.Logger())) subFlags.Usage = func() { wr.Logger().Printf("Usage: %s %s\n\n", action, cmd.params) wr.Logger().Printf("%s\n\n", cmd.help) subFlags.PrintDefaults() } return cmd.method(ctx, wr, subFlags, args[1:]) } } } wr.Logger().Printf("Unknown command: %v\n", action) return ErrUnknownCommand }
[ "func", "RunCommand", "(", "ctx", "context", ".", "Context", ",", "wr", "*", "wrangler", ".", "Wrangler", ",", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", "==", "0", "{", "wr", ".", "Logger", "(", ")", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ")", "\n", "PrintAllCommands", "(", "wr", ".", "Logger", "(", ")", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "action", ":=", "args", "[", "0", "]", "\n", "actionLowerCase", ":=", "strings", ".", "ToLower", "(", "action", ")", "\n", "for", "_", ",", "group", ":=", "range", "commands", "{", "for", "_", ",", "cmd", ":=", "range", "group", ".", "commands", "{", "if", "strings", ".", "ToLower", "(", "cmd", ".", "name", ")", "==", "actionLowerCase", "{", "subFlags", ":=", "flag", ".", "NewFlagSet", "(", "action", ",", "flag", ".", "ContinueOnError", ")", "\n", "subFlags", ".", "SetOutput", "(", "logutil", ".", "NewLoggerWriter", "(", "wr", ".", "Logger", "(", ")", ")", ")", "\n", "subFlags", ".", "Usage", "=", "func", "(", ")", "{", "wr", ".", "Logger", "(", ")", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ",", "action", ",", "cmd", ".", "params", ")", "\n", "wr", ".", "Logger", "(", ")", ".", "Printf", "(", "\"", "\\n", "\\n", "\"", ",", "cmd", ".", "help", ")", "\n", "subFlags", ".", "PrintDefaults", "(", ")", "\n", "}", "\n", "return", "cmd", ".", "method", "(", "ctx", ",", "wr", ",", "subFlags", ",", "args", "[", "1", ":", "]", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "wr", ".", "Logger", "(", ")", ".", "Printf", "(", "\"", "\\n", "\"", ",", "action", ")", "\n", "return", "ErrUnknownCommand", "\n", "}" ]
// RunCommand will execute the command using the provided wrangler. // It will return the actionPath to wait on for long remote actions if // applicable.
[ "RunCommand", "will", "execute", "the", "command", "using", "the", "provided", "wrangler", ".", "It", "will", "return", "the", "actionPath", "to", "wait", "on", "for", "long", "remote", "actions", "if", "applicable", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/vtctl.go#L2588-L2614
train
vitessio/vitess
go/vt/vtctl/vtctl.go
PrintAllCommands
func PrintAllCommands(logger logutil.Logger) { for _, group := range commands { logger.Printf("%s:\n", group.name) for _, cmd := range group.commands { if strings.HasPrefix(cmd.help, "HIDDEN") { continue } logger.Printf(" %s %s\n", cmd.name, cmd.params) } logger.Printf("\n") } }
go
func PrintAllCommands(logger logutil.Logger) { for _, group := range commands { logger.Printf("%s:\n", group.name) for _, cmd := range group.commands { if strings.HasPrefix(cmd.help, "HIDDEN") { continue } logger.Printf(" %s %s\n", cmd.name, cmd.params) } logger.Printf("\n") } }
[ "func", "PrintAllCommands", "(", "logger", "logutil", ".", "Logger", ")", "{", "for", "_", ",", "group", ":=", "range", "commands", "{", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "group", ".", "name", ")", "\n", "for", "_", ",", "cmd", ":=", "range", "group", ".", "commands", "{", "if", "strings", ".", "HasPrefix", "(", "cmd", ".", "help", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "cmd", ".", "name", ",", "cmd", ".", "params", ")", "\n", "}", "\n", "logger", ".", "Printf", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "}" ]
// PrintAllCommands will print the list of commands to the logger
[ "PrintAllCommands", "will", "print", "the", "list", "of", "commands", "to", "the", "logger" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/vtctl.go#L2617-L2628
train
vitessio/vitess
go/vt/worker/split_diff.go
NewSplitDiffWorker
func NewSplitDiffWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, sourceUID uint32, excludeTables []string, minHealthyRdonlyTablets, parallelDiffsCount int, tabletType topodatapb.TabletType) Worker { return &SplitDiffWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, sourceUID: sourceUID, excludeTables: excludeTables, minHealthyRdonlyTablets: minHealthyRdonlyTablets, destinationTabletType: tabletType, parallelDiffsCount: parallelDiffsCount, cleaner: &wrangler.Cleaner{}, } }
go
func NewSplitDiffWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, sourceUID uint32, excludeTables []string, minHealthyRdonlyTablets, parallelDiffsCount int, tabletType topodatapb.TabletType) Worker { return &SplitDiffWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, sourceUID: sourceUID, excludeTables: excludeTables, minHealthyRdonlyTablets: minHealthyRdonlyTablets, destinationTabletType: tabletType, parallelDiffsCount: parallelDiffsCount, cleaner: &wrangler.Cleaner{}, } }
[ "func", "NewSplitDiffWorker", "(", "wr", "*", "wrangler", ".", "Wrangler", ",", "cell", ",", "keyspace", ",", "shard", "string", ",", "sourceUID", "uint32", ",", "excludeTables", "[", "]", "string", ",", "minHealthyRdonlyTablets", ",", "parallelDiffsCount", "int", ",", "tabletType", "topodatapb", ".", "TabletType", ")", "Worker", "{", "return", "&", "SplitDiffWorker", "{", "StatusWorker", ":", "NewStatusWorker", "(", ")", ",", "wr", ":", "wr", ",", "cell", ":", "cell", ",", "keyspace", ":", "keyspace", ",", "shard", ":", "shard", ",", "sourceUID", ":", "sourceUID", ",", "excludeTables", ":", "excludeTables", ",", "minHealthyRdonlyTablets", ":", "minHealthyRdonlyTablets", ",", "destinationTabletType", ":", "tabletType", ",", "parallelDiffsCount", ":", "parallelDiffsCount", ",", "cleaner", ":", "&", "wrangler", ".", "Cleaner", "{", "}", ",", "}", "\n", "}" ]
// NewSplitDiffWorker returns a new SplitDiffWorker object.
[ "NewSplitDiffWorker", "returns", "a", "new", "SplitDiffWorker", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/split_diff.go#L74-L88
train
vitessio/vitess
go/vt/mysqlproxy/mysqlproxy.go
NewProxy
func NewProxy(target *querypb.Target, qs queryservice.QueryService, normalize bool) *Proxy { return &Proxy{ target: target, qs: qs, normalize: normalize, } }
go
func NewProxy(target *querypb.Target, qs queryservice.QueryService, normalize bool) *Proxy { return &Proxy{ target: target, qs: qs, normalize: normalize, } }
[ "func", "NewProxy", "(", "target", "*", "querypb", ".", "Target", ",", "qs", "queryservice", ".", "QueryService", ",", "normalize", "bool", ")", "*", "Proxy", "{", "return", "&", "Proxy", "{", "target", ":", "target", ",", "qs", ":", "qs", ",", "normalize", ":", "normalize", ",", "}", "\n", "}" ]
// NewProxy creates a new proxy
[ "NewProxy", "creates", "a", "new", "proxy" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlproxy/mysqlproxy.go#L50-L56
train
vitessio/vitess
go/vt/mysqlproxy/mysqlproxy.go
Execute
func (mp *Proxy) Execute(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*ProxySession, *sqltypes.Result, error) { var err error result := &sqltypes.Result{} switch sqlparser.Preview(sql) { case sqlparser.StmtBegin: err = mp.doBegin(ctx, session) case sqlparser.StmtCommit: err = mp.doCommit(ctx, session) case sqlparser.StmtRollback: err = mp.doRollback(ctx, session) case sqlparser.StmtSet: result, err = mp.doSet(ctx, session, sql, bindVariables) case sqlparser.StmtInsert, sqlparser.StmtUpdate, sqlparser.StmtDelete, sqlparser.StmtReplace: result, err = mp.executeDML(ctx, session, sql, bindVariables) case sqlparser.StmtSelect: result, err = mp.executeSelect(ctx, session, sql, bindVariables) default: result, err = mp.executeOther(ctx, session, sql, bindVariables) } // N.B. You must return session, even on error. Modeled after vtgate mysql plugin, the // vtqueryserver plugin expects you to return a new or updated session and not drop it on the // floor during an error. return session, result, err }
go
func (mp *Proxy) Execute(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*ProxySession, *sqltypes.Result, error) { var err error result := &sqltypes.Result{} switch sqlparser.Preview(sql) { case sqlparser.StmtBegin: err = mp.doBegin(ctx, session) case sqlparser.StmtCommit: err = mp.doCommit(ctx, session) case sqlparser.StmtRollback: err = mp.doRollback(ctx, session) case sqlparser.StmtSet: result, err = mp.doSet(ctx, session, sql, bindVariables) case sqlparser.StmtInsert, sqlparser.StmtUpdate, sqlparser.StmtDelete, sqlparser.StmtReplace: result, err = mp.executeDML(ctx, session, sql, bindVariables) case sqlparser.StmtSelect: result, err = mp.executeSelect(ctx, session, sql, bindVariables) default: result, err = mp.executeOther(ctx, session, sql, bindVariables) } // N.B. You must return session, even on error. Modeled after vtgate mysql plugin, the // vtqueryserver plugin expects you to return a new or updated session and not drop it on the // floor during an error. return session, result, err }
[ "func", "(", "mp", "*", "Proxy", ")", "Execute", "(", "ctx", "context", ".", "Context", ",", "session", "*", "ProxySession", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "ProxySession", ",", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "var", "err", "error", "\n", "result", ":=", "&", "sqltypes", ".", "Result", "{", "}", "\n\n", "switch", "sqlparser", ".", "Preview", "(", "sql", ")", "{", "case", "sqlparser", ".", "StmtBegin", ":", "err", "=", "mp", ".", "doBegin", "(", "ctx", ",", "session", ")", "\n", "case", "sqlparser", ".", "StmtCommit", ":", "err", "=", "mp", ".", "doCommit", "(", "ctx", ",", "session", ")", "\n", "case", "sqlparser", ".", "StmtRollback", ":", "err", "=", "mp", ".", "doRollback", "(", "ctx", ",", "session", ")", "\n", "case", "sqlparser", ".", "StmtSet", ":", "result", ",", "err", "=", "mp", ".", "doSet", "(", "ctx", ",", "session", ",", "sql", ",", "bindVariables", ")", "\n", "case", "sqlparser", ".", "StmtInsert", ",", "sqlparser", ".", "StmtUpdate", ",", "sqlparser", ".", "StmtDelete", ",", "sqlparser", ".", "StmtReplace", ":", "result", ",", "err", "=", "mp", ".", "executeDML", "(", "ctx", ",", "session", ",", "sql", ",", "bindVariables", ")", "\n", "case", "sqlparser", ".", "StmtSelect", ":", "result", ",", "err", "=", "mp", ".", "executeSelect", "(", "ctx", ",", "session", ",", "sql", ",", "bindVariables", ")", "\n", "default", ":", "result", ",", "err", "=", "mp", ".", "executeOther", "(", "ctx", ",", "session", ",", "sql", ",", "bindVariables", ")", "\n", "}", "\n\n", "// N.B. You must return session, even on error. Modeled after vtgate mysql plugin, the", "// vtqueryserver plugin expects you to return a new or updated session and not drop it on the", "// floor during an error.", "return", "session", ",", "result", ",", "err", "\n", "}" ]
// Execute runs the given sql query in the specified session
[ "Execute", "runs", "the", "given", "sql", "query", "in", "the", "specified", "session" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlproxy/mysqlproxy.go#L59-L84
train
vitessio/vitess
go/vt/mysqlproxy/mysqlproxy.go
doSet
func (mp *Proxy) doSet(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { vals, _, err := sqlparser.ExtractSetValues(sql) if err != nil { return nil, err } for k, v := range vals { switch k.Key { case "autocommit": val, ok := v.(int64) if !ok { return nil, fmt.Errorf("unexpected value type for autocommit: %T", v) } switch val { case 0: session.Autocommit = false case 1: if !session.Autocommit && session.TransactionID != 0 { if err := mp.doCommit(ctx, session); err != nil { return nil, err } } session.Autocommit = true default: return nil, fmt.Errorf("unexpected value for autocommit: %d", val) } case "charset", "names": val, ok := v.(string) if !ok { return nil, fmt.Errorf("unexpected value type for charset/names: %T", v) } switch val { case "", "utf8", "utf8mb4", "latin1", "default": break default: return nil, fmt.Errorf("unexpected value for charset/names: %v", val) } default: log.Warningf("Ignored inapplicable SET %v = %v", k, v) } } return &sqltypes.Result{}, nil }
go
func (mp *Proxy) doSet(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { vals, _, err := sqlparser.ExtractSetValues(sql) if err != nil { return nil, err } for k, v := range vals { switch k.Key { case "autocommit": val, ok := v.(int64) if !ok { return nil, fmt.Errorf("unexpected value type for autocommit: %T", v) } switch val { case 0: session.Autocommit = false case 1: if !session.Autocommit && session.TransactionID != 0 { if err := mp.doCommit(ctx, session); err != nil { return nil, err } } session.Autocommit = true default: return nil, fmt.Errorf("unexpected value for autocommit: %d", val) } case "charset", "names": val, ok := v.(string) if !ok { return nil, fmt.Errorf("unexpected value type for charset/names: %T", v) } switch val { case "", "utf8", "utf8mb4", "latin1", "default": break default: return nil, fmt.Errorf("unexpected value for charset/names: %v", val) } default: log.Warningf("Ignored inapplicable SET %v = %v", k, v) } } return &sqltypes.Result{}, nil }
[ "func", "(", "mp", "*", "Proxy", ")", "doSet", "(", "ctx", "context", ".", "Context", ",", "session", "*", "ProxySession", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "vals", ",", "_", ",", "err", ":=", "sqlparser", ".", "ExtractSetValues", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "vals", "{", "switch", "k", ".", "Key", "{", "case", "\"", "\"", ":", "val", ",", "ok", ":=", "v", ".", "(", "int64", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "switch", "val", "{", "case", "0", ":", "session", ".", "Autocommit", "=", "false", "\n", "case", "1", ":", "if", "!", "session", ".", "Autocommit", "&&", "session", ".", "TransactionID", "!=", "0", "{", "if", "err", ":=", "mp", ".", "doCommit", "(", "ctx", ",", "session", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "session", ".", "Autocommit", "=", "true", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "val", ")", "\n", "}", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "val", ",", "ok", ":=", "v", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "switch", "val", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "break", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "val", ")", "\n", "}", "\n", "default", ":", "log", ".", "Warningf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "}", "\n\n", "return", "&", "sqltypes", ".", "Result", "{", "}", ",", "nil", "\n", "}" ]
// Set is currently ignored
[ "Set", "is", "currently", "ignored" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlproxy/mysqlproxy.go#L128-L171
train
vitessio/vitess
go/vt/mysqlproxy/mysqlproxy.go
executeSelect
func (mp *Proxy) executeSelect(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { if mp.normalize { query, comments := sqlparser.SplitMarginComments(sql) stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } sqlparser.Normalize(stmt, bindVariables, "vtp") normalized := sqlparser.String(stmt) sql = comments.Leading + normalized + comments.Trailing } return mp.qs.Execute(ctx, mp.target, sql, bindVariables, session.TransactionID, session.Options) }
go
func (mp *Proxy) executeSelect(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { if mp.normalize { query, comments := sqlparser.SplitMarginComments(sql) stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } sqlparser.Normalize(stmt, bindVariables, "vtp") normalized := sqlparser.String(stmt) sql = comments.Leading + normalized + comments.Trailing } return mp.qs.Execute(ctx, mp.target, sql, bindVariables, session.TransactionID, session.Options) }
[ "func", "(", "mp", "*", "Proxy", ")", "executeSelect", "(", "ctx", "context", ".", "Context", ",", "session", "*", "ProxySession", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "if", "mp", ".", "normalize", "{", "query", ",", "comments", ":=", "sqlparser", ".", "SplitMarginComments", "(", "sql", ")", "\n", "stmt", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sqlparser", ".", "Normalize", "(", "stmt", ",", "bindVariables", ",", "\"", "\"", ")", "\n", "normalized", ":=", "sqlparser", ".", "String", "(", "stmt", ")", "\n", "sql", "=", "comments", ".", "Leading", "+", "normalized", "+", "comments", ".", "Trailing", "\n", "}", "\n\n", "return", "mp", ".", "qs", ".", "Execute", "(", "ctx", ",", "mp", ".", "target", ",", "sql", ",", "bindVariables", ",", "session", ".", "TransactionID", ",", "session", ".", "Options", ")", "\n", "}" ]
// executeSelect runs the given select statement
[ "executeSelect", "runs", "the", "given", "select", "statement" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlproxy/mysqlproxy.go#L174-L187
train
vitessio/vitess
go/vt/mysqlproxy/mysqlproxy.go
executeDML
func (mp *Proxy) executeDML(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { if mp.normalize { query, comments := sqlparser.SplitMarginComments(sql) stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } sqlparser.Normalize(stmt, bindVariables, "vtp") normalized := sqlparser.String(stmt) sql = comments.Leading + normalized + comments.Trailing } if session.TransactionID != 0 { return mp.qs.Execute(ctx, mp.target, sql, bindVariables, session.TransactionID, session.Options) } else if session.Autocommit { queries := []*querypb.BoundQuery{{ Sql: sql, BindVariables: bindVariables, }} // This is a stopgap until there is a better way to do autocommit results, err := mp.qs.ExecuteBatch(ctx, mp.target, queries, true /* asTransaction */, 0, session.Options) if err != nil { return nil, err } return &results[0], nil } else { result, txnID, err := mp.qs.BeginExecute(ctx, mp.target, sql, bindVariables, session.Options) if err != nil { return nil, err } session.TransactionID = txnID return result, nil } }
go
func (mp *Proxy) executeDML(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { if mp.normalize { query, comments := sqlparser.SplitMarginComments(sql) stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } sqlparser.Normalize(stmt, bindVariables, "vtp") normalized := sqlparser.String(stmt) sql = comments.Leading + normalized + comments.Trailing } if session.TransactionID != 0 { return mp.qs.Execute(ctx, mp.target, sql, bindVariables, session.TransactionID, session.Options) } else if session.Autocommit { queries := []*querypb.BoundQuery{{ Sql: sql, BindVariables: bindVariables, }} // This is a stopgap until there is a better way to do autocommit results, err := mp.qs.ExecuteBatch(ctx, mp.target, queries, true /* asTransaction */, 0, session.Options) if err != nil { return nil, err } return &results[0], nil } else { result, txnID, err := mp.qs.BeginExecute(ctx, mp.target, sql, bindVariables, session.Options) if err != nil { return nil, err } session.TransactionID = txnID return result, nil } }
[ "func", "(", "mp", "*", "Proxy", ")", "executeDML", "(", "ctx", "context", ".", "Context", ",", "session", "*", "ProxySession", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "if", "mp", ".", "normalize", "{", "query", ",", "comments", ":=", "sqlparser", ".", "SplitMarginComments", "(", "sql", ")", "\n", "stmt", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sqlparser", ".", "Normalize", "(", "stmt", ",", "bindVariables", ",", "\"", "\"", ")", "\n", "normalized", ":=", "sqlparser", ".", "String", "(", "stmt", ")", "\n", "sql", "=", "comments", ".", "Leading", "+", "normalized", "+", "comments", ".", "Trailing", "\n", "}", "\n\n", "if", "session", ".", "TransactionID", "!=", "0", "{", "return", "mp", ".", "qs", ".", "Execute", "(", "ctx", ",", "mp", ".", "target", ",", "sql", ",", "bindVariables", ",", "session", ".", "TransactionID", ",", "session", ".", "Options", ")", "\n\n", "}", "else", "if", "session", ".", "Autocommit", "{", "queries", ":=", "[", "]", "*", "querypb", ".", "BoundQuery", "{", "{", "Sql", ":", "sql", ",", "BindVariables", ":", "bindVariables", ",", "}", "}", "\n\n", "// This is a stopgap until there is a better way to do autocommit", "results", ",", "err", ":=", "mp", ".", "qs", ".", "ExecuteBatch", "(", "ctx", ",", "mp", ".", "target", ",", "queries", ",", "true", "/* asTransaction */", ",", "0", ",", "session", ".", "Options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "results", "[", "0", "]", ",", "nil", "\n\n", "}", "else", "{", "result", ",", "txnID", ",", "err", ":=", "mp", ".", "qs", ".", "BeginExecute", "(", "ctx", ",", "mp", ".", "target", ",", "sql", ",", "bindVariables", ",", "session", ".", "Options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "session", ".", "TransactionID", "=", "txnID", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "}" ]
// executeDML runs the given query handling autocommit semantics
[ "executeDML", "runs", "the", "given", "query", "handling", "autocommit", "semantics" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlproxy/mysqlproxy.go#L190-L226
train
vitessio/vitess
go/vt/mysqlproxy/mysqlproxy.go
executeOther
func (mp *Proxy) executeOther(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return mp.qs.Execute(ctx, mp.target, sql, bindVariables, session.TransactionID, session.Options) }
go
func (mp *Proxy) executeOther(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) { return mp.qs.Execute(ctx, mp.target, sql, bindVariables, session.TransactionID, session.Options) }
[ "func", "(", "mp", "*", "Proxy", ")", "executeOther", "(", "ctx", "context", ".", "Context", ",", "session", "*", "ProxySession", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "return", "mp", ".", "qs", ".", "Execute", "(", "ctx", ",", "mp", ".", "target", ",", "sql", ",", "bindVariables", ",", "session", ".", "TransactionID", ",", "session", ".", "Options", ")", "\n", "}" ]
// executeOther runs the given other statement bypassing the normalizer
[ "executeOther", "runs", "the", "given", "other", "statement", "bypassing", "the", "normalizer" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlproxy/mysqlproxy.go#L229-L231
train
vitessio/vitess
go/vt/vtqueryserver/plugin_mysql_server.go
newMysqlUnixSocket
func newMysqlUnixSocket(address string, authServer mysql.AuthServer, handler mysql.Handler) (*mysql.Listener, error) { listener, err := mysql.NewListener("unix", address, authServer, handler, *mysqlConnReadTimeout, *mysqlConnWriteTimeout) switch err := err.(type) { case nil: return listener, nil case *net.OpError: log.Warningf("Found existent socket when trying to create new unix mysql listener: %s, attempting to clean up", address) // err.Op should never be different from listen, just being extra careful // in case in the future other errors are returned here if err.Op != "listen" { return nil, err } _, dialErr := net.Dial("unix", address) if dialErr == nil { log.Errorf("Existent socket '%s' is still accepting connections, aborting", address) return nil, err } removeFileErr := os.Remove(address) if removeFileErr != nil { log.Errorf("Couldn't remove existent socket file: %s", address) return nil, err } listener, listenerErr := mysql.NewListener("unix", address, authServer, handler, *mysqlConnReadTimeout, *mysqlConnWriteTimeout) return listener, listenerErr default: return nil, err } }
go
func newMysqlUnixSocket(address string, authServer mysql.AuthServer, handler mysql.Handler) (*mysql.Listener, error) { listener, err := mysql.NewListener("unix", address, authServer, handler, *mysqlConnReadTimeout, *mysqlConnWriteTimeout) switch err := err.(type) { case nil: return listener, nil case *net.OpError: log.Warningf("Found existent socket when trying to create new unix mysql listener: %s, attempting to clean up", address) // err.Op should never be different from listen, just being extra careful // in case in the future other errors are returned here if err.Op != "listen" { return nil, err } _, dialErr := net.Dial("unix", address) if dialErr == nil { log.Errorf("Existent socket '%s' is still accepting connections, aborting", address) return nil, err } removeFileErr := os.Remove(address) if removeFileErr != nil { log.Errorf("Couldn't remove existent socket file: %s", address) return nil, err } listener, listenerErr := mysql.NewListener("unix", address, authServer, handler, *mysqlConnReadTimeout, *mysqlConnWriteTimeout) return listener, listenerErr default: return nil, err } }
[ "func", "newMysqlUnixSocket", "(", "address", "string", ",", "authServer", "mysql", ".", "AuthServer", ",", "handler", "mysql", ".", "Handler", ")", "(", "*", "mysql", ".", "Listener", ",", "error", ")", "{", "listener", ",", "err", ":=", "mysql", ".", "NewListener", "(", "\"", "\"", ",", "address", ",", "authServer", ",", "handler", ",", "*", "mysqlConnReadTimeout", ",", "*", "mysqlConnWriteTimeout", ")", "\n", "switch", "err", ":=", "err", ".", "(", "type", ")", "{", "case", "nil", ":", "return", "listener", ",", "nil", "\n", "case", "*", "net", ".", "OpError", ":", "log", ".", "Warningf", "(", "\"", "\"", ",", "address", ")", "\n", "// err.Op should never be different from listen, just being extra careful", "// in case in the future other errors are returned here", "if", "err", ".", "Op", "!=", "\"", "\"", "{", "return", "nil", ",", "err", "\n", "}", "\n", "_", ",", "dialErr", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "address", ")", "\n", "if", "dialErr", "==", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "address", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "removeFileErr", ":=", "os", ".", "Remove", "(", "address", ")", "\n", "if", "removeFileErr", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "address", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "listener", ",", "listenerErr", ":=", "mysql", ".", "NewListener", "(", "\"", "\"", ",", "address", ",", "authServer", ",", "handler", ",", "*", "mysqlConnReadTimeout", ",", "*", "mysqlConnWriteTimeout", ")", "\n", "return", "listener", ",", "listenerErr", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// newMysqlUnixSocket creates a new unix socket mysql listener. If a socket file already exists, attempts // to clean it up.
[ "newMysqlUnixSocket", "creates", "a", "new", "unix", "socket", "mysql", "listener", ".", "If", "a", "socket", "file", "already", "exists", "attempts", "to", "clean", "it", "up", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtqueryserver/plugin_mysql_server.go#L208-L235
train
vitessio/vitess
go/cacheservice/cacheservice.go
Register
func Register(name string, fn NewConnFunc) { mu.Lock() defer mu.Unlock() if _, ok := services[name]; ok { panic(fmt.Sprintf("register a registered key: %s", name)) } services[name] = fn }
go
func Register(name string, fn NewConnFunc) { mu.Lock() defer mu.Unlock() if _, ok := services[name]; ok { panic(fmt.Sprintf("register a registered key: %s", name)) } services[name] = fn }
[ "func", "Register", "(", "name", "string", ",", "fn", "NewConnFunc", ")", "{", "mu", ".", "Lock", "(", ")", "\n", "defer", "mu", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "services", "[", "name", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n", "services", "[", "name", "]", "=", "fn", "\n", "}" ]
// Register a db connection.
[ "Register", "a", "db", "connection", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cacheservice/cacheservice.go#L83-L90
train
vitessio/vitess
go/cacheservice/cacheservice.go
Connect
func Connect(config Config) (CacheService, error) { mu.Lock() defer mu.Unlock() if DefaultCacheService == "" { if len(services) == 1 { for _, fn := range services { return fn(config) } } panic("there are more than one service connect func " + "registered but no default cache service has been specified.") } fn, ok := services[DefaultCacheService] if !ok { panic(fmt.Sprintf("service connect function for given default cache service: %s is not found.", DefaultCacheService)) } return fn(config) }
go
func Connect(config Config) (CacheService, error) { mu.Lock() defer mu.Unlock() if DefaultCacheService == "" { if len(services) == 1 { for _, fn := range services { return fn(config) } } panic("there are more than one service connect func " + "registered but no default cache service has been specified.") } fn, ok := services[DefaultCacheService] if !ok { panic(fmt.Sprintf("service connect function for given default cache service: %s is not found.", DefaultCacheService)) } return fn(config) }
[ "func", "Connect", "(", "config", "Config", ")", "(", "CacheService", ",", "error", ")", "{", "mu", ".", "Lock", "(", ")", "\n", "defer", "mu", ".", "Unlock", "(", ")", "\n", "if", "DefaultCacheService", "==", "\"", "\"", "{", "if", "len", "(", "services", ")", "==", "1", "{", "for", "_", ",", "fn", ":=", "range", "services", "{", "return", "fn", "(", "config", ")", "\n", "}", "\n", "}", "\n", "panic", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n", "fn", ",", "ok", ":=", "services", "[", "DefaultCacheService", "]", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "DefaultCacheService", ")", ")", "\n", "}", "\n", "return", "fn", "(", "config", ")", "\n", "}" ]
// Connect returns a CacheService using the given config.
[ "Connect", "returns", "a", "CacheService", "using", "the", "given", "config", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cacheservice/cacheservice.go#L93-L110
train
vitessio/vitess
go/vt/vtgate/engine/merge_sort.go
mergeSort
func mergeSort(vcursor VCursor, query string, orderBy []OrderbyParams, rss []*srvtopo.ResolvedShard, bvs []map[string]*querypb.BindVariable, callback func(*sqltypes.Result) error) error { ctx, cancel := context.WithCancel(vcursor.Context()) defer cancel() handles := make([]*streamHandle, len(rss)) id := 0 for i, rs := range rss { handles[id] = runOneStream(ctx, vcursor, query, rs, bvs[i]) id++ } // Fetch field info from just one stream. fields := <-handles[0].fields // If fields is nil, it means there was an error. if fields == nil { return handles[0].err } if err := callback(&sqltypes.Result{Fields: fields}); err != nil { return err } sh := &scatterHeap{ rows: make([]streamRow, 0, len(handles)), orderBy: orderBy, } // Prime the heap. One element must be pulled from // each stream. for i, handle := range handles { select { case row, ok := <-handle.row: if !ok { if handle.err != nil { return handle.err } // It's possible that a stream returns no rows. // If so, don't add anything to the heap. continue } sh.rows = append(sh.rows, streamRow{row: row, id: i}) case <-ctx.Done(): return ctx.Err() } } heap.Init(sh) if sh.err != nil { return sh.err } // Iterate one row at a time: // Pop a row from the heap and send it out. // Then pull the next row from the stream the popped // row came from and push it into the heap. for len(sh.rows) != 0 { sr := heap.Pop(sh).(streamRow) if sh.err != nil { // Unreachable: This should never fail. return sh.err } if err := callback(&sqltypes.Result{Rows: [][]sqltypes.Value{sr.row}}); err != nil { return err } select { case row, ok := <-handles[sr.id].row: if !ok { if handles[sr.id].err != nil { return handles[sr.id].err } continue } sr.row = row heap.Push(sh, sr) if sh.err != nil { return sh.err } case <-ctx.Done(): return ctx.Err() } } return nil }
go
func mergeSort(vcursor VCursor, query string, orderBy []OrderbyParams, rss []*srvtopo.ResolvedShard, bvs []map[string]*querypb.BindVariable, callback func(*sqltypes.Result) error) error { ctx, cancel := context.WithCancel(vcursor.Context()) defer cancel() handles := make([]*streamHandle, len(rss)) id := 0 for i, rs := range rss { handles[id] = runOneStream(ctx, vcursor, query, rs, bvs[i]) id++ } // Fetch field info from just one stream. fields := <-handles[0].fields // If fields is nil, it means there was an error. if fields == nil { return handles[0].err } if err := callback(&sqltypes.Result{Fields: fields}); err != nil { return err } sh := &scatterHeap{ rows: make([]streamRow, 0, len(handles)), orderBy: orderBy, } // Prime the heap. One element must be pulled from // each stream. for i, handle := range handles { select { case row, ok := <-handle.row: if !ok { if handle.err != nil { return handle.err } // It's possible that a stream returns no rows. // If so, don't add anything to the heap. continue } sh.rows = append(sh.rows, streamRow{row: row, id: i}) case <-ctx.Done(): return ctx.Err() } } heap.Init(sh) if sh.err != nil { return sh.err } // Iterate one row at a time: // Pop a row from the heap and send it out. // Then pull the next row from the stream the popped // row came from and push it into the heap. for len(sh.rows) != 0 { sr := heap.Pop(sh).(streamRow) if sh.err != nil { // Unreachable: This should never fail. return sh.err } if err := callback(&sqltypes.Result{Rows: [][]sqltypes.Value{sr.row}}); err != nil { return err } select { case row, ok := <-handles[sr.id].row: if !ok { if handles[sr.id].err != nil { return handles[sr.id].err } continue } sr.row = row heap.Push(sh, sr) if sh.err != nil { return sh.err } case <-ctx.Done(): return ctx.Err() } } return nil }
[ "func", "mergeSort", "(", "vcursor", "VCursor", ",", "query", "string", ",", "orderBy", "[", "]", "OrderbyParams", ",", "rss", "[", "]", "*", "srvtopo", ".", "ResolvedShard", ",", "bvs", "[", "]", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "vcursor", ".", "Context", "(", ")", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "handles", ":=", "make", "(", "[", "]", "*", "streamHandle", ",", "len", "(", "rss", ")", ")", "\n", "id", ":=", "0", "\n", "for", "i", ",", "rs", ":=", "range", "rss", "{", "handles", "[", "id", "]", "=", "runOneStream", "(", "ctx", ",", "vcursor", ",", "query", ",", "rs", ",", "bvs", "[", "i", "]", ")", "\n", "id", "++", "\n", "}", "\n\n", "// Fetch field info from just one stream.", "fields", ":=", "<-", "handles", "[", "0", "]", ".", "fields", "\n", "// If fields is nil, it means there was an error.", "if", "fields", "==", "nil", "{", "return", "handles", "[", "0", "]", ".", "err", "\n", "}", "\n", "if", "err", ":=", "callback", "(", "&", "sqltypes", ".", "Result", "{", "Fields", ":", "fields", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "sh", ":=", "&", "scatterHeap", "{", "rows", ":", "make", "(", "[", "]", "streamRow", ",", "0", ",", "len", "(", "handles", ")", ")", ",", "orderBy", ":", "orderBy", ",", "}", "\n\n", "// Prime the heap. One element must be pulled from", "// each stream.", "for", "i", ",", "handle", ":=", "range", "handles", "{", "select", "{", "case", "row", ",", "ok", ":=", "<-", "handle", ".", "row", ":", "if", "!", "ok", "{", "if", "handle", ".", "err", "!=", "nil", "{", "return", "handle", ".", "err", "\n", "}", "\n", "// It's possible that a stream returns no rows.", "// If so, don't add anything to the heap.", "continue", "\n", "}", "\n", "sh", ".", "rows", "=", "append", "(", "sh", ".", "rows", ",", "streamRow", "{", "row", ":", "row", ",", "id", ":", "i", "}", ")", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "heap", ".", "Init", "(", "sh", ")", "\n", "if", "sh", ".", "err", "!=", "nil", "{", "return", "sh", ".", "err", "\n", "}", "\n\n", "// Iterate one row at a time:", "// Pop a row from the heap and send it out.", "// Then pull the next row from the stream the popped", "// row came from and push it into the heap.", "for", "len", "(", "sh", ".", "rows", ")", "!=", "0", "{", "sr", ":=", "heap", ".", "Pop", "(", "sh", ")", ".", "(", "streamRow", ")", "\n", "if", "sh", ".", "err", "!=", "nil", "{", "// Unreachable: This should never fail.", "return", "sh", ".", "err", "\n", "}", "\n", "if", "err", ":=", "callback", "(", "&", "sqltypes", ".", "Result", "{", "Rows", ":", "[", "]", "[", "]", "sqltypes", ".", "Value", "{", "sr", ".", "row", "}", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "select", "{", "case", "row", ",", "ok", ":=", "<-", "handles", "[", "sr", ".", "id", "]", ".", "row", ":", "if", "!", "ok", "{", "if", "handles", "[", "sr", ".", "id", "]", ".", "err", "!=", "nil", "{", "return", "handles", "[", "sr", ".", "id", "]", ".", "err", "\n", "}", "\n", "continue", "\n", "}", "\n", "sr", ".", "row", "=", "row", "\n", "heap", ".", "Push", "(", "sh", ",", "sr", ")", "\n", "if", "sh", ".", "err", "!=", "nil", "{", "return", "sh", ".", "err", "\n", "}", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mergeSort performs a merge-sort of rows returned by a streaming scatter query. // Each shard of the scatter query is treated as a stream. One row from each stream // is added to the merge-sorter heap. Every time a value is pulled out of the heap, // a new value is added to it from the stream that was the source of the value that // was pulled out. Since the input streams are sorted the same way that the heap is // sorted, this guarantees that the merged stream will also be sorted the same way.
[ "mergeSort", "performs", "a", "merge", "-", "sort", "of", "rows", "returned", "by", "a", "streaming", "scatter", "query", ".", "Each", "shard", "of", "the", "scatter", "query", "is", "treated", "as", "a", "stream", ".", "One", "row", "from", "each", "stream", "is", "added", "to", "the", "merge", "-", "sorter", "heap", ".", "Every", "time", "a", "value", "is", "pulled", "out", "of", "the", "heap", "a", "new", "value", "is", "added", "to", "it", "from", "the", "stream", "that", "was", "the", "source", "of", "the", "value", "that", "was", "pulled", "out", ".", "Since", "the", "input", "streams", "are", "sorted", "the", "same", "way", "that", "the", "heap", "is", "sorted", "this", "guarantees", "that", "the", "merged", "stream", "will", "also", "be", "sorted", "the", "same", "way", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/merge_sort.go#L39-L120
train
vitessio/vitess
go/vt/vtgate/engine/merge_sort.go
runOneStream
func runOneStream(ctx context.Context, vcursor VCursor, query string, rs *srvtopo.ResolvedShard, vars map[string]*querypb.BindVariable) *streamHandle { handle := &streamHandle{ fields: make(chan []*querypb.Field, 1), row: make(chan []sqltypes.Value, 10), } go func() { defer close(handle.fields) defer close(handle.row) handle.err = vcursor.StreamExecuteMulti( query, []*srvtopo.ResolvedShard{rs}, []map[string]*querypb.BindVariable{vars}, func(qr *sqltypes.Result) error { if len(qr.Fields) != 0 { select { case handle.fields <- qr.Fields: case <-ctx.Done(): return io.EOF } } for _, row := range qr.Rows { select { case handle.row <- row: case <-ctx.Done(): return io.EOF } } return nil }, ) }() return handle }
go
func runOneStream(ctx context.Context, vcursor VCursor, query string, rs *srvtopo.ResolvedShard, vars map[string]*querypb.BindVariable) *streamHandle { handle := &streamHandle{ fields: make(chan []*querypb.Field, 1), row: make(chan []sqltypes.Value, 10), } go func() { defer close(handle.fields) defer close(handle.row) handle.err = vcursor.StreamExecuteMulti( query, []*srvtopo.ResolvedShard{rs}, []map[string]*querypb.BindVariable{vars}, func(qr *sqltypes.Result) error { if len(qr.Fields) != 0 { select { case handle.fields <- qr.Fields: case <-ctx.Done(): return io.EOF } } for _, row := range qr.Rows { select { case handle.row <- row: case <-ctx.Done(): return io.EOF } } return nil }, ) }() return handle }
[ "func", "runOneStream", "(", "ctx", "context", ".", "Context", ",", "vcursor", "VCursor", ",", "query", "string", ",", "rs", "*", "srvtopo", ".", "ResolvedShard", ",", "vars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "*", "streamHandle", "{", "handle", ":=", "&", "streamHandle", "{", "fields", ":", "make", "(", "chan", "[", "]", "*", "querypb", ".", "Field", ",", "1", ")", ",", "row", ":", "make", "(", "chan", "[", "]", "sqltypes", ".", "Value", ",", "10", ")", ",", "}", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "handle", ".", "fields", ")", "\n", "defer", "close", "(", "handle", ".", "row", ")", "\n\n", "handle", ".", "err", "=", "vcursor", ".", "StreamExecuteMulti", "(", "query", ",", "[", "]", "*", "srvtopo", ".", "ResolvedShard", "{", "rs", "}", ",", "[", "]", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "vars", "}", ",", "func", "(", "qr", "*", "sqltypes", ".", "Result", ")", "error", "{", "if", "len", "(", "qr", ".", "Fields", ")", "!=", "0", "{", "select", "{", "case", "handle", ".", "fields", "<-", "qr", ".", "Fields", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "io", ".", "EOF", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "select", "{", "case", "handle", ".", "row", "<-", "row", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "io", ".", "EOF", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ",", ")", "\n", "}", "(", ")", "\n\n", "return", "handle", "\n", "}" ]
// runOnestream starts a streaming query on one shard, and returns a streamHandle for it.
[ "runOnestream", "starts", "a", "streaming", "query", "on", "one", "shard", "and", "returns", "a", "streamHandle", "for", "it", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/merge_sort.go#L136-L172
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
newMessageManager
func newMessageManager(tsv TabletService, table *schema.Table, conns *connpool.Pool, postponeSema *sync2.Semaphore) *messageManager { mm := &messageManager{ tsv: tsv, name: table.Name, fieldResult: &sqltypes.Result{ Fields: table.MessageInfo.Fields, }, ackWaitTime: table.MessageInfo.AckWaitDuration, purgeAfter: table.MessageInfo.PurgeAfterDuration, batchSize: table.MessageInfo.BatchSize, cache: newCache(table.MessageInfo.CacheSize), pollerTicks: timer.NewTimer(table.MessageInfo.PollInterval), purgeTicks: timer.NewTimer(table.MessageInfo.PollInterval), conns: conns, postponeSema: postponeSema, } mm.cond.L = &mm.mu columnList := buildSelectColumnList(table) mm.readByTimeNext = sqlparser.BuildParsedQuery( "select time_next, epoch, time_created, %s from %v where time_next < %a order by time_next desc limit %a", columnList, mm.name, ":time_next", ":max") mm.loadMessagesQuery = sqlparser.BuildParsedQuery( "select time_next, epoch, time_created, %s from %v where %a", columnList, mm.name, ":#pk") mm.ackQuery = sqlparser.BuildParsedQuery( "update %v set time_acked = %a, time_next = null where id in %a and time_acked is null", mm.name, ":time_acked", "::ids") mm.postponeQuery = sqlparser.BuildParsedQuery( "update %v set time_next = %a+(%a<<epoch), epoch = epoch+1 where id in %a and time_acked is null", mm.name, ":time_now", ":wait_time", "::ids") mm.purgeQuery = sqlparser.BuildParsedQuery( "delete from %v where time_scheduled < %a and time_acked is not null limit 500", mm.name, ":time_scheduled") return mm }
go
func newMessageManager(tsv TabletService, table *schema.Table, conns *connpool.Pool, postponeSema *sync2.Semaphore) *messageManager { mm := &messageManager{ tsv: tsv, name: table.Name, fieldResult: &sqltypes.Result{ Fields: table.MessageInfo.Fields, }, ackWaitTime: table.MessageInfo.AckWaitDuration, purgeAfter: table.MessageInfo.PurgeAfterDuration, batchSize: table.MessageInfo.BatchSize, cache: newCache(table.MessageInfo.CacheSize), pollerTicks: timer.NewTimer(table.MessageInfo.PollInterval), purgeTicks: timer.NewTimer(table.MessageInfo.PollInterval), conns: conns, postponeSema: postponeSema, } mm.cond.L = &mm.mu columnList := buildSelectColumnList(table) mm.readByTimeNext = sqlparser.BuildParsedQuery( "select time_next, epoch, time_created, %s from %v where time_next < %a order by time_next desc limit %a", columnList, mm.name, ":time_next", ":max") mm.loadMessagesQuery = sqlparser.BuildParsedQuery( "select time_next, epoch, time_created, %s from %v where %a", columnList, mm.name, ":#pk") mm.ackQuery = sqlparser.BuildParsedQuery( "update %v set time_acked = %a, time_next = null where id in %a and time_acked is null", mm.name, ":time_acked", "::ids") mm.postponeQuery = sqlparser.BuildParsedQuery( "update %v set time_next = %a+(%a<<epoch), epoch = epoch+1 where id in %a and time_acked is null", mm.name, ":time_now", ":wait_time", "::ids") mm.purgeQuery = sqlparser.BuildParsedQuery( "delete from %v where time_scheduled < %a and time_acked is not null limit 500", mm.name, ":time_scheduled") return mm }
[ "func", "newMessageManager", "(", "tsv", "TabletService", ",", "table", "*", "schema", ".", "Table", ",", "conns", "*", "connpool", ".", "Pool", ",", "postponeSema", "*", "sync2", ".", "Semaphore", ")", "*", "messageManager", "{", "mm", ":=", "&", "messageManager", "{", "tsv", ":", "tsv", ",", "name", ":", "table", ".", "Name", ",", "fieldResult", ":", "&", "sqltypes", ".", "Result", "{", "Fields", ":", "table", ".", "MessageInfo", ".", "Fields", ",", "}", ",", "ackWaitTime", ":", "table", ".", "MessageInfo", ".", "AckWaitDuration", ",", "purgeAfter", ":", "table", ".", "MessageInfo", ".", "PurgeAfterDuration", ",", "batchSize", ":", "table", ".", "MessageInfo", ".", "BatchSize", ",", "cache", ":", "newCache", "(", "table", ".", "MessageInfo", ".", "CacheSize", ")", ",", "pollerTicks", ":", "timer", ".", "NewTimer", "(", "table", ".", "MessageInfo", ".", "PollInterval", ")", ",", "purgeTicks", ":", "timer", ".", "NewTimer", "(", "table", ".", "MessageInfo", ".", "PollInterval", ")", ",", "conns", ":", "conns", ",", "postponeSema", ":", "postponeSema", ",", "}", "\n", "mm", ".", "cond", ".", "L", "=", "&", "mm", ".", "mu", "\n\n", "columnList", ":=", "buildSelectColumnList", "(", "table", ")", "\n", "mm", ".", "readByTimeNext", "=", "sqlparser", ".", "BuildParsedQuery", "(", "\"", "\"", ",", "columnList", ",", "mm", ".", "name", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "mm", ".", "loadMessagesQuery", "=", "sqlparser", ".", "BuildParsedQuery", "(", "\"", "\"", ",", "columnList", ",", "mm", ".", "name", ",", "\"", "\"", ")", "\n", "mm", ".", "ackQuery", "=", "sqlparser", ".", "BuildParsedQuery", "(", "\"", "\"", ",", "mm", ".", "name", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "mm", ".", "postponeQuery", "=", "sqlparser", ".", "BuildParsedQuery", "(", "\"", "\"", ",", "mm", ".", "name", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "mm", ".", "purgeQuery", "=", "sqlparser", ".", "BuildParsedQuery", "(", "\"", "\"", ",", "mm", ".", "name", ",", "\"", "\"", ")", "\n", "return", "mm", "\n", "}" ]
// newMessageManager creates a new message manager. // Calls into tsv have to be made asynchronously. Otherwise, // it can lead to deadlocks.
[ "newMessageManager", "creates", "a", "new", "message", "manager", ".", "Calls", "into", "tsv", "have", "to", "be", "made", "asynchronously", ".", "Otherwise", "it", "can", "lead", "to", "deadlocks", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L206-L241
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
buildSelectColumnList
func buildSelectColumnList(t *schema.Table) string { buf := sqlparser.NewTrackedBuffer(nil) for i, c := range t.MessageInfo.Fields { // Column names may have to be escaped. if i == 0 { buf.Myprintf("%v", sqlparser.NewColIdent(c.Name)) } else { buf.Myprintf(", %v", sqlparser.NewColIdent(c.Name)) } } return buf.String() }
go
func buildSelectColumnList(t *schema.Table) string { buf := sqlparser.NewTrackedBuffer(nil) for i, c := range t.MessageInfo.Fields { // Column names may have to be escaped. if i == 0 { buf.Myprintf("%v", sqlparser.NewColIdent(c.Name)) } else { buf.Myprintf(", %v", sqlparser.NewColIdent(c.Name)) } } return buf.String() }
[ "func", "buildSelectColumnList", "(", "t", "*", "schema", ".", "Table", ")", "string", "{", "buf", ":=", "sqlparser", ".", "NewTrackedBuffer", "(", "nil", ")", "\n", "for", "i", ",", "c", ":=", "range", "t", ".", "MessageInfo", ".", "Fields", "{", "// Column names may have to be escaped.", "if", "i", "==", "0", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "sqlparser", ".", "NewColIdent", "(", "c", ".", "Name", ")", ")", "\n", "}", "else", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "sqlparser", ".", "NewColIdent", "(", "c", ".", "Name", ")", ")", "\n", "}", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// buildSelectColumnList is a convenience function that // builds a 'select' list for the user-defined columns.
[ "buildSelectColumnList", "is", "a", "convenience", "function", "that", "builds", "a", "select", "list", "for", "the", "user", "-", "defined", "columns", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L245-L256
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
Open
func (mm *messageManager) Open() { mm.mu.Lock() defer mm.mu.Unlock() if mm.isOpen { return } mm.isOpen = true mm.wg.Add(1) mm.curReceiver = -1 go mm.runSend() // TODO(sougou): improve ticks to add randomness. mm.pollerTicks.Start(mm.runPoller) mm.purgeTicks.Start(mm.runPurge) }
go
func (mm *messageManager) Open() { mm.mu.Lock() defer mm.mu.Unlock() if mm.isOpen { return } mm.isOpen = true mm.wg.Add(1) mm.curReceiver = -1 go mm.runSend() // TODO(sougou): improve ticks to add randomness. mm.pollerTicks.Start(mm.runPoller) mm.purgeTicks.Start(mm.runPurge) }
[ "func", "(", "mm", "*", "messageManager", ")", "Open", "(", ")", "{", "mm", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "mm", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "mm", ".", "isOpen", "{", "return", "\n", "}", "\n", "mm", ".", "isOpen", "=", "true", "\n", "mm", ".", "wg", ".", "Add", "(", "1", ")", "\n", "mm", ".", "curReceiver", "=", "-", "1", "\n\n", "go", "mm", ".", "runSend", "(", ")", "\n", "// TODO(sougou): improve ticks to add randomness.", "mm", ".", "pollerTicks", ".", "Start", "(", "mm", ".", "runPoller", ")", "\n", "mm", ".", "purgeTicks", ".", "Start", "(", "mm", ".", "runPurge", ")", "\n", "}" ]
// Open starts the messageManager service.
[ "Open", "starts", "the", "messageManager", "service", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L259-L273
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
Close
func (mm *messageManager) Close() { mm.pollerTicks.Stop() mm.purgeTicks.Stop() mm.mu.Lock() if !mm.isOpen { mm.mu.Unlock() return } mm.isOpen = false for _, rcvr := range mm.receivers { rcvr.receiver.cancel() } mm.receivers = nil MessageStats.Set([]string{mm.name.String(), "ClientCount"}, 0) mm.cache.Clear() mm.cond.Broadcast() mm.mu.Unlock() mm.wg.Wait() }
go
func (mm *messageManager) Close() { mm.pollerTicks.Stop() mm.purgeTicks.Stop() mm.mu.Lock() if !mm.isOpen { mm.mu.Unlock() return } mm.isOpen = false for _, rcvr := range mm.receivers { rcvr.receiver.cancel() } mm.receivers = nil MessageStats.Set([]string{mm.name.String(), "ClientCount"}, 0) mm.cache.Clear() mm.cond.Broadcast() mm.mu.Unlock() mm.wg.Wait() }
[ "func", "(", "mm", "*", "messageManager", ")", "Close", "(", ")", "{", "mm", ".", "pollerTicks", ".", "Stop", "(", ")", "\n", "mm", ".", "purgeTicks", ".", "Stop", "(", ")", "\n\n", "mm", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "!", "mm", ".", "isOpen", "{", "mm", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "mm", ".", "isOpen", "=", "false", "\n", "for", "_", ",", "rcvr", ":=", "range", "mm", ".", "receivers", "{", "rcvr", ".", "receiver", ".", "cancel", "(", ")", "\n", "}", "\n", "mm", ".", "receivers", "=", "nil", "\n", "MessageStats", ".", "Set", "(", "[", "]", "string", "{", "mm", ".", "name", ".", "String", "(", ")", ",", "\"", "\"", "}", ",", "0", ")", "\n", "mm", ".", "cache", ".", "Clear", "(", ")", "\n", "mm", ".", "cond", ".", "Broadcast", "(", ")", "\n", "mm", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "mm", ".", "wg", ".", "Wait", "(", ")", "\n", "}" ]
// Close stops the messageManager service.
[ "Close", "stops", "the", "messageManager", "service", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L276-L296
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
rescanReceivers
func (mm *messageManager) rescanReceivers(start int) { cur := start for range mm.receivers { cur = (cur + 1) % len(mm.receivers) if !mm.receivers[cur].busy { if mm.curReceiver == -1 { mm.cond.Broadcast() } mm.curReceiver = cur return } } // Nothing was found. mm.curReceiver = -1 }
go
func (mm *messageManager) rescanReceivers(start int) { cur := start for range mm.receivers { cur = (cur + 1) % len(mm.receivers) if !mm.receivers[cur].busy { if mm.curReceiver == -1 { mm.cond.Broadcast() } mm.curReceiver = cur return } } // Nothing was found. mm.curReceiver = -1 }
[ "func", "(", "mm", "*", "messageManager", ")", "rescanReceivers", "(", "start", "int", ")", "{", "cur", ":=", "start", "\n", "for", "range", "mm", ".", "receivers", "{", "cur", "=", "(", "cur", "+", "1", ")", "%", "len", "(", "mm", ".", "receivers", ")", "\n", "if", "!", "mm", ".", "receivers", "[", "cur", "]", ".", "busy", "{", "if", "mm", ".", "curReceiver", "==", "-", "1", "{", "mm", ".", "cond", ".", "Broadcast", "(", ")", "\n", "}", "\n", "mm", ".", "curReceiver", "=", "cur", "\n", "return", "\n", "}", "\n", "}", "\n", "// Nothing was found.", "mm", ".", "curReceiver", "=", "-", "1", "\n", "}" ]
// rescanReceivers finds the next available receiver // using start as the starting point. If one was found, // it sets curReceiver to that index. If curReceiver // was previously -1, it broadcasts. If none was found, // curReceiver is set to -1. If there's no starting point, // it must be specified as -1.
[ "rescanReceivers", "finds", "the", "next", "available", "receiver", "using", "start", "as", "the", "starting", "point", ".", "If", "one", "was", "found", "it", "sets", "curReceiver", "to", "that", "index", ".", "If", "curReceiver", "was", "previously", "-", "1", "it", "broadcasts", ".", "If", "none", "was", "found", "curReceiver", "is", "set", "to", "-", "1", ".", "If", "there", "s", "no", "starting", "point", "it", "must", "be", "specified", "as", "-", "1", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L353-L367
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
Add
func (mm *messageManager) Add(mr *MessageRow) bool { mm.mu.Lock() defer mm.mu.Unlock() if len(mm.receivers) == 0 { return false } if !mm.cache.Add(mr) { // Cache is full. Enter "messagesPending" mode to let the poller // fill the cache with messages from disk as soon as a cache // slot becomes available. // We also skip notifying the send routine via mm.cond.Broadcast() // because a full cache means that it's already active. mm.messagesPending = true return false } mm.cond.Broadcast() return true }
go
func (mm *messageManager) Add(mr *MessageRow) bool { mm.mu.Lock() defer mm.mu.Unlock() if len(mm.receivers) == 0 { return false } if !mm.cache.Add(mr) { // Cache is full. Enter "messagesPending" mode to let the poller // fill the cache with messages from disk as soon as a cache // slot becomes available. // We also skip notifying the send routine via mm.cond.Broadcast() // because a full cache means that it's already active. mm.messagesPending = true return false } mm.cond.Broadcast() return true }
[ "func", "(", "mm", "*", "messageManager", ")", "Add", "(", "mr", "*", "MessageRow", ")", "bool", "{", "mm", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "mm", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "mm", ".", "receivers", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "if", "!", "mm", ".", "cache", ".", "Add", "(", "mr", ")", "{", "// Cache is full. Enter \"messagesPending\" mode to let the poller", "// fill the cache with messages from disk as soon as a cache", "// slot becomes available.", "// We also skip notifying the send routine via mm.cond.Broadcast()", "// because a full cache means that it's already active.", "mm", ".", "messagesPending", "=", "true", "\n", "return", "false", "\n", "}", "\n", "mm", ".", "cond", ".", "Broadcast", "(", ")", "\n", "return", "true", "\n", "}" ]
// Add adds the message to the cache. It returns true // if successful. If the message is already present, // it still returns true.
[ "Add", "adds", "the", "message", "to", "the", "cache", ".", "It", "returns", "true", "if", "successful", ".", "If", "the", "message", "is", "already", "present", "it", "still", "returns", "true", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L372-L389
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
purge
func purge(tsv TabletService, name string, purgeAfter, purgeInterval time.Duration) { ctx, cancel := context.WithTimeout(tabletenv.LocalContext(), purgeInterval) defer func() { tabletenv.LogError() cancel() }() for { count, err := tsv.PurgeMessages(ctx, nil, name, time.Now().Add(-purgeAfter).UnixNano()) if err != nil { MessageStats.Add([]string{name, "PurgeFailed"}, 1) log.Errorf("Unable to delete messages: %v", err) } else { MessageStats.Add([]string{name, "Purged"}, count) } // If deleted 500 or more, we should continue. if count < 500 { return } } }
go
func purge(tsv TabletService, name string, purgeAfter, purgeInterval time.Duration) { ctx, cancel := context.WithTimeout(tabletenv.LocalContext(), purgeInterval) defer func() { tabletenv.LogError() cancel() }() for { count, err := tsv.PurgeMessages(ctx, nil, name, time.Now().Add(-purgeAfter).UnixNano()) if err != nil { MessageStats.Add([]string{name, "PurgeFailed"}, 1) log.Errorf("Unable to delete messages: %v", err) } else { MessageStats.Add([]string{name, "Purged"}, count) } // If deleted 500 or more, we should continue. if count < 500 { return } } }
[ "func", "purge", "(", "tsv", "TabletService", ",", "name", "string", ",", "purgeAfter", ",", "purgeInterval", "time", ".", "Duration", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "tabletenv", ".", "LocalContext", "(", ")", ",", "purgeInterval", ")", "\n", "defer", "func", "(", ")", "{", "tabletenv", ".", "LogError", "(", ")", "\n", "cancel", "(", ")", "\n", "}", "(", ")", "\n", "for", "{", "count", ",", "err", ":=", "tsv", ".", "PurgeMessages", "(", "ctx", ",", "nil", ",", "name", ",", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "purgeAfter", ")", ".", "UnixNano", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "MessageStats", ".", "Add", "(", "[", "]", "string", "{", "name", ",", "\"", "\"", "}", ",", "1", ")", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "MessageStats", ".", "Add", "(", "[", "]", "string", "{", "name", ",", "\"", "\"", "}", ",", "count", ")", "\n", "}", "\n", "// If deleted 500 or more, we should continue.", "if", "count", "<", "500", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// purge is a non-member because it should be called asynchronously and should // not rely on members of messageManager.
[ "purge", "is", "a", "non", "-", "member", "because", "it", "should", "be", "called", "asynchronously", "and", "should", "not", "rely", "on", "members", "of", "messageManager", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L614-L633
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/message_manager.go
BuildMessageRow
func BuildMessageRow(row []sqltypes.Value) (*MessageRow, error) { timeNext, err := sqltypes.ToInt64(row[0]) if err != nil { return nil, err } epoch, err := sqltypes.ToInt64(row[1]) if err != nil { return nil, err } timeCreated, err := sqltypes.ToInt64(row[2]) if err != nil { return nil, err } return &MessageRow{ TimeNext: timeNext, Epoch: epoch, TimeCreated: timeCreated, Row: row[3:], }, nil }
go
func BuildMessageRow(row []sqltypes.Value) (*MessageRow, error) { timeNext, err := sqltypes.ToInt64(row[0]) if err != nil { return nil, err } epoch, err := sqltypes.ToInt64(row[1]) if err != nil { return nil, err } timeCreated, err := sqltypes.ToInt64(row[2]) if err != nil { return nil, err } return &MessageRow{ TimeNext: timeNext, Epoch: epoch, TimeCreated: timeCreated, Row: row[3:], }, nil }
[ "func", "BuildMessageRow", "(", "row", "[", "]", "sqltypes", ".", "Value", ")", "(", "*", "MessageRow", ",", "error", ")", "{", "timeNext", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "epoch", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "timeCreated", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "row", "[", "2", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "MessageRow", "{", "TimeNext", ":", "timeNext", ",", "Epoch", ":", "epoch", ",", "TimeCreated", ":", "timeCreated", ",", "Row", ":", "row", "[", "3", ":", "]", ",", "}", ",", "nil", "\n", "}" ]
// BuildMessageRow builds a MessageRow for a db row.
[ "BuildMessageRow", "builds", "a", "MessageRow", "for", "a", "db", "row", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/message_manager.go#L680-L699
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Equal
func (qrs *Rules) Equal(other *Rules) bool { if len(qrs.rules) != len(other.rules) { return false } for i := 0; i < len(qrs.rules); i++ { if !qrs.rules[i].Equal(other.rules[i]) { return false } } return true }
go
func (qrs *Rules) Equal(other *Rules) bool { if len(qrs.rules) != len(other.rules) { return false } for i := 0; i < len(qrs.rules); i++ { if !qrs.rules[i].Equal(other.rules[i]) { return false } } return true }
[ "func", "(", "qrs", "*", "Rules", ")", "Equal", "(", "other", "*", "Rules", ")", "bool", "{", "if", "len", "(", "qrs", ".", "rules", ")", "!=", "len", "(", "other", ".", "rules", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "qrs", ".", "rules", ")", ";", "i", "++", "{", "if", "!", "qrs", ".", "rules", "[", "i", "]", ".", "Equal", "(", "other", ".", "rules", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equal returns true if other is equal to this object, otherwise false.
[ "Equal", "returns", "true", "if", "other", "is", "equal", "to", "this", "object", "otherwise", "false", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L48-L58
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Copy
func (qrs *Rules) Copy() (newqrs *Rules) { newqrs = New() if qrs.rules != nil { newqrs.rules = make([]*Rule, 0, len(qrs.rules)) for _, qr := range qrs.rules { newqrs.rules = append(newqrs.rules, qr.Copy()) } } return newqrs }
go
func (qrs *Rules) Copy() (newqrs *Rules) { newqrs = New() if qrs.rules != nil { newqrs.rules = make([]*Rule, 0, len(qrs.rules)) for _, qr := range qrs.rules { newqrs.rules = append(newqrs.rules, qr.Copy()) } } return newqrs }
[ "func", "(", "qrs", "*", "Rules", ")", "Copy", "(", ")", "(", "newqrs", "*", "Rules", ")", "{", "newqrs", "=", "New", "(", ")", "\n", "if", "qrs", ".", "rules", "!=", "nil", "{", "newqrs", ".", "rules", "=", "make", "(", "[", "]", "*", "Rule", ",", "0", ",", "len", "(", "qrs", ".", "rules", ")", ")", "\n", "for", "_", ",", "qr", ":=", "range", "qrs", ".", "rules", "{", "newqrs", ".", "rules", "=", "append", "(", "newqrs", ".", "rules", ",", "qr", ".", "Copy", "(", ")", ")", "\n", "}", "\n", "}", "\n", "return", "newqrs", "\n", "}" ]
// Copy performs a deep copy of Rules. // A nil input produces a nil output.
[ "Copy", "performs", "a", "deep", "copy", "of", "Rules", ".", "A", "nil", "input", "produces", "a", "nil", "output", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L62-L71
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Append
func (qrs *Rules) Append(otherqrs *Rules) { qrs.rules = append(qrs.rules, otherqrs.rules...) }
go
func (qrs *Rules) Append(otherqrs *Rules) { qrs.rules = append(qrs.rules, otherqrs.rules...) }
[ "func", "(", "qrs", "*", "Rules", ")", "Append", "(", "otherqrs", "*", "Rules", ")", "{", "qrs", ".", "rules", "=", "append", "(", "qrs", ".", "rules", ",", "otherqrs", ".", "rules", "...", ")", "\n", "}" ]
// Append merges the rules from another Rules into the receiver
[ "Append", "merges", "the", "rules", "from", "another", "Rules", "into", "the", "receiver" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L74-L76
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Add
func (qrs *Rules) Add(qr *Rule) { qrs.rules = append(qrs.rules, qr) }
go
func (qrs *Rules) Add(qr *Rule) { qrs.rules = append(qrs.rules, qr) }
[ "func", "(", "qrs", "*", "Rules", ")", "Add", "(", "qr", "*", "Rule", ")", "{", "qrs", ".", "rules", "=", "append", "(", "qrs", ".", "rules", ",", "qr", ")", "\n", "}" ]
// Add adds a Rule to Rules. It does not check // for duplicates.
[ "Add", "adds", "a", "Rule", "to", "Rules", ".", "It", "does", "not", "check", "for", "duplicates", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L80-L82
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Find
func (qrs *Rules) Find(name string) (qr *Rule) { for _, qr = range qrs.rules { if qr.Name == name { return qr } } return nil }
go
func (qrs *Rules) Find(name string) (qr *Rule) { for _, qr = range qrs.rules { if qr.Name == name { return qr } } return nil }
[ "func", "(", "qrs", "*", "Rules", ")", "Find", "(", "name", "string", ")", "(", "qr", "*", "Rule", ")", "{", "for", "_", ",", "qr", "=", "range", "qrs", ".", "rules", "{", "if", "qr", ".", "Name", "==", "name", "{", "return", "qr", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Find finds the first occurrence of a Rule by matching // the Name field. It returns nil if the rule was not found.
[ "Find", "finds", "the", "first", "occurrence", "of", "a", "Rule", "by", "matching", "the", "Name", "field", ".", "It", "returns", "nil", "if", "the", "rule", "was", "not", "found", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L86-L93
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Delete
func (qrs *Rules) Delete(name string) (qr *Rule) { for i, qr := range qrs.rules { if qr.Name == name { for j := i; j < len(qrs.rules)-i-1; j++ { qrs.rules[j] = qrs.rules[j+1] } qrs.rules = qrs.rules[:len(qrs.rules)-1] return qr } } return nil }
go
func (qrs *Rules) Delete(name string) (qr *Rule) { for i, qr := range qrs.rules { if qr.Name == name { for j := i; j < len(qrs.rules)-i-1; j++ { qrs.rules[j] = qrs.rules[j+1] } qrs.rules = qrs.rules[:len(qrs.rules)-1] return qr } } return nil }
[ "func", "(", "qrs", "*", "Rules", ")", "Delete", "(", "name", "string", ")", "(", "qr", "*", "Rule", ")", "{", "for", "i", ",", "qr", ":=", "range", "qrs", ".", "rules", "{", "if", "qr", ".", "Name", "==", "name", "{", "for", "j", ":=", "i", ";", "j", "<", "len", "(", "qrs", ".", "rules", ")", "-", "i", "-", "1", ";", "j", "++", "{", "qrs", ".", "rules", "[", "j", "]", "=", "qrs", ".", "rules", "[", "j", "+", "1", "]", "\n", "}", "\n", "qrs", ".", "rules", "=", "qrs", ".", "rules", "[", ":", "len", "(", "qrs", ".", "rules", ")", "-", "1", "]", "\n", "return", "qr", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Delete deletes a Rule by name and returns the rule // that was deleted. It returns nil if the rule was not found.
[ "Delete", "deletes", "a", "Rule", "by", "name", "and", "returns", "the", "rule", "that", "was", "deleted", ".", "It", "returns", "nil", "if", "the", "rule", "was", "not", "found", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L97-L108
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
UnmarshalJSON
func (qrs *Rules) UnmarshalJSON(data []byte) (err error) { var rulesInfo []map[string]interface{} dec := json.NewDecoder(bytes.NewReader(data)) dec.UseNumber() err = dec.Decode(&rulesInfo) if err != nil { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } for _, ruleInfo := range rulesInfo { qr, err := BuildQueryRule(ruleInfo) if err != nil { return err } qrs.Add(qr) } return nil }
go
func (qrs *Rules) UnmarshalJSON(data []byte) (err error) { var rulesInfo []map[string]interface{} dec := json.NewDecoder(bytes.NewReader(data)) dec.UseNumber() err = dec.Decode(&rulesInfo) if err != nil { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err) } for _, ruleInfo := range rulesInfo { qr, err := BuildQueryRule(ruleInfo) if err != nil { return err } qrs.Add(qr) } return nil }
[ "func", "(", "qrs", "*", "Rules", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "var", "rulesInfo", "[", "]", "map", "[", "string", "]", "interface", "{", "}", "\n", "dec", ":=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n", "dec", ".", "UseNumber", "(", ")", "\n", "err", "=", "dec", ".", "Decode", "(", "&", "rulesInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "ruleInfo", ":=", "range", "rulesInfo", "{", "qr", ",", "err", ":=", "BuildQueryRule", "(", "ruleInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "qrs", ".", "Add", "(", "qr", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON unmarshals Rules.
[ "UnmarshalJSON", "unmarshals", "Rules", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L111-L127
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
FilterByPlan
func (qrs *Rules) FilterByPlan(query string, planid planbuilder.PlanType, tableName string) (newqrs *Rules) { var newrules []*Rule for _, qr := range qrs.rules { if newrule := qr.FilterByPlan(query, planid, tableName); newrule != nil { newrules = append(newrules, newrule) } } return &Rules{newrules} }
go
func (qrs *Rules) FilterByPlan(query string, planid planbuilder.PlanType, tableName string) (newqrs *Rules) { var newrules []*Rule for _, qr := range qrs.rules { if newrule := qr.FilterByPlan(query, planid, tableName); newrule != nil { newrules = append(newrules, newrule) } } return &Rules{newrules} }
[ "func", "(", "qrs", "*", "Rules", ")", "FilterByPlan", "(", "query", "string", ",", "planid", "planbuilder", ".", "PlanType", ",", "tableName", "string", ")", "(", "newqrs", "*", "Rules", ")", "{", "var", "newrules", "[", "]", "*", "Rule", "\n", "for", "_", ",", "qr", ":=", "range", "qrs", ".", "rules", "{", "if", "newrule", ":=", "qr", ".", "FilterByPlan", "(", "query", ",", "planid", ",", "tableName", ")", ";", "newrule", "!=", "nil", "{", "newrules", "=", "append", "(", "newrules", ",", "newrule", ")", "\n", "}", "\n", "}", "\n", "return", "&", "Rules", "{", "newrules", "}", "\n", "}" ]
// FilterByPlan creates a new Rules by prefiltering on the query and planId. This allows // us to create query plan specific Rules out of the original Rules. In the new rules, // query, plans and tableNames predicates are empty.
[ "FilterByPlan", "creates", "a", "new", "Rules", "by", "prefiltering", "on", "the", "query", "and", "planId", ".", "This", "allows", "us", "to", "create", "query", "plan", "specific", "Rules", "out", "of", "the", "original", "Rules", ".", "In", "the", "new", "rules", "query", "plans", "and", "tableNames", "predicates", "are", "empty", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L146-L154
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
GetAction
func (qrs *Rules) GetAction(ip, user string, bindVars map[string]*querypb.BindVariable) (action Action, desc string) { for _, qr := range qrs.rules { if act := qr.GetAction(ip, user, bindVars); act != QRContinue { return act, qr.Description } } return QRContinue, "" }
go
func (qrs *Rules) GetAction(ip, user string, bindVars map[string]*querypb.BindVariable) (action Action, desc string) { for _, qr := range qrs.rules { if act := qr.GetAction(ip, user, bindVars); act != QRContinue { return act, qr.Description } } return QRContinue, "" }
[ "func", "(", "qrs", "*", "Rules", ")", "GetAction", "(", "ip", ",", "user", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "action", "Action", ",", "desc", "string", ")", "{", "for", "_", ",", "qr", ":=", "range", "qrs", ".", "rules", "{", "if", "act", ":=", "qr", ".", "GetAction", "(", "ip", ",", "user", ",", "bindVars", ")", ";", "act", "!=", "QRContinue", "{", "return", "act", ",", "qr", ".", "Description", "\n", "}", "\n", "}", "\n", "return", "QRContinue", ",", "\"", "\"", "\n", "}" ]
// GetAction runs the input against the rules engine and returns the action to be performed.
[ "GetAction", "runs", "the", "input", "against", "the", "rules", "engine", "and", "returns", "the", "action", "to", "be", "performed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L157-L164
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Equal
func (nr namedRegexp) Equal(other namedRegexp) bool { if nr.Regexp == nil || other.Regexp == nil { return nr.Regexp == nil && other.Regexp == nil && nr.name == other.name } return nr.name == other.name && nr.String() == other.String() }
go
func (nr namedRegexp) Equal(other namedRegexp) bool { if nr.Regexp == nil || other.Regexp == nil { return nr.Regexp == nil && other.Regexp == nil && nr.name == other.name } return nr.name == other.name && nr.String() == other.String() }
[ "func", "(", "nr", "namedRegexp", ")", "Equal", "(", "other", "namedRegexp", ")", "bool", "{", "if", "nr", ".", "Regexp", "==", "nil", "||", "other", ".", "Regexp", "==", "nil", "{", "return", "nr", ".", "Regexp", "==", "nil", "&&", "other", ".", "Regexp", "==", "nil", "&&", "nr", ".", "name", "==", "other", ".", "name", "\n", "}", "\n", "return", "nr", ".", "name", "==", "other", ".", "name", "&&", "nr", ".", "String", "(", ")", "==", "other", ".", "String", "(", ")", "\n", "}" ]
// Equal returns true if other is equal to this namedRegexp, otherwise false.
[ "Equal", "returns", "true", "if", "other", "is", "equal", "to", "this", "namedRegexp", "otherwise", "false", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L209-L214
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
NewQueryRule
func NewQueryRule(description, name string, act Action) (qr *Rule) { // We ignore act because there's only one action right now return &Rule{Description: description, Name: name, act: act} }
go
func NewQueryRule(description, name string, act Action) (qr *Rule) { // We ignore act because there's only one action right now return &Rule{Description: description, Name: name, act: act} }
[ "func", "NewQueryRule", "(", "description", ",", "name", "string", ",", "act", "Action", ")", "(", "qr", "*", "Rule", ")", "{", "// We ignore act because there's only one action right now", "return", "&", "Rule", "{", "Description", ":", "description", ",", "Name", ":", "name", ",", "act", ":", "act", "}", "\n", "}" ]
// NewQueryRule creates a new Rule.
[ "NewQueryRule", "creates", "a", "new", "Rule", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L217-L220
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Equal
func (qr *Rule) Equal(other *Rule) bool { if qr == nil || other == nil { return qr == nil && other == nil } return (qr.Description == other.Description && qr.Name == other.Name && qr.requestIP.Equal(other.requestIP) && qr.user.Equal(other.user) && qr.query.Equal(other.query) && reflect.DeepEqual(qr.plans, other.plans) && reflect.DeepEqual(qr.tableNames, other.tableNames) && reflect.DeepEqual(qr.bindVarConds, other.bindVarConds) && qr.act == other.act) }
go
func (qr *Rule) Equal(other *Rule) bool { if qr == nil || other == nil { return qr == nil && other == nil } return (qr.Description == other.Description && qr.Name == other.Name && qr.requestIP.Equal(other.requestIP) && qr.user.Equal(other.user) && qr.query.Equal(other.query) && reflect.DeepEqual(qr.plans, other.plans) && reflect.DeepEqual(qr.tableNames, other.tableNames) && reflect.DeepEqual(qr.bindVarConds, other.bindVarConds) && qr.act == other.act) }
[ "func", "(", "qr", "*", "Rule", ")", "Equal", "(", "other", "*", "Rule", ")", "bool", "{", "if", "qr", "==", "nil", "||", "other", "==", "nil", "{", "return", "qr", "==", "nil", "&&", "other", "==", "nil", "\n", "}", "\n", "return", "(", "qr", ".", "Description", "==", "other", ".", "Description", "&&", "qr", ".", "Name", "==", "other", ".", "Name", "&&", "qr", ".", "requestIP", ".", "Equal", "(", "other", ".", "requestIP", ")", "&&", "qr", ".", "user", ".", "Equal", "(", "other", ".", "user", ")", "&&", "qr", ".", "query", ".", "Equal", "(", "other", ".", "query", ")", "&&", "reflect", ".", "DeepEqual", "(", "qr", ".", "plans", ",", "other", ".", "plans", ")", "&&", "reflect", ".", "DeepEqual", "(", "qr", ".", "tableNames", ",", "other", ".", "tableNames", ")", "&&", "reflect", ".", "DeepEqual", "(", "qr", ".", "bindVarConds", ",", "other", ".", "bindVarConds", ")", "&&", "qr", ".", "act", "==", "other", ".", "act", ")", "\n", "}" ]
// Equal returns true if other is equal to this Rule, otherwise false.
[ "Equal", "returns", "true", "if", "other", "is", "equal", "to", "this", "Rule", "otherwise", "false", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L223-L236
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
Copy
func (qr *Rule) Copy() (newqr *Rule) { newqr = &Rule{ Description: qr.Description, Name: qr.Name, requestIP: qr.requestIP, user: qr.user, query: qr.query, act: qr.act, } if qr.plans != nil { newqr.plans = make([]planbuilder.PlanType, len(qr.plans)) copy(newqr.plans, qr.plans) } if qr.tableNames != nil { newqr.tableNames = make([]string, len(qr.tableNames)) copy(newqr.tableNames, qr.tableNames) } if qr.bindVarConds != nil { newqr.bindVarConds = make([]BindVarCond, len(qr.bindVarConds)) copy(newqr.bindVarConds, qr.bindVarConds) } return newqr }
go
func (qr *Rule) Copy() (newqr *Rule) { newqr = &Rule{ Description: qr.Description, Name: qr.Name, requestIP: qr.requestIP, user: qr.user, query: qr.query, act: qr.act, } if qr.plans != nil { newqr.plans = make([]planbuilder.PlanType, len(qr.plans)) copy(newqr.plans, qr.plans) } if qr.tableNames != nil { newqr.tableNames = make([]string, len(qr.tableNames)) copy(newqr.tableNames, qr.tableNames) } if qr.bindVarConds != nil { newqr.bindVarConds = make([]BindVarCond, len(qr.bindVarConds)) copy(newqr.bindVarConds, qr.bindVarConds) } return newqr }
[ "func", "(", "qr", "*", "Rule", ")", "Copy", "(", ")", "(", "newqr", "*", "Rule", ")", "{", "newqr", "=", "&", "Rule", "{", "Description", ":", "qr", ".", "Description", ",", "Name", ":", "qr", ".", "Name", ",", "requestIP", ":", "qr", ".", "requestIP", ",", "user", ":", "qr", ".", "user", ",", "query", ":", "qr", ".", "query", ",", "act", ":", "qr", ".", "act", ",", "}", "\n", "if", "qr", ".", "plans", "!=", "nil", "{", "newqr", ".", "plans", "=", "make", "(", "[", "]", "planbuilder", ".", "PlanType", ",", "len", "(", "qr", ".", "plans", ")", ")", "\n", "copy", "(", "newqr", ".", "plans", ",", "qr", ".", "plans", ")", "\n", "}", "\n", "if", "qr", ".", "tableNames", "!=", "nil", "{", "newqr", ".", "tableNames", "=", "make", "(", "[", "]", "string", ",", "len", "(", "qr", ".", "tableNames", ")", ")", "\n", "copy", "(", "newqr", ".", "tableNames", ",", "qr", ".", "tableNames", ")", "\n", "}", "\n", "if", "qr", ".", "bindVarConds", "!=", "nil", "{", "newqr", ".", "bindVarConds", "=", "make", "(", "[", "]", "BindVarCond", ",", "len", "(", "qr", ".", "bindVarConds", ")", ")", "\n", "copy", "(", "newqr", ".", "bindVarConds", ",", "qr", ".", "bindVarConds", ")", "\n", "}", "\n", "return", "newqr", "\n", "}" ]
// Copy performs a deep copy of a Rule.
[ "Copy", "performs", "a", "deep", "copy", "of", "a", "Rule", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L239-L261
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
SetUserCond
func (qr *Rule) SetUserCond(pattern string) (err error) { qr.user.name = pattern qr.user.Regexp, err = regexp.Compile(makeExact(pattern)) return }
go
func (qr *Rule) SetUserCond(pattern string) (err error) { qr.user.name = pattern qr.user.Regexp, err = regexp.Compile(makeExact(pattern)) return }
[ "func", "(", "qr", "*", "Rule", ")", "SetUserCond", "(", "pattern", "string", ")", "(", "err", "error", ")", "{", "qr", ".", "user", ".", "name", "=", "pattern", "\n", "qr", ".", "user", ".", "Regexp", ",", "err", "=", "regexp", ".", "Compile", "(", "makeExact", "(", "pattern", ")", ")", "\n", "return", "\n", "}" ]
// SetUserCond adds a regular expression condition for the user name // used by the client.
[ "SetUserCond", "adds", "a", "regular", "expression", "condition", "for", "the", "user", "name", "used", "by", "the", "client", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L303-L307
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
SetQueryCond
func (qr *Rule) SetQueryCond(pattern string) (err error) { qr.query.name = pattern qr.query.Regexp, err = regexp.Compile(makeExact(pattern)) return }
go
func (qr *Rule) SetQueryCond(pattern string) (err error) { qr.query.name = pattern qr.query.Regexp, err = regexp.Compile(makeExact(pattern)) return }
[ "func", "(", "qr", "*", "Rule", ")", "SetQueryCond", "(", "pattern", "string", ")", "(", "err", "error", ")", "{", "qr", ".", "query", ".", "name", "=", "pattern", "\n", "qr", ".", "query", ".", "Regexp", ",", "err", "=", "regexp", ".", "Compile", "(", "makeExact", "(", "pattern", ")", ")", "\n", "return", "\n", "}" ]
// SetQueryCond adds a regular expression condition for the query.
[ "SetQueryCond", "adds", "a", "regular", "expression", "condition", "for", "the", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L324-L328
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
FilterByPlan
func (qr *Rule) FilterByPlan(query string, planid planbuilder.PlanType, tableName string) (newqr *Rule) { if !reMatch(qr.query.Regexp, query) { return nil } if !planMatch(qr.plans, planid) { return nil } if !tableMatch(qr.tableNames, tableName) { return nil } newqr = qr.Copy() newqr.query = namedRegexp{} newqr.plans = nil newqr.tableNames = nil return newqr }
go
func (qr *Rule) FilterByPlan(query string, planid planbuilder.PlanType, tableName string) (newqr *Rule) { if !reMatch(qr.query.Regexp, query) { return nil } if !planMatch(qr.plans, planid) { return nil } if !tableMatch(qr.tableNames, tableName) { return nil } newqr = qr.Copy() newqr.query = namedRegexp{} newqr.plans = nil newqr.tableNames = nil return newqr }
[ "func", "(", "qr", "*", "Rule", ")", "FilterByPlan", "(", "query", "string", ",", "planid", "planbuilder", ".", "PlanType", ",", "tableName", "string", ")", "(", "newqr", "*", "Rule", ")", "{", "if", "!", "reMatch", "(", "qr", ".", "query", ".", "Regexp", ",", "query", ")", "{", "return", "nil", "\n", "}", "\n", "if", "!", "planMatch", "(", "qr", ".", "plans", ",", "planid", ")", "{", "return", "nil", "\n", "}", "\n", "if", "!", "tableMatch", "(", "qr", ".", "tableNames", ",", "tableName", ")", "{", "return", "nil", "\n", "}", "\n", "newqr", "=", "qr", ".", "Copy", "(", ")", "\n", "newqr", ".", "query", "=", "namedRegexp", "{", "}", "\n", "newqr", ".", "plans", "=", "nil", "\n", "newqr", ".", "tableNames", "=", "nil", "\n", "return", "newqr", "\n", "}" ]
// FilterByPlan returns a new Rule if the query and planid match. // The new Rule will contain all the original constraints other // than the plan and query. If the plan and query don't match the Rule, // then it returns nil.
[ "FilterByPlan", "returns", "a", "new", "Rule", "if", "the", "query", "and", "planid", "match", ".", "The", "new", "Rule", "will", "contain", "all", "the", "original", "constraints", "other", "than", "the", "plan", "and", "query", ".", "If", "the", "plan", "and", "query", "don", "t", "match", "the", "Rule", "then", "it", "returns", "nil", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L397-L412
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
GetAction
func (qr *Rule) GetAction(ip, user string, bindVars map[string]*querypb.BindVariable) Action { if !reMatch(qr.requestIP.Regexp, ip) { return QRContinue } if !reMatch(qr.user.Regexp, user) { return QRContinue } for _, bvcond := range qr.bindVarConds { if !bvMatch(bvcond, bindVars) { return QRContinue } } return qr.act }
go
func (qr *Rule) GetAction(ip, user string, bindVars map[string]*querypb.BindVariable) Action { if !reMatch(qr.requestIP.Regexp, ip) { return QRContinue } if !reMatch(qr.user.Regexp, user) { return QRContinue } for _, bvcond := range qr.bindVarConds { if !bvMatch(bvcond, bindVars) { return QRContinue } } return qr.act }
[ "func", "(", "qr", "*", "Rule", ")", "GetAction", "(", "ip", ",", "user", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "Action", "{", "if", "!", "reMatch", "(", "qr", ".", "requestIP", ".", "Regexp", ",", "ip", ")", "{", "return", "QRContinue", "\n", "}", "\n", "if", "!", "reMatch", "(", "qr", ".", "user", ".", "Regexp", ",", "user", ")", "{", "return", "QRContinue", "\n", "}", "\n", "for", "_", ",", "bvcond", ":=", "range", "qr", ".", "bindVarConds", "{", "if", "!", "bvMatch", "(", "bvcond", ",", "bindVars", ")", "{", "return", "QRContinue", "\n", "}", "\n", "}", "\n", "return", "qr", ".", "act", "\n", "}" ]
// GetAction returns the action for a single rule.
[ "GetAction", "returns", "the", "action", "for", "a", "single", "rule", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L415-L428
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
getuint64
func getuint64(val *querypb.BindVariable) (uv uint64, status int) { bv, err := sqltypes.BindVariableToValue(val) if err != nil { return 0, QROutOfRange } v, err := sqltypes.ToUint64(bv) if err != nil { return 0, QROutOfRange } return v, QROK }
go
func getuint64(val *querypb.BindVariable) (uv uint64, status int) { bv, err := sqltypes.BindVariableToValue(val) if err != nil { return 0, QROutOfRange } v, err := sqltypes.ToUint64(bv) if err != nil { return 0, QROutOfRange } return v, QROK }
[ "func", "getuint64", "(", "val", "*", "querypb", ".", "BindVariable", ")", "(", "uv", "uint64", ",", "status", "int", ")", "{", "bv", ",", "err", ":=", "sqltypes", ".", "BindVariableToValue", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "QROutOfRange", "\n", "}", "\n", "v", ",", "err", ":=", "sqltypes", ".", "ToUint64", "(", "bv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "QROutOfRange", "\n", "}", "\n", "return", "v", ",", "QROK", "\n", "}" ]
// getuint64 returns QROutOfRange for negative values
[ "getuint64", "returns", "QROutOfRange", "for", "negative", "values" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L730-L740
train
vitessio/vitess
go/vt/vttablet/tabletserver/rules/rules.go
getint64
func getint64(val *querypb.BindVariable) (iv int64, status int) { bv, err := sqltypes.BindVariableToValue(val) if err != nil { return 0, QROutOfRange } v, err := sqltypes.ToInt64(bv) if err != nil { return 0, QROutOfRange } return v, QROK }
go
func getint64(val *querypb.BindVariable) (iv int64, status int) { bv, err := sqltypes.BindVariableToValue(val) if err != nil { return 0, QROutOfRange } v, err := sqltypes.ToInt64(bv) if err != nil { return 0, QROutOfRange } return v, QROK }
[ "func", "getint64", "(", "val", "*", "querypb", ".", "BindVariable", ")", "(", "iv", "int64", ",", "status", "int", ")", "{", "bv", ",", "err", ":=", "sqltypes", ".", "BindVariableToValue", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "QROutOfRange", "\n", "}", "\n", "v", ",", "err", ":=", "sqltypes", ".", "ToInt64", "(", "bv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "QROutOfRange", "\n", "}", "\n", "return", "v", ",", "QROK", "\n", "}" ]
// getint64 returns QROutOfRange if a uint64 is too large
[ "getint64", "returns", "QROutOfRange", "if", "a", "uint64", "is", "too", "large" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/rules/rules.go#L743-L753
train
vitessio/vitess
go/vt/vtaclcheck/vtaclcheck.go
Run
func Run() error { if options.ACLFile != "" { tableacl.Register("simpleacl", &simpleacl.Factory{}) err := tableacl.Init( options.ACLFile, func() {}, ) if err != nil { return fmt.Errorf("fail to initialize Table ACL: %v", err) } fmt.Printf("JSON ACL file %s looks good\n", options.ACLFile) } if options.StaticAuthFile != "" { mysql.RegisterAuthServerStaticFromParams(options.StaticAuthFile, "") fmt.Printf("Static auth file %s looks good\n", options.StaticAuthFile) } return nil }
go
func Run() error { if options.ACLFile != "" { tableacl.Register("simpleacl", &simpleacl.Factory{}) err := tableacl.Init( options.ACLFile, func() {}, ) if err != nil { return fmt.Errorf("fail to initialize Table ACL: %v", err) } fmt.Printf("JSON ACL file %s looks good\n", options.ACLFile) } if options.StaticAuthFile != "" { mysql.RegisterAuthServerStaticFromParams(options.StaticAuthFile, "") fmt.Printf("Static auth file %s looks good\n", options.StaticAuthFile) } return nil }
[ "func", "Run", "(", ")", "error", "{", "if", "options", ".", "ACLFile", "!=", "\"", "\"", "{", "tableacl", ".", "Register", "(", "\"", "\"", ",", "&", "simpleacl", ".", "Factory", "{", "}", ")", "\n", "err", ":=", "tableacl", ".", "Init", "(", "options", ".", "ACLFile", ",", "func", "(", ")", "{", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "options", ".", "ACLFile", ")", "\n", "}", "\n\n", "if", "options", ".", "StaticAuthFile", "!=", "\"", "\"", "{", "mysql", ".", "RegisterAuthServerStaticFromParams", "(", "options", ".", "StaticAuthFile", ",", "\"", "\"", ")", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "options", ".", "StaticAuthFile", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Run the check on the given file
[ "Run", "the", "check", "on", "the", "given", "file" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtaclcheck/vtaclcheck.go#L57-L78
train
vitessio/vitess
go/vt/topo/helpers/copy.go
CopyKeyspaces
func CopyKeyspaces(ctx context.Context, fromTS, toTS *topo.Server) { keyspaces, err := fromTS.GetKeyspaces(ctx) if err != nil { log.Fatalf("GetKeyspaces: %v", err) } for _, keyspace := range keyspaces { ki, err := fromTS.GetKeyspace(ctx, keyspace) if err != nil { log.Fatalf("GetKeyspace(%v): %v", keyspace, err) } if err := toTS.CreateKeyspace(ctx, keyspace, ki.Keyspace); err != nil { if topo.IsErrType(err, topo.NodeExists) { log.Warningf("keyspace %v already exists", keyspace) } else { log.Errorf("CreateKeyspace(%v): %v", keyspace, err) } } vs, err := fromTS.GetVSchema(ctx, keyspace) switch { case err == nil: if err := toTS.SaveVSchema(ctx, keyspace, vs); err != nil { log.Errorf("SaveVSchema(%v): %v", keyspace, err) } case topo.IsErrType(err, topo.NoNode): // Nothing to do. default: log.Errorf("GetVSchema(%v): %v", keyspace, err) } } }
go
func CopyKeyspaces(ctx context.Context, fromTS, toTS *topo.Server) { keyspaces, err := fromTS.GetKeyspaces(ctx) if err != nil { log.Fatalf("GetKeyspaces: %v", err) } for _, keyspace := range keyspaces { ki, err := fromTS.GetKeyspace(ctx, keyspace) if err != nil { log.Fatalf("GetKeyspace(%v): %v", keyspace, err) } if err := toTS.CreateKeyspace(ctx, keyspace, ki.Keyspace); err != nil { if topo.IsErrType(err, topo.NodeExists) { log.Warningf("keyspace %v already exists", keyspace) } else { log.Errorf("CreateKeyspace(%v): %v", keyspace, err) } } vs, err := fromTS.GetVSchema(ctx, keyspace) switch { case err == nil: if err := toTS.SaveVSchema(ctx, keyspace, vs); err != nil { log.Errorf("SaveVSchema(%v): %v", keyspace, err) } case topo.IsErrType(err, topo.NoNode): // Nothing to do. default: log.Errorf("GetVSchema(%v): %v", keyspace, err) } } }
[ "func", "CopyKeyspaces", "(", "ctx", "context", ".", "Context", ",", "fromTS", ",", "toTS", "*", "topo", ".", "Server", ")", "{", "keyspaces", ",", "err", ":=", "fromTS", ".", "GetKeyspaces", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "keyspace", ":=", "range", "keyspaces", "{", "ki", ",", "err", ":=", "fromTS", ".", "GetKeyspace", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "keyspace", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "toTS", ".", "CreateKeyspace", "(", "ctx", ",", "keyspace", ",", "ki", ".", "Keyspace", ")", ";", "err", "!=", "nil", "{", "if", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NodeExists", ")", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "keyspace", ")", "\n", "}", "else", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "vs", ",", "err", ":=", "fromTS", ".", "GetVSchema", "(", "ctx", ",", "keyspace", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "if", "err", ":=", "toTS", ".", "SaveVSchema", "(", "ctx", ",", "keyspace", ",", "vs", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "err", ")", "\n", "}", "\n", "case", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NoNode", ")", ":", "// Nothing to do.", "default", ":", "log", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// CopyKeyspaces will create the keyspaces in the destination topo.
[ "CopyKeyspaces", "will", "create", "the", "keyspaces", "in", "the", "destination", "topo", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/copy.go#L30-L63
train
vitessio/vitess
go/vt/topo/helpers/copy.go
CopyShards
func CopyShards(ctx context.Context, fromTS, toTS *topo.Server) { keyspaces, err := fromTS.GetKeyspaces(ctx) if err != nil { log.Fatalf("fromTS.GetKeyspaces: %v", err) } for _, keyspace := range keyspaces { shards, err := fromTS.GetShardNames(ctx, keyspace) if err != nil { log.Fatalf("GetShardNames(%v): %v", keyspace, err) return } for _, shard := range shards { si, err := fromTS.GetShard(ctx, keyspace, shard) if err != nil { log.Fatalf("GetShard(%v, %v): %v", keyspace, shard, err) } if err := toTS.CreateShard(ctx, keyspace, shard); err != nil { if topo.IsErrType(err, topo.NodeExists) { log.Warningf("shard %v/%v already exists", keyspace, shard) } else { log.Fatalf("CreateShard(%v, %v): %v", keyspace, shard, err) } } if _, err := toTS.UpdateShardFields(ctx, keyspace, shard, func(toSI *topo.ShardInfo) error { *toSI.Shard = *si.Shard return nil }); err != nil { log.Fatalf("UpdateShardFields(%v, %v): %v", keyspace, shard, err) } } } }
go
func CopyShards(ctx context.Context, fromTS, toTS *topo.Server) { keyspaces, err := fromTS.GetKeyspaces(ctx) if err != nil { log.Fatalf("fromTS.GetKeyspaces: %v", err) } for _, keyspace := range keyspaces { shards, err := fromTS.GetShardNames(ctx, keyspace) if err != nil { log.Fatalf("GetShardNames(%v): %v", keyspace, err) return } for _, shard := range shards { si, err := fromTS.GetShard(ctx, keyspace, shard) if err != nil { log.Fatalf("GetShard(%v, %v): %v", keyspace, shard, err) } if err := toTS.CreateShard(ctx, keyspace, shard); err != nil { if topo.IsErrType(err, topo.NodeExists) { log.Warningf("shard %v/%v already exists", keyspace, shard) } else { log.Fatalf("CreateShard(%v, %v): %v", keyspace, shard, err) } } if _, err := toTS.UpdateShardFields(ctx, keyspace, shard, func(toSI *topo.ShardInfo) error { *toSI.Shard = *si.Shard return nil }); err != nil { log.Fatalf("UpdateShardFields(%v, %v): %v", keyspace, shard, err) } } } }
[ "func", "CopyShards", "(", "ctx", "context", ".", "Context", ",", "fromTS", ",", "toTS", "*", "topo", ".", "Server", ")", "{", "keyspaces", ",", "err", ":=", "fromTS", ".", "GetKeyspaces", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "keyspace", ":=", "range", "keyspaces", "{", "shards", ",", "err", ":=", "fromTS", ".", "GetShardNames", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "keyspace", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "for", "_", ",", "shard", ":=", "range", "shards", "{", "si", ",", "err", ":=", "fromTS", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "toTS", ".", "CreateShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", ";", "err", "!=", "nil", "{", "if", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NodeExists", ")", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "}", "else", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "_", ",", "err", ":=", "toTS", ".", "UpdateShardFields", "(", "ctx", ",", "keyspace", ",", "shard", ",", "func", "(", "toSI", "*", "topo", ".", "ShardInfo", ")", "error", "{", "*", "toSI", ".", "Shard", "=", "*", "si", ".", "Shard", "\n", "return", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// CopyShards will create the shards in the destination topo.
[ "CopyShards", "will", "create", "the", "shards", "in", "the", "destination", "topo", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/copy.go#L66-L101
train
vitessio/vitess
go/vt/topo/helpers/copy.go
CopyTablets
func CopyTablets(ctx context.Context, fromTS, toTS *topo.Server) { cells, err := fromTS.GetKnownCells(ctx) if err != nil { log.Fatalf("fromTS.GetKnownCells: %v", err) } for _, cell := range cells { tabletAliases, err := fromTS.GetTabletsByCell(ctx, cell) if err != nil { log.Fatalf("GetTabletsByCell(%v): %v", cell, err) } else { for _, tabletAlias := range tabletAliases { // read the source tablet ti, err := fromTS.GetTablet(ctx, tabletAlias) if err != nil { log.Fatalf("GetTablet(%v): %v", tabletAlias, err) } // try to create the destination err = toTS.CreateTablet(ctx, ti.Tablet) if topo.IsErrType(err, topo.NodeExists) { // update the destination tablet log.Warningf("tablet %v already exists, updating it", tabletAlias) _, err = toTS.UpdateTabletFields(ctx, tabletAlias, func(t *topodatapb.Tablet) error { *t = *ti.Tablet return nil }) } if err != nil { log.Fatalf("CreateTablet(%v): %v", tabletAlias, err) } } } } }
go
func CopyTablets(ctx context.Context, fromTS, toTS *topo.Server) { cells, err := fromTS.GetKnownCells(ctx) if err != nil { log.Fatalf("fromTS.GetKnownCells: %v", err) } for _, cell := range cells { tabletAliases, err := fromTS.GetTabletsByCell(ctx, cell) if err != nil { log.Fatalf("GetTabletsByCell(%v): %v", cell, err) } else { for _, tabletAlias := range tabletAliases { // read the source tablet ti, err := fromTS.GetTablet(ctx, tabletAlias) if err != nil { log.Fatalf("GetTablet(%v): %v", tabletAlias, err) } // try to create the destination err = toTS.CreateTablet(ctx, ti.Tablet) if topo.IsErrType(err, topo.NodeExists) { // update the destination tablet log.Warningf("tablet %v already exists, updating it", tabletAlias) _, err = toTS.UpdateTabletFields(ctx, tabletAlias, func(t *topodatapb.Tablet) error { *t = *ti.Tablet return nil }) } if err != nil { log.Fatalf("CreateTablet(%v): %v", tabletAlias, err) } } } } }
[ "func", "CopyTablets", "(", "ctx", "context", ".", "Context", ",", "fromTS", ",", "toTS", "*", "topo", ".", "Server", ")", "{", "cells", ",", "err", ":=", "fromTS", ".", "GetKnownCells", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "cell", ":=", "range", "cells", "{", "tabletAliases", ",", "err", ":=", "fromTS", ".", "GetTabletsByCell", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "cell", ",", "err", ")", "\n", "}", "else", "{", "for", "_", ",", "tabletAlias", ":=", "range", "tabletAliases", "{", "// read the source tablet", "ti", ",", "err", ":=", "fromTS", ".", "GetTablet", "(", "ctx", ",", "tabletAlias", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "tabletAlias", ",", "err", ")", "\n", "}", "\n\n", "// try to create the destination", "err", "=", "toTS", ".", "CreateTablet", "(", "ctx", ",", "ti", ".", "Tablet", ")", "\n", "if", "topo", ".", "IsErrType", "(", "err", ",", "topo", ".", "NodeExists", ")", "{", "// update the destination tablet", "log", ".", "Warningf", "(", "\"", "\"", ",", "tabletAlias", ")", "\n", "_", ",", "err", "=", "toTS", ".", "UpdateTabletFields", "(", "ctx", ",", "tabletAlias", ",", "func", "(", "t", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "*", "t", "=", "*", "ti", ".", "Tablet", "\n", "return", "nil", "\n", "}", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "tabletAlias", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// CopyTablets will create the tablets in the destination topo.
[ "CopyTablets", "will", "create", "the", "tablets", "in", "the", "destination", "topo", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/copy.go#L104-L139
train
vitessio/vitess
go/vt/topo/helpers/copy.go
CopyShardReplications
func CopyShardReplications(ctx context.Context, fromTS, toTS *topo.Server) { keyspaces, err := fromTS.GetKeyspaces(ctx) if err != nil { log.Fatalf("fromTS.GetKeyspaces: %v", err) } cells, err := fromTS.GetCellInfoNames(ctx) if err != nil { log.Fatalf("GetCellInfoNames(): %v", err) } for _, keyspace := range keyspaces { shards, err := fromTS.GetShardNames(ctx, keyspace) if err != nil { log.Fatalf("GetShardNames(%v): %v", keyspace, err) } for _, shard := range shards { for _, cell := range cells { sri, err := fromTS.GetShardReplication(ctx, cell, keyspace, shard) if err != nil { log.Fatalf("GetShardReplication(%v, %v, %v): %v", cell, keyspace, shard, err) continue } if err := toTS.UpdateShardReplicationFields(ctx, cell, keyspace, shard, func(oldSR *topodatapb.ShardReplication) error { *oldSR = *sri.ShardReplication return nil }); err != nil { log.Warningf("UpdateShardReplicationFields(%v, %v, %v): %v", cell, keyspace, shard, err) } } } } }
go
func CopyShardReplications(ctx context.Context, fromTS, toTS *topo.Server) { keyspaces, err := fromTS.GetKeyspaces(ctx) if err != nil { log.Fatalf("fromTS.GetKeyspaces: %v", err) } cells, err := fromTS.GetCellInfoNames(ctx) if err != nil { log.Fatalf("GetCellInfoNames(): %v", err) } for _, keyspace := range keyspaces { shards, err := fromTS.GetShardNames(ctx, keyspace) if err != nil { log.Fatalf("GetShardNames(%v): %v", keyspace, err) } for _, shard := range shards { for _, cell := range cells { sri, err := fromTS.GetShardReplication(ctx, cell, keyspace, shard) if err != nil { log.Fatalf("GetShardReplication(%v, %v, %v): %v", cell, keyspace, shard, err) continue } if err := toTS.UpdateShardReplicationFields(ctx, cell, keyspace, shard, func(oldSR *topodatapb.ShardReplication) error { *oldSR = *sri.ShardReplication return nil }); err != nil { log.Warningf("UpdateShardReplicationFields(%v, %v, %v): %v", cell, keyspace, shard, err) } } } } }
[ "func", "CopyShardReplications", "(", "ctx", "context", ".", "Context", ",", "fromTS", ",", "toTS", "*", "topo", ".", "Server", ")", "{", "keyspaces", ",", "err", ":=", "fromTS", ".", "GetKeyspaces", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "cells", ",", "err", ":=", "fromTS", ".", "GetCellInfoNames", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "keyspace", ":=", "range", "keyspaces", "{", "shards", ",", "err", ":=", "fromTS", ".", "GetShardNames", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "keyspace", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "shard", ":=", "range", "shards", "{", "for", "_", ",", "cell", ":=", "range", "cells", "{", "sri", ",", "err", ":=", "fromTS", ".", "GetShardReplication", "(", "ctx", ",", "cell", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "cell", ",", "keyspace", ",", "shard", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "if", "err", ":=", "toTS", ".", "UpdateShardReplicationFields", "(", "ctx", ",", "cell", ",", "keyspace", ",", "shard", ",", "func", "(", "oldSR", "*", "topodatapb", ".", "ShardReplication", ")", "error", "{", "*", "oldSR", "=", "*", "sri", ".", "ShardReplication", "\n", "return", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "cell", ",", "keyspace", ",", "shard", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// CopyShardReplications will create the ShardReplication objects in // the destination topo.
[ "CopyShardReplications", "will", "create", "the", "ShardReplication", "objects", "in", "the", "destination", "topo", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/copy.go#L143-L177
train