repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
vitessio/vitess | go/vt/vtgate/scatter_conn.go | NewScatterConn | func NewScatterConn(statsName string, txConn *TxConn, gw gateway.Gateway, hc discovery.HealthCheck) *ScatterConn {
tabletCallErrorCountStatsName := ""
if statsName != "" {
tabletCallErrorCountStatsName = statsName + "ErrorCount"
}
return &ScatterConn{
timings: stats.NewMultiTimings(
statsName,
"Scatter connection timings",
[]string{"Operation", "Keyspace", "ShardName", "DbType"}),
tabletCallErrorCount: stats.NewCountersWithMultiLabels(
tabletCallErrorCountStatsName,
"Error count from tablet calls in scatter conns",
[]string{"Operation", "Keyspace", "ShardName", "DbType"}),
txConn: txConn,
gateway: gw,
healthCheck: hc,
}
} | go | func NewScatterConn(statsName string, txConn *TxConn, gw gateway.Gateway, hc discovery.HealthCheck) *ScatterConn {
tabletCallErrorCountStatsName := ""
if statsName != "" {
tabletCallErrorCountStatsName = statsName + "ErrorCount"
}
return &ScatterConn{
timings: stats.NewMultiTimings(
statsName,
"Scatter connection timings",
[]string{"Operation", "Keyspace", "ShardName", "DbType"}),
tabletCallErrorCount: stats.NewCountersWithMultiLabels(
tabletCallErrorCountStatsName,
"Error count from tablet calls in scatter conns",
[]string{"Operation", "Keyspace", "ShardName", "DbType"}),
txConn: txConn,
gateway: gw,
healthCheck: hc,
}
} | [
"func",
"NewScatterConn",
"(",
"statsName",
"string",
",",
"txConn",
"*",
"TxConn",
",",
"gw",
"gateway",
".",
"Gateway",
",",
"hc",
"discovery",
".",
"HealthCheck",
")",
"*",
"ScatterConn",
"{",
"tabletCallErrorCountStatsName",
":=",
"\"",
"\"",
"\n",
"if",
"statsName",
"!=",
"\"",
"\"",
"{",
"tabletCallErrorCountStatsName",
"=",
"statsName",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"&",
"ScatterConn",
"{",
"timings",
":",
"stats",
".",
"NewMultiTimings",
"(",
"statsName",
",",
"\"",
"\"",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
",",
"tabletCallErrorCount",
":",
"stats",
".",
"NewCountersWithMultiLabels",
"(",
"tabletCallErrorCountStatsName",
",",
"\"",
"\"",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
",",
"txConn",
":",
"txConn",
",",
"gateway",
":",
"gw",
",",
"healthCheck",
":",
"hc",
",",
"}",
"\n",
"}"
] | // NewScatterConn creates a new ScatterConn. | [
"NewScatterConn",
"creates",
"a",
"new",
"ScatterConn",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L76-L94 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | Execute | func (stc *ScatterConn) Execute(
ctx context.Context,
query string,
bindVars map[string]*querypb.BindVariable,
rss []*srvtopo.ResolvedShard,
tabletType topodatapb.TabletType,
session *SafeSession,
notInTransaction bool,
options *querypb.ExecuteOptions,
) (*sqltypes.Result, error) {
// mu protects qr
var mu sync.Mutex
qr := new(sqltypes.Result)
allErrors := stc.multiGoTransaction(
ctx,
"Execute",
rss,
tabletType,
session,
notInTransaction,
func(rs *srvtopo.ResolvedShard, i int, shouldBegin bool, transactionID int64) (int64, error) {
var innerqr *sqltypes.Result
if shouldBegin {
var err error
innerqr, transactionID, err = rs.QueryService.BeginExecute(ctx, rs.Target, query, bindVars, options)
if err != nil {
return transactionID, err
}
} else {
var err error
innerqr, err = rs.QueryService.Execute(ctx, rs.Target, query, bindVars, transactionID, options)
if err != nil {
return transactionID, err
}
}
mu.Lock()
defer mu.Unlock()
qr.AppendResult(innerqr)
return transactionID, nil
})
return qr, allErrors.AggrError(vterrors.Aggregate)
} | go | func (stc *ScatterConn) Execute(
ctx context.Context,
query string,
bindVars map[string]*querypb.BindVariable,
rss []*srvtopo.ResolvedShard,
tabletType topodatapb.TabletType,
session *SafeSession,
notInTransaction bool,
options *querypb.ExecuteOptions,
) (*sqltypes.Result, error) {
// mu protects qr
var mu sync.Mutex
qr := new(sqltypes.Result)
allErrors := stc.multiGoTransaction(
ctx,
"Execute",
rss,
tabletType,
session,
notInTransaction,
func(rs *srvtopo.ResolvedShard, i int, shouldBegin bool, transactionID int64) (int64, error) {
var innerqr *sqltypes.Result
if shouldBegin {
var err error
innerqr, transactionID, err = rs.QueryService.BeginExecute(ctx, rs.Target, query, bindVars, options)
if err != nil {
return transactionID, err
}
} else {
var err error
innerqr, err = rs.QueryService.Execute(ctx, rs.Target, query, bindVars, transactionID, options)
if err != nil {
return transactionID, err
}
}
mu.Lock()
defer mu.Unlock()
qr.AppendResult(innerqr)
return transactionID, nil
})
return qr, allErrors.AggrError(vterrors.Aggregate)
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"Execute",
"(",
"ctx",
"context",
".",
"Context",
",",
"query",
"string",
",",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"rss",
"[",
"]",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"tabletType",
"topodatapb",
".",
"TabletType",
",",
"session",
"*",
"SafeSession",
",",
"notInTransaction",
"bool",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
",",
")",
"(",
"*",
"sqltypes",
".",
"Result",
",",
"error",
")",
"{",
"// mu protects qr",
"var",
"mu",
"sync",
".",
"Mutex",
"\n",
"qr",
":=",
"new",
"(",
"sqltypes",
".",
"Result",
")",
"\n\n",
"allErrors",
":=",
"stc",
".",
"multiGoTransaction",
"(",
"ctx",
",",
"\"",
"\"",
",",
"rss",
",",
"tabletType",
",",
"session",
",",
"notInTransaction",
",",
"func",
"(",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"i",
"int",
",",
"shouldBegin",
"bool",
",",
"transactionID",
"int64",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"innerqr",
"*",
"sqltypes",
".",
"Result",
"\n",
"if",
"shouldBegin",
"{",
"var",
"err",
"error",
"\n",
"innerqr",
",",
"transactionID",
",",
"err",
"=",
"rs",
".",
"QueryService",
".",
"BeginExecute",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"query",
",",
"bindVars",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"transactionID",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"var",
"err",
"error",
"\n",
"innerqr",
",",
"err",
"=",
"rs",
".",
"QueryService",
".",
"Execute",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"query",
",",
"bindVars",
",",
"transactionID",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"transactionID",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"qr",
".",
"AppendResult",
"(",
"innerqr",
")",
"\n",
"return",
"transactionID",
",",
"nil",
"\n",
"}",
")",
"\n\n",
"return",
"qr",
",",
"allErrors",
".",
"AggrError",
"(",
"vterrors",
".",
"Aggregate",
")",
"\n",
"}"
] | // Execute executes a non-streaming query on the specified shards. | [
"Execute",
"executes",
"a",
"non",
"-",
"streaming",
"query",
"on",
"the",
"specified",
"shards",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L120-L165 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | ExecuteMultiShard | func (stc *ScatterConn) ExecuteMultiShard(
ctx context.Context,
rss []*srvtopo.ResolvedShard,
queries []*querypb.BoundQuery,
tabletType topodatapb.TabletType,
session *SafeSession,
notInTransaction bool,
autocommit bool,
) (qr *sqltypes.Result, errs []error) {
// mu protects qr
var mu sync.Mutex
qr = new(sqltypes.Result)
allErrors := stc.multiGoTransaction(
ctx,
"Execute",
rss,
tabletType,
session,
notInTransaction,
func(rs *srvtopo.ResolvedShard, i int, shouldBegin bool, transactionID int64) (int64, error) {
var (
innerqr *sqltypes.Result
err error
opts *querypb.ExecuteOptions
)
if session != nil && session.Session != nil {
opts = session.Session.Options
}
switch {
case autocommit:
innerqr, err = stc.executeAutocommit(ctx, rs, queries[i].Sql, queries[i].BindVariables, opts)
case shouldBegin:
innerqr, transactionID, err = rs.QueryService.BeginExecute(ctx, rs.Target, queries[i].Sql, queries[i].BindVariables, opts)
default:
innerqr, err = rs.QueryService.Execute(ctx, rs.Target, queries[i].Sql, queries[i].BindVariables, transactionID, opts)
}
if err != nil {
return transactionID, err
}
mu.Lock()
defer mu.Unlock()
qr.AppendResult(innerqr)
return transactionID, nil
})
return qr, allErrors.GetErrors()
} | go | func (stc *ScatterConn) ExecuteMultiShard(
ctx context.Context,
rss []*srvtopo.ResolvedShard,
queries []*querypb.BoundQuery,
tabletType topodatapb.TabletType,
session *SafeSession,
notInTransaction bool,
autocommit bool,
) (qr *sqltypes.Result, errs []error) {
// mu protects qr
var mu sync.Mutex
qr = new(sqltypes.Result)
allErrors := stc.multiGoTransaction(
ctx,
"Execute",
rss,
tabletType,
session,
notInTransaction,
func(rs *srvtopo.ResolvedShard, i int, shouldBegin bool, transactionID int64) (int64, error) {
var (
innerqr *sqltypes.Result
err error
opts *querypb.ExecuteOptions
)
if session != nil && session.Session != nil {
opts = session.Session.Options
}
switch {
case autocommit:
innerqr, err = stc.executeAutocommit(ctx, rs, queries[i].Sql, queries[i].BindVariables, opts)
case shouldBegin:
innerqr, transactionID, err = rs.QueryService.BeginExecute(ctx, rs.Target, queries[i].Sql, queries[i].BindVariables, opts)
default:
innerqr, err = rs.QueryService.Execute(ctx, rs.Target, queries[i].Sql, queries[i].BindVariables, transactionID, opts)
}
if err != nil {
return transactionID, err
}
mu.Lock()
defer mu.Unlock()
qr.AppendResult(innerqr)
return transactionID, nil
})
return qr, allErrors.GetErrors()
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"ExecuteMultiShard",
"(",
"ctx",
"context",
".",
"Context",
",",
"rss",
"[",
"]",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"queries",
"[",
"]",
"*",
"querypb",
".",
"BoundQuery",
",",
"tabletType",
"topodatapb",
".",
"TabletType",
",",
"session",
"*",
"SafeSession",
",",
"notInTransaction",
"bool",
",",
"autocommit",
"bool",
",",
")",
"(",
"qr",
"*",
"sqltypes",
".",
"Result",
",",
"errs",
"[",
"]",
"error",
")",
"{",
"// mu protects qr",
"var",
"mu",
"sync",
".",
"Mutex",
"\n",
"qr",
"=",
"new",
"(",
"sqltypes",
".",
"Result",
")",
"\n\n",
"allErrors",
":=",
"stc",
".",
"multiGoTransaction",
"(",
"ctx",
",",
"\"",
"\"",
",",
"rss",
",",
"tabletType",
",",
"session",
",",
"notInTransaction",
",",
"func",
"(",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"i",
"int",
",",
"shouldBegin",
"bool",
",",
"transactionID",
"int64",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"(",
"innerqr",
"*",
"sqltypes",
".",
"Result",
"\n",
"err",
"error",
"\n",
"opts",
"*",
"querypb",
".",
"ExecuteOptions",
"\n",
")",
"\n",
"if",
"session",
"!=",
"nil",
"&&",
"session",
".",
"Session",
"!=",
"nil",
"{",
"opts",
"=",
"session",
".",
"Session",
".",
"Options",
"\n",
"}",
"\n\n",
"switch",
"{",
"case",
"autocommit",
":",
"innerqr",
",",
"err",
"=",
"stc",
".",
"executeAutocommit",
"(",
"ctx",
",",
"rs",
",",
"queries",
"[",
"i",
"]",
".",
"Sql",
",",
"queries",
"[",
"i",
"]",
".",
"BindVariables",
",",
"opts",
")",
"\n",
"case",
"shouldBegin",
":",
"innerqr",
",",
"transactionID",
",",
"err",
"=",
"rs",
".",
"QueryService",
".",
"BeginExecute",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"queries",
"[",
"i",
"]",
".",
"Sql",
",",
"queries",
"[",
"i",
"]",
".",
"BindVariables",
",",
"opts",
")",
"\n",
"default",
":",
"innerqr",
",",
"err",
"=",
"rs",
".",
"QueryService",
".",
"Execute",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"queries",
"[",
"i",
"]",
".",
"Sql",
",",
"queries",
"[",
"i",
"]",
".",
"BindVariables",
",",
"transactionID",
",",
"opts",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"transactionID",
",",
"err",
"\n",
"}",
"\n\n",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"qr",
".",
"AppendResult",
"(",
"innerqr",
")",
"\n",
"return",
"transactionID",
",",
"nil",
"\n",
"}",
")",
"\n\n",
"return",
"qr",
",",
"allErrors",
".",
"GetErrors",
"(",
")",
"\n",
"}"
] | // ExecuteMultiShard is like Execute,
// but each shard gets its own Sql Queries and BindVariables.
//
// It always returns a non-nil query result and an array of
// shard errors which may be nil so that callers can optionally
// process a partially-successful operation. | [
"ExecuteMultiShard",
"is",
"like",
"Execute",
"but",
"each",
"shard",
"gets",
"its",
"own",
"Sql",
"Queries",
"and",
"BindVariables",
".",
"It",
"always",
"returns",
"a",
"non",
"-",
"nil",
"query",
"result",
"and",
"an",
"array",
"of",
"shard",
"errors",
"which",
"may",
"be",
"nil",
"so",
"that",
"callers",
"can",
"optionally",
"process",
"a",
"partially",
"-",
"successful",
"operation",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L173-L223 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | ExecuteBatch | func (stc *ScatterConn) ExecuteBatch(
ctx context.Context,
batchRequest *scatterBatchRequest,
tabletType topodatapb.TabletType,
asTransaction bool,
session *SafeSession,
options *querypb.ExecuteOptions) (qrs []sqltypes.Result, err error) {
allErrors := new(concurrency.AllErrorRecorder)
results := make([]sqltypes.Result, batchRequest.length)
var resMutex sync.Mutex
var wg sync.WaitGroup
for _, req := range batchRequest.requests {
wg.Add(1)
go func(req *shardBatchRequest) {
defer wg.Done()
var err error
startTime, statsKey := stc.startAction("ExecuteBatch", req.rs.Target)
defer stc.endAction(startTime, allErrors, statsKey, &err, session)
shouldBegin, transactionID := transactionInfo(req.rs.Target, session, false)
var innerqrs []sqltypes.Result
if shouldBegin {
innerqrs, transactionID, err = req.rs.QueryService.BeginExecuteBatch(ctx, req.rs.Target, req.queries, asTransaction, options)
if transactionID != 0 {
if appendErr := session.Append(&vtgatepb.Session_ShardSession{
Target: req.rs.Target,
TransactionId: transactionID,
}, stc.txConn.mode); appendErr != nil {
err = appendErr
}
}
if err != nil {
return
}
} else {
innerqrs, err = req.rs.QueryService.ExecuteBatch(ctx, req.rs.Target, req.queries, asTransaction, transactionID, options)
if err != nil {
return
}
}
resMutex.Lock()
defer resMutex.Unlock()
for i, result := range innerqrs {
results[req.resultIndexes[i]].AppendResult(&result)
}
}(req)
}
wg.Wait()
if session.MustRollback() {
stc.txConn.Rollback(ctx, session)
}
if allErrors.HasErrors() {
return nil, allErrors.AggrError(vterrors.Aggregate)
}
return results, nil
} | go | func (stc *ScatterConn) ExecuteBatch(
ctx context.Context,
batchRequest *scatterBatchRequest,
tabletType topodatapb.TabletType,
asTransaction bool,
session *SafeSession,
options *querypb.ExecuteOptions) (qrs []sqltypes.Result, err error) {
allErrors := new(concurrency.AllErrorRecorder)
results := make([]sqltypes.Result, batchRequest.length)
var resMutex sync.Mutex
var wg sync.WaitGroup
for _, req := range batchRequest.requests {
wg.Add(1)
go func(req *shardBatchRequest) {
defer wg.Done()
var err error
startTime, statsKey := stc.startAction("ExecuteBatch", req.rs.Target)
defer stc.endAction(startTime, allErrors, statsKey, &err, session)
shouldBegin, transactionID := transactionInfo(req.rs.Target, session, false)
var innerqrs []sqltypes.Result
if shouldBegin {
innerqrs, transactionID, err = req.rs.QueryService.BeginExecuteBatch(ctx, req.rs.Target, req.queries, asTransaction, options)
if transactionID != 0 {
if appendErr := session.Append(&vtgatepb.Session_ShardSession{
Target: req.rs.Target,
TransactionId: transactionID,
}, stc.txConn.mode); appendErr != nil {
err = appendErr
}
}
if err != nil {
return
}
} else {
innerqrs, err = req.rs.QueryService.ExecuteBatch(ctx, req.rs.Target, req.queries, asTransaction, transactionID, options)
if err != nil {
return
}
}
resMutex.Lock()
defer resMutex.Unlock()
for i, result := range innerqrs {
results[req.resultIndexes[i]].AppendResult(&result)
}
}(req)
}
wg.Wait()
if session.MustRollback() {
stc.txConn.Rollback(ctx, session)
}
if allErrors.HasErrors() {
return nil, allErrors.AggrError(vterrors.Aggregate)
}
return results, nil
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"ExecuteBatch",
"(",
"ctx",
"context",
".",
"Context",
",",
"batchRequest",
"*",
"scatterBatchRequest",
",",
"tabletType",
"topodatapb",
".",
"TabletType",
",",
"asTransaction",
"bool",
",",
"session",
"*",
"SafeSession",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
")",
"(",
"qrs",
"[",
"]",
"sqltypes",
".",
"Result",
",",
"err",
"error",
")",
"{",
"allErrors",
":=",
"new",
"(",
"concurrency",
".",
"AllErrorRecorder",
")",
"\n\n",
"results",
":=",
"make",
"(",
"[",
"]",
"sqltypes",
".",
"Result",
",",
"batchRequest",
".",
"length",
")",
"\n",
"var",
"resMutex",
"sync",
".",
"Mutex",
"\n\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"_",
",",
"req",
":=",
"range",
"batchRequest",
".",
"requests",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"req",
"*",
"shardBatchRequest",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"var",
"err",
"error",
"\n",
"startTime",
",",
"statsKey",
":=",
"stc",
".",
"startAction",
"(",
"\"",
"\"",
",",
"req",
".",
"rs",
".",
"Target",
")",
"\n",
"defer",
"stc",
".",
"endAction",
"(",
"startTime",
",",
"allErrors",
",",
"statsKey",
",",
"&",
"err",
",",
"session",
")",
"\n\n",
"shouldBegin",
",",
"transactionID",
":=",
"transactionInfo",
"(",
"req",
".",
"rs",
".",
"Target",
",",
"session",
",",
"false",
")",
"\n",
"var",
"innerqrs",
"[",
"]",
"sqltypes",
".",
"Result",
"\n",
"if",
"shouldBegin",
"{",
"innerqrs",
",",
"transactionID",
",",
"err",
"=",
"req",
".",
"rs",
".",
"QueryService",
".",
"BeginExecuteBatch",
"(",
"ctx",
",",
"req",
".",
"rs",
".",
"Target",
",",
"req",
".",
"queries",
",",
"asTransaction",
",",
"options",
")",
"\n",
"if",
"transactionID",
"!=",
"0",
"{",
"if",
"appendErr",
":=",
"session",
".",
"Append",
"(",
"&",
"vtgatepb",
".",
"Session_ShardSession",
"{",
"Target",
":",
"req",
".",
"rs",
".",
"Target",
",",
"TransactionId",
":",
"transactionID",
",",
"}",
",",
"stc",
".",
"txConn",
".",
"mode",
")",
";",
"appendErr",
"!=",
"nil",
"{",
"err",
"=",
"appendErr",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"innerqrs",
",",
"err",
"=",
"req",
".",
"rs",
".",
"QueryService",
".",
"ExecuteBatch",
"(",
"ctx",
",",
"req",
".",
"rs",
".",
"Target",
",",
"req",
".",
"queries",
",",
"asTransaction",
",",
"transactionID",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"resMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"resMutex",
".",
"Unlock",
"(",
")",
"\n",
"for",
"i",
",",
"result",
":=",
"range",
"innerqrs",
"{",
"results",
"[",
"req",
".",
"resultIndexes",
"[",
"i",
"]",
"]",
".",
"AppendResult",
"(",
"&",
"result",
")",
"\n",
"}",
"\n",
"}",
"(",
"req",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"if",
"session",
".",
"MustRollback",
"(",
")",
"{",
"stc",
".",
"txConn",
".",
"Rollback",
"(",
"ctx",
",",
"session",
")",
"\n",
"}",
"\n",
"if",
"allErrors",
".",
"HasErrors",
"(",
")",
"{",
"return",
"nil",
",",
"allErrors",
".",
"AggrError",
"(",
"vterrors",
".",
"Aggregate",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ExecuteBatch executes a batch of non-streaming queries on the specified shards. | [
"ExecuteBatch",
"executes",
"a",
"batch",
"of",
"non",
"-",
"streaming",
"queries",
"on",
"the",
"specified",
"shards",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L362-L422 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | StreamExecute | func (stc *ScatterConn) StreamExecute(
ctx context.Context,
query string,
bindVars map[string]*querypb.BindVariable,
rss []*srvtopo.ResolvedShard,
tabletType topodatapb.TabletType,
options *querypb.ExecuteOptions,
callback func(reply *sqltypes.Result) error,
) error {
// mu protects fieldSent, replyErr and callback
var mu sync.Mutex
fieldSent := false
allErrors := stc.multiGo(ctx, "StreamExecute", rss, tabletType, func(rs *srvtopo.ResolvedShard, i int) error {
return rs.QueryService.StreamExecute(ctx, rs.Target, query, bindVars, 0, options, func(qr *sqltypes.Result) error {
return stc.processOneStreamingResult(&mu, &fieldSent, qr, callback)
})
})
return allErrors.AggrError(vterrors.Aggregate)
} | go | func (stc *ScatterConn) StreamExecute(
ctx context.Context,
query string,
bindVars map[string]*querypb.BindVariable,
rss []*srvtopo.ResolvedShard,
tabletType topodatapb.TabletType,
options *querypb.ExecuteOptions,
callback func(reply *sqltypes.Result) error,
) error {
// mu protects fieldSent, replyErr and callback
var mu sync.Mutex
fieldSent := false
allErrors := stc.multiGo(ctx, "StreamExecute", rss, tabletType, func(rs *srvtopo.ResolvedShard, i int) error {
return rs.QueryService.StreamExecute(ctx, rs.Target, query, bindVars, 0, options, func(qr *sqltypes.Result) error {
return stc.processOneStreamingResult(&mu, &fieldSent, qr, callback)
})
})
return allErrors.AggrError(vterrors.Aggregate)
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"StreamExecute",
"(",
"ctx",
"context",
".",
"Context",
",",
"query",
"string",
",",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"rss",
"[",
"]",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"tabletType",
"topodatapb",
".",
"TabletType",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
",",
"callback",
"func",
"(",
"reply",
"*",
"sqltypes",
".",
"Result",
")",
"error",
",",
")",
"error",
"{",
"// mu protects fieldSent, replyErr and callback",
"var",
"mu",
"sync",
".",
"Mutex",
"\n",
"fieldSent",
":=",
"false",
"\n\n",
"allErrors",
":=",
"stc",
".",
"multiGo",
"(",
"ctx",
",",
"\"",
"\"",
",",
"rss",
",",
"tabletType",
",",
"func",
"(",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"i",
"int",
")",
"error",
"{",
"return",
"rs",
".",
"QueryService",
".",
"StreamExecute",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"query",
",",
"bindVars",
",",
"0",
",",
"options",
",",
"func",
"(",
"qr",
"*",
"sqltypes",
".",
"Result",
")",
"error",
"{",
"return",
"stc",
".",
"processOneStreamingResult",
"(",
"&",
"mu",
",",
"&",
"fieldSent",
",",
"qr",
",",
"callback",
")",
"\n",
"}",
")",
"\n",
"}",
")",
"\n",
"return",
"allErrors",
".",
"AggrError",
"(",
"vterrors",
".",
"Aggregate",
")",
"\n",
"}"
] | // StreamExecute executes a streaming query on vttablet. The retry rules are the same.
// Note we guarantee the callback will not be called concurrently
// by mutiple go routines, through processOneStreamingResult. | [
"StreamExecute",
"executes",
"a",
"streaming",
"query",
"on",
"vttablet",
".",
"The",
"retry",
"rules",
"are",
"the",
"same",
".",
"Note",
"we",
"guarantee",
"the",
"callback",
"will",
"not",
"be",
"called",
"concurrently",
"by",
"mutiple",
"go",
"routines",
"through",
"processOneStreamingResult",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L446-L466 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | Reset | func (tt *timeTracker) Reset(target *querypb.Target) {
tt.mu.Lock()
defer tt.mu.Unlock()
delete(tt.timestamps, target)
} | go | func (tt *timeTracker) Reset(target *querypb.Target) {
tt.mu.Lock()
defer tt.mu.Unlock()
delete(tt.timestamps, target)
} | [
"func",
"(",
"tt",
"*",
"timeTracker",
")",
"Reset",
"(",
"target",
"*",
"querypb",
".",
"Target",
")",
"{",
"tt",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tt",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"tt",
".",
"timestamps",
",",
"target",
")",
"\n",
"}"
] | // Reset resets the timestamp set by Record. | [
"Reset",
"resets",
"the",
"timestamp",
"set",
"by",
"Record",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L508-L512 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | Record | func (tt *timeTracker) Record(target *querypb.Target) time.Time {
tt.mu.Lock()
defer tt.mu.Unlock()
last, ok := tt.timestamps[target]
if !ok {
last = time.Now()
tt.timestamps[target] = last
}
return last
} | go | func (tt *timeTracker) Record(target *querypb.Target) time.Time {
tt.mu.Lock()
defer tt.mu.Unlock()
last, ok := tt.timestamps[target]
if !ok {
last = time.Now()
tt.timestamps[target] = last
}
return last
} | [
"func",
"(",
"tt",
"*",
"timeTracker",
")",
"Record",
"(",
"target",
"*",
"querypb",
".",
"Target",
")",
"time",
".",
"Time",
"{",
"tt",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tt",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"last",
",",
"ok",
":=",
"tt",
".",
"timestamps",
"[",
"target",
"]",
"\n",
"if",
"!",
"ok",
"{",
"last",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"tt",
".",
"timestamps",
"[",
"target",
"]",
"=",
"last",
"\n",
"}",
"\n",
"return",
"last",
"\n",
"}"
] | // Record records the time to Now if there was no previous timestamp,
// and it keeps returning that value until the next Reset. | [
"Record",
"records",
"the",
"time",
"to",
"Now",
"if",
"there",
"was",
"no",
"previous",
"timestamp",
"and",
"it",
"keeps",
"returning",
"that",
"value",
"until",
"the",
"next",
"Reset",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L516-L525 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | MessageStream | func (stc *ScatterConn) MessageStream(ctx context.Context, rss []*srvtopo.ResolvedShard, name string, callback func(*sqltypes.Result) error) error {
// The cancelable context is used for handling errors
// from individual streams.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// mu is used to merge multiple callback calls into one.
var mu sync.Mutex
fieldSent := false
lastErrors := newTimeTracker()
allErrors := stc.multiGo(ctx, "MessageStream", rss, topodatapb.TabletType_MASTER, func(rs *srvtopo.ResolvedShard, i int) error {
// This loop handles the case where a reparent happens, which can cause
// an individual stream to end. If we don't succeed on the retries for
// messageStreamGracePeriod, we abort and return an error.
for {
err := rs.QueryService.MessageStream(ctx, rs.Target, name, func(qr *sqltypes.Result) error {
lastErrors.Reset(rs.Target)
return stc.processOneStreamingResult(&mu, &fieldSent, qr, callback)
})
// nil and EOF are equivalent. UNAVAILABLE can be returned by vttablet if it's demoted
// from master to replica. For any of these conditions, we have to retry.
if err != nil && err != io.EOF && vterrors.Code(err) != vtrpcpb.Code_UNAVAILABLE {
cancel()
return err
}
// There was no error. We have to see if we need to retry.
// If context was canceled, likely due to client disconnect,
// return normally without retrying.
select {
case <-ctx.Done():
return nil
default:
}
firstErrorTimeStamp := lastErrors.Record(rs.Target)
if time.Since(firstErrorTimeStamp) >= *messageStreamGracePeriod {
// Cancel all streams and return an error.
cancel()
return vterrors.Errorf(vtrpcpb.Code_DEADLINE_EXCEEDED, "message stream from %v has repeatedly failed for longer than %v", rs.Target, *messageStreamGracePeriod)
}
// It's not been too long since our last good send. Wait and retry.
select {
case <-ctx.Done():
return nil
case <-time.After(*messageStreamGracePeriod / 5):
}
}
})
return allErrors.AggrError(vterrors.Aggregate)
} | go | func (stc *ScatterConn) MessageStream(ctx context.Context, rss []*srvtopo.ResolvedShard, name string, callback func(*sqltypes.Result) error) error {
// The cancelable context is used for handling errors
// from individual streams.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// mu is used to merge multiple callback calls into one.
var mu sync.Mutex
fieldSent := false
lastErrors := newTimeTracker()
allErrors := stc.multiGo(ctx, "MessageStream", rss, topodatapb.TabletType_MASTER, func(rs *srvtopo.ResolvedShard, i int) error {
// This loop handles the case where a reparent happens, which can cause
// an individual stream to end. If we don't succeed on the retries for
// messageStreamGracePeriod, we abort and return an error.
for {
err := rs.QueryService.MessageStream(ctx, rs.Target, name, func(qr *sqltypes.Result) error {
lastErrors.Reset(rs.Target)
return stc.processOneStreamingResult(&mu, &fieldSent, qr, callback)
})
// nil and EOF are equivalent. UNAVAILABLE can be returned by vttablet if it's demoted
// from master to replica. For any of these conditions, we have to retry.
if err != nil && err != io.EOF && vterrors.Code(err) != vtrpcpb.Code_UNAVAILABLE {
cancel()
return err
}
// There was no error. We have to see if we need to retry.
// If context was canceled, likely due to client disconnect,
// return normally without retrying.
select {
case <-ctx.Done():
return nil
default:
}
firstErrorTimeStamp := lastErrors.Record(rs.Target)
if time.Since(firstErrorTimeStamp) >= *messageStreamGracePeriod {
// Cancel all streams and return an error.
cancel()
return vterrors.Errorf(vtrpcpb.Code_DEADLINE_EXCEEDED, "message stream from %v has repeatedly failed for longer than %v", rs.Target, *messageStreamGracePeriod)
}
// It's not been too long since our last good send. Wait and retry.
select {
case <-ctx.Done():
return nil
case <-time.After(*messageStreamGracePeriod / 5):
}
}
})
return allErrors.AggrError(vterrors.Aggregate)
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"MessageStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"rss",
"[",
"]",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"name",
"string",
",",
"callback",
"func",
"(",
"*",
"sqltypes",
".",
"Result",
")",
"error",
")",
"error",
"{",
"// The cancelable context is used for handling errors",
"// from individual streams.",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"ctx",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"// mu is used to merge multiple callback calls into one.",
"var",
"mu",
"sync",
".",
"Mutex",
"\n",
"fieldSent",
":=",
"false",
"\n",
"lastErrors",
":=",
"newTimeTracker",
"(",
")",
"\n",
"allErrors",
":=",
"stc",
".",
"multiGo",
"(",
"ctx",
",",
"\"",
"\"",
",",
"rss",
",",
"topodatapb",
".",
"TabletType_MASTER",
",",
"func",
"(",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"i",
"int",
")",
"error",
"{",
"// This loop handles the case where a reparent happens, which can cause",
"// an individual stream to end. If we don't succeed on the retries for",
"// messageStreamGracePeriod, we abort and return an error.",
"for",
"{",
"err",
":=",
"rs",
".",
"QueryService",
".",
"MessageStream",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"name",
",",
"func",
"(",
"qr",
"*",
"sqltypes",
".",
"Result",
")",
"error",
"{",
"lastErrors",
".",
"Reset",
"(",
"rs",
".",
"Target",
")",
"\n",
"return",
"stc",
".",
"processOneStreamingResult",
"(",
"&",
"mu",
",",
"&",
"fieldSent",
",",
"qr",
",",
"callback",
")",
"\n",
"}",
")",
"\n",
"// nil and EOF are equivalent. UNAVAILABLE can be returned by vttablet if it's demoted",
"// from master to replica. For any of these conditions, we have to retry.",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"io",
".",
"EOF",
"&&",
"vterrors",
".",
"Code",
"(",
"err",
")",
"!=",
"vtrpcpb",
".",
"Code_UNAVAILABLE",
"{",
"cancel",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// There was no error. We have to see if we need to retry.",
"// If context was canceled, likely due to client disconnect,",
"// return normally without retrying.",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
"\n",
"default",
":",
"}",
"\n",
"firstErrorTimeStamp",
":=",
"lastErrors",
".",
"Record",
"(",
"rs",
".",
"Target",
")",
"\n",
"if",
"time",
".",
"Since",
"(",
"firstErrorTimeStamp",
")",
">=",
"*",
"messageStreamGracePeriod",
"{",
"// Cancel all streams and return an error.",
"cancel",
"(",
")",
"\n",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpcpb",
".",
"Code_DEADLINE_EXCEEDED",
",",
"\"",
"\"",
",",
"rs",
".",
"Target",
",",
"*",
"messageStreamGracePeriod",
")",
"\n",
"}",
"\n\n",
"// It's not been too long since our last good send. Wait and retry.",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"*",
"messageStreamGracePeriod",
"/",
"5",
")",
":",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"allErrors",
".",
"AggrError",
"(",
"vterrors",
".",
"Aggregate",
")",
"\n",
"}"
] | // MessageStream streams messages from the specified shards.
// Note we guarantee the callback will not be called concurrently
// by mutiple go routines, through processOneStreamingResult. | [
"MessageStream",
"streams",
"messages",
"from",
"the",
"specified",
"shards",
".",
"Note",
"we",
"guarantee",
"the",
"callback",
"will",
"not",
"be",
"called",
"concurrently",
"by",
"mutiple",
"go",
"routines",
"through",
"processOneStreamingResult",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L530-L580 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | MessageAck | func (stc *ScatterConn) MessageAck(ctx context.Context, rss []*srvtopo.ResolvedShard, values [][]*querypb.Value, name string) (int64, error) {
var mu sync.Mutex
var totalCount int64
allErrors := stc.multiGo(ctx, "MessageAck", rss, topodatapb.TabletType_MASTER, func(rs *srvtopo.ResolvedShard, i int) error {
count, err := rs.QueryService.MessageAck(ctx, rs.Target, name, values[i])
if err != nil {
return err
}
mu.Lock()
totalCount += count
mu.Unlock()
return nil
})
return totalCount, allErrors.AggrError(vterrors.Aggregate)
} | go | func (stc *ScatterConn) MessageAck(ctx context.Context, rss []*srvtopo.ResolvedShard, values [][]*querypb.Value, name string) (int64, error) {
var mu sync.Mutex
var totalCount int64
allErrors := stc.multiGo(ctx, "MessageAck", rss, topodatapb.TabletType_MASTER, func(rs *srvtopo.ResolvedShard, i int) error {
count, err := rs.QueryService.MessageAck(ctx, rs.Target, name, values[i])
if err != nil {
return err
}
mu.Lock()
totalCount += count
mu.Unlock()
return nil
})
return totalCount, allErrors.AggrError(vterrors.Aggregate)
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"MessageAck",
"(",
"ctx",
"context",
".",
"Context",
",",
"rss",
"[",
"]",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"values",
"[",
"]",
"[",
"]",
"*",
"querypb",
".",
"Value",
",",
"name",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"mu",
"sync",
".",
"Mutex",
"\n",
"var",
"totalCount",
"int64",
"\n",
"allErrors",
":=",
"stc",
".",
"multiGo",
"(",
"ctx",
",",
"\"",
"\"",
",",
"rss",
",",
"topodatapb",
".",
"TabletType_MASTER",
",",
"func",
"(",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"i",
"int",
")",
"error",
"{",
"count",
",",
"err",
":=",
"rs",
".",
"QueryService",
".",
"MessageAck",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"name",
",",
"values",
"[",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"mu",
".",
"Lock",
"(",
")",
"\n",
"totalCount",
"+=",
"count",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"totalCount",
",",
"allErrors",
".",
"AggrError",
"(",
"vterrors",
".",
"Aggregate",
")",
"\n",
"}"
] | // MessageAck acks messages across multiple shards. | [
"MessageAck",
"acks",
"messages",
"across",
"multiple",
"shards",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L583-L597 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | UpdateStream | func (stc *ScatterConn) UpdateStream(ctx context.Context, rs *srvtopo.ResolvedShard, timestamp int64, position string, callback func(*querypb.StreamEvent) error) error {
return rs.QueryService.UpdateStream(ctx, rs.Target, position, timestamp, callback)
} | go | func (stc *ScatterConn) UpdateStream(ctx context.Context, rs *srvtopo.ResolvedShard, timestamp int64, position string, callback func(*querypb.StreamEvent) error) error {
return rs.QueryService.UpdateStream(ctx, rs.Target, position, timestamp, callback)
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"UpdateStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"timestamp",
"int64",
",",
"position",
"string",
",",
"callback",
"func",
"(",
"*",
"querypb",
".",
"StreamEvent",
")",
"error",
")",
"error",
"{",
"return",
"rs",
".",
"QueryService",
".",
"UpdateStream",
"(",
"ctx",
",",
"rs",
".",
"Target",
",",
"position",
",",
"timestamp",
",",
"callback",
")",
"\n",
"}"
] | // UpdateStream just sends the query to the ResolvedShard,
// and sends the results back. | [
"UpdateStream",
"just",
"sends",
"the",
"query",
"to",
"the",
"ResolvedShard",
"and",
"sends",
"the",
"results",
"back",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L601-L603 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | shuffleQueryParts | func shuffleQueryParts(splits []*vtgatepb.SplitQueryResponse_Part) {
for i := len(splits) - 1; i >= 1; i-- {
randIndex := shuffleQueryPartsRandomGenerator.Intn(i + 1)
// swap splits[i], splits[randIndex]
splits[randIndex], splits[i] = splits[i], splits[randIndex]
}
} | go | func shuffleQueryParts(splits []*vtgatepb.SplitQueryResponse_Part) {
for i := len(splits) - 1; i >= 1; i-- {
randIndex := shuffleQueryPartsRandomGenerator.Intn(i + 1)
// swap splits[i], splits[randIndex]
splits[randIndex], splits[i] = splits[i], splits[randIndex]
}
} | [
"func",
"shuffleQueryParts",
"(",
"splits",
"[",
"]",
"*",
"vtgatepb",
".",
"SplitQueryResponse_Part",
")",
"{",
"for",
"i",
":=",
"len",
"(",
"splits",
")",
"-",
"1",
";",
"i",
">=",
"1",
";",
"i",
"--",
"{",
"randIndex",
":=",
"shuffleQueryPartsRandomGenerator",
".",
"Intn",
"(",
"i",
"+",
"1",
")",
"\n",
"// swap splits[i], splits[randIndex]",
"splits",
"[",
"randIndex",
"]",
",",
"splits",
"[",
"i",
"]",
"=",
"splits",
"[",
"i",
"]",
",",
"splits",
"[",
"randIndex",
"]",
"\n",
"}",
"\n",
"}"
] | // shuffleQueryParts performs an in-place shuffle of the given array.
// The result is a psuedo-random permutation of the array chosen uniformally
// from the space of all permutations. | [
"shuffleQueryParts",
"performs",
"an",
"in",
"-",
"place",
"shuffle",
"of",
"the",
"given",
"array",
".",
"The",
"result",
"is",
"a",
"psuedo",
"-",
"random",
"permutation",
"of",
"the",
"array",
"chosen",
"uniformally",
"from",
"the",
"space",
"of",
"all",
"permutations",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L707-L713 | train |
vitessio/vitess | go/vt/vtgate/scatter_conn.go | multiGo | func (stc *ScatterConn) multiGo(
ctx context.Context,
name string,
rss []*srvtopo.ResolvedShard,
tabletType topodatapb.TabletType,
action shardActionFunc,
) (allErrors *concurrency.AllErrorRecorder) {
allErrors = new(concurrency.AllErrorRecorder)
if len(rss) == 0 {
return allErrors
}
oneShard := func(rs *srvtopo.ResolvedShard, i int) {
var err error
startTime, statsKey := stc.startAction(name, rs.Target)
defer stc.endAction(startTime, allErrors, statsKey, &err, nil)
err = action(rs, i)
}
if len(rss) == 1 {
// only one shard, do it synchronously.
oneShard(rss[0], 0)
return allErrors
}
var wg sync.WaitGroup
for i, rs := range rss {
wg.Add(1)
go func(rs *srvtopo.ResolvedShard, i int) {
defer wg.Done()
oneShard(rs, i)
}(rs, i)
}
wg.Wait()
return allErrors
} | go | func (stc *ScatterConn) multiGo(
ctx context.Context,
name string,
rss []*srvtopo.ResolvedShard,
tabletType topodatapb.TabletType,
action shardActionFunc,
) (allErrors *concurrency.AllErrorRecorder) {
allErrors = new(concurrency.AllErrorRecorder)
if len(rss) == 0 {
return allErrors
}
oneShard := func(rs *srvtopo.ResolvedShard, i int) {
var err error
startTime, statsKey := stc.startAction(name, rs.Target)
defer stc.endAction(startTime, allErrors, statsKey, &err, nil)
err = action(rs, i)
}
if len(rss) == 1 {
// only one shard, do it synchronously.
oneShard(rss[0], 0)
return allErrors
}
var wg sync.WaitGroup
for i, rs := range rss {
wg.Add(1)
go func(rs *srvtopo.ResolvedShard, i int) {
defer wg.Done()
oneShard(rs, i)
}(rs, i)
}
wg.Wait()
return allErrors
} | [
"func",
"(",
"stc",
"*",
"ScatterConn",
")",
"multiGo",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"rss",
"[",
"]",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"tabletType",
"topodatapb",
".",
"TabletType",
",",
"action",
"shardActionFunc",
",",
")",
"(",
"allErrors",
"*",
"concurrency",
".",
"AllErrorRecorder",
")",
"{",
"allErrors",
"=",
"new",
"(",
"concurrency",
".",
"AllErrorRecorder",
")",
"\n",
"if",
"len",
"(",
"rss",
")",
"==",
"0",
"{",
"return",
"allErrors",
"\n",
"}",
"\n\n",
"oneShard",
":=",
"func",
"(",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"i",
"int",
")",
"{",
"var",
"err",
"error",
"\n",
"startTime",
",",
"statsKey",
":=",
"stc",
".",
"startAction",
"(",
"name",
",",
"rs",
".",
"Target",
")",
"\n",
"defer",
"stc",
".",
"endAction",
"(",
"startTime",
",",
"allErrors",
",",
"statsKey",
",",
"&",
"err",
",",
"nil",
")",
"\n",
"err",
"=",
"action",
"(",
"rs",
",",
"i",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"rss",
")",
"==",
"1",
"{",
"// only one shard, do it synchronously.",
"oneShard",
"(",
"rss",
"[",
"0",
"]",
",",
"0",
")",
"\n",
"return",
"allErrors",
"\n",
"}",
"\n\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n",
"for",
"i",
",",
"rs",
":=",
"range",
"rss",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"rs",
"*",
"srvtopo",
".",
"ResolvedShard",
",",
"i",
"int",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"oneShard",
"(",
"rs",
",",
"i",
")",
"\n",
"}",
"(",
"rs",
",",
"i",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"allErrors",
"\n",
"}"
] | // multiGo performs the requested 'action' on the specified
// shards in parallel. This does not handle any transaction state.
// The action function must match the shardActionFunc2 signature. | [
"multiGo",
"performs",
"the",
"requested",
"action",
"on",
"the",
"specified",
"shards",
"in",
"parallel",
".",
"This",
"does",
"not",
"handle",
"any",
"transaction",
"state",
".",
"The",
"action",
"function",
"must",
"match",
"the",
"shardActionFunc2",
"signature",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/scatter_conn.go#L728-L763 | train |
vitessio/vitess | go/vt/vttablet/endtoend/framework/eventcatcher.go | Next | func (tc *TxCatcher) Next() (*tabletserver.TxConnection, error) {
event, err := tc.catcher.next()
if err != nil {
return nil, err
}
return event.(*tabletserver.TxConnection), nil
} | go | func (tc *TxCatcher) Next() (*tabletserver.TxConnection, error) {
event, err := tc.catcher.next()
if err != nil {
return nil, err
}
return event.(*tabletserver.TxConnection), nil
} | [
"func",
"(",
"tc",
"*",
"TxCatcher",
")",
"Next",
"(",
")",
"(",
"*",
"tabletserver",
".",
"TxConnection",
",",
"error",
")",
"{",
"event",
",",
"err",
":=",
"tc",
".",
"catcher",
".",
"next",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"event",
".",
"(",
"*",
"tabletserver",
".",
"TxConnection",
")",
",",
"nil",
"\n",
"}"
] | // Next fetches the next captured transaction.
// If the wait is longer than one second, it returns an error. | [
"Next",
"fetches",
"the",
"next",
"captured",
"transaction",
".",
"If",
"the",
"wait",
"is",
"longer",
"than",
"one",
"second",
"it",
"returns",
"an",
"error",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/eventcatcher.go#L47-L53 | train |
vitessio/vitess | go/vt/vttablet/endtoend/framework/eventcatcher.go | Next | func (qc *QueryCatcher) Next() (*tabletenv.LogStats, error) {
event, err := qc.catcher.next()
if err != nil {
return nil, err
}
return event.(*tabletenv.LogStats), nil
} | go | func (qc *QueryCatcher) Next() (*tabletenv.LogStats, error) {
event, err := qc.catcher.next()
if err != nil {
return nil, err
}
return event.(*tabletenv.LogStats), nil
} | [
"func",
"(",
"qc",
"*",
"QueryCatcher",
")",
"Next",
"(",
")",
"(",
"*",
"tabletenv",
".",
"LogStats",
",",
"error",
")",
"{",
"event",
",",
"err",
":=",
"qc",
".",
"catcher",
".",
"next",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"event",
".",
"(",
"*",
"tabletenv",
".",
"LogStats",
")",
",",
"nil",
"\n",
"}"
] | // Next fetches the next captured query.
// If the wait is longer than one second, it returns an error. | [
"Next",
"fetches",
"the",
"next",
"captured",
"query",
".",
"If",
"the",
"wait",
"is",
"longer",
"than",
"one",
"second",
"it",
"returns",
"an",
"error",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/eventcatcher.go#L74-L80 | train |
vitessio/vitess | go/vt/vttablet/endtoend/framework/eventcatcher.go | Close | func (catcher *eventCatcher) Close() {
catcher.logger.Unsubscribe(catcher.in)
close(catcher.in)
} | go | func (catcher *eventCatcher) Close() {
catcher.logger.Unsubscribe(catcher.in)
close(catcher.in)
} | [
"func",
"(",
"catcher",
"*",
"eventCatcher",
")",
"Close",
"(",
")",
"{",
"catcher",
".",
"logger",
".",
"Unsubscribe",
"(",
"catcher",
".",
"in",
")",
"\n",
"close",
"(",
"catcher",
".",
"in",
")",
"\n",
"}"
] | // Close closes the eventCatcher. | [
"Close",
"closes",
"the",
"eventCatcher",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/eventcatcher.go#L111-L114 | train |
vitessio/vitess | go/vt/srvtopo/target_stats.go | Subscribe | func (tsm *TargetStatsMultiplexer) Subscribe() (int, <-chan (*TargetStatsEntry)) {
i := tsm.nextIndex
tsm.nextIndex++
c := make(chan (*TargetStatsEntry), 100)
tsm.listeners[i] = c
return i, c
} | go | func (tsm *TargetStatsMultiplexer) Subscribe() (int, <-chan (*TargetStatsEntry)) {
i := tsm.nextIndex
tsm.nextIndex++
c := make(chan (*TargetStatsEntry), 100)
tsm.listeners[i] = c
return i, c
} | [
"func",
"(",
"tsm",
"*",
"TargetStatsMultiplexer",
")",
"Subscribe",
"(",
")",
"(",
"int",
",",
"<-",
"chan",
"(",
"*",
"TargetStatsEntry",
")",
")",
"{",
"i",
":=",
"tsm",
".",
"nextIndex",
"\n",
"tsm",
".",
"nextIndex",
"++",
"\n",
"c",
":=",
"make",
"(",
"chan",
"(",
"*",
"TargetStatsEntry",
")",
",",
"100",
")",
"\n",
"tsm",
".",
"listeners",
"[",
"i",
"]",
"=",
"c",
"\n",
"return",
"i",
",",
"c",
"\n",
"}"
] | // Subscribe adds a channel to the list.
// Will change the list. | [
"Subscribe",
"adds",
"a",
"channel",
"to",
"the",
"list",
".",
"Will",
"change",
"the",
"list",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/srvtopo/target_stats.go#L78-L84 | train |
vitessio/vitess | go/vt/srvtopo/target_stats.go | Unsubscribe | func (tsm *TargetStatsMultiplexer) Unsubscribe(i int) error {
c, ok := tsm.listeners[i]
if !ok {
return fmt.Errorf("TargetStatsMultiplexer.Unsubscribe(%v): not suc channel", i)
}
delete(tsm.listeners, i)
close(c)
return nil
} | go | func (tsm *TargetStatsMultiplexer) Unsubscribe(i int) error {
c, ok := tsm.listeners[i]
if !ok {
return fmt.Errorf("TargetStatsMultiplexer.Unsubscribe(%v): not suc channel", i)
}
delete(tsm.listeners, i)
close(c)
return nil
} | [
"func",
"(",
"tsm",
"*",
"TargetStatsMultiplexer",
")",
"Unsubscribe",
"(",
"i",
"int",
")",
"error",
"{",
"c",
",",
"ok",
":=",
"tsm",
".",
"listeners",
"[",
"i",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"}",
"\n",
"delete",
"(",
"tsm",
".",
"listeners",
",",
"i",
")",
"\n",
"close",
"(",
"c",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Unsubscribe removes a channel from the list.
// Will change the list. | [
"Unsubscribe",
"removes",
"a",
"channel",
"from",
"the",
"list",
".",
"Will",
"change",
"the",
"list",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/srvtopo/target_stats.go#L88-L96 | train |
vitessio/vitess | go/vt/srvtopo/target_stats.go | Broadcast | func (tsm *TargetStatsMultiplexer) Broadcast(tse *TargetStatsEntry) {
for _, c := range tsm.listeners {
c <- tse
}
} | go | func (tsm *TargetStatsMultiplexer) Broadcast(tse *TargetStatsEntry) {
for _, c := range tsm.listeners {
c <- tse
}
} | [
"func",
"(",
"tsm",
"*",
"TargetStatsMultiplexer",
")",
"Broadcast",
"(",
"tse",
"*",
"TargetStatsEntry",
")",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"tsm",
".",
"listeners",
"{",
"c",
"<-",
"tse",
"\n",
"}",
"\n",
"}"
] | // Broadcast sends an update to the list.
// Will read the list. | [
"Broadcast",
"sends",
"an",
"update",
"to",
"the",
"list",
".",
"Will",
"read",
"the",
"list",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/srvtopo/target_stats.go#L106-L110 | train |
vitessio/vitess | go/vt/vtexplain/vtexplain.go | MarshalJSON | func (tq *TabletQuery) MarshalJSON() ([]byte, error) {
// Convert Bindvars to strings for nicer output
bindVars := make(map[string]string)
for k, v := range tq.BindVars {
var b strings.Builder
sqlparser.EncodeValue(&b, v)
bindVars[k] = b.String()
}
return jsonutil.MarshalNoEscape(&struct {
Time int
SQL string
BindVars map[string]string
}{
Time: tq.Time,
SQL: tq.SQL,
BindVars: bindVars,
})
} | go | func (tq *TabletQuery) MarshalJSON() ([]byte, error) {
// Convert Bindvars to strings for nicer output
bindVars := make(map[string]string)
for k, v := range tq.BindVars {
var b strings.Builder
sqlparser.EncodeValue(&b, v)
bindVars[k] = b.String()
}
return jsonutil.MarshalNoEscape(&struct {
Time int
SQL string
BindVars map[string]string
}{
Time: tq.Time,
SQL: tq.SQL,
BindVars: bindVars,
})
} | [
"func",
"(",
"tq",
"*",
"TabletQuery",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Convert Bindvars to strings for nicer output",
"bindVars",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"tq",
".",
"BindVars",
"{",
"var",
"b",
"strings",
".",
"Builder",
"\n",
"sqlparser",
".",
"EncodeValue",
"(",
"&",
"b",
",",
"v",
")",
"\n",
"bindVars",
"[",
"k",
"]",
"=",
"b",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"jsonutil",
".",
"MarshalNoEscape",
"(",
"&",
"struct",
"{",
"Time",
"int",
"\n",
"SQL",
"string",
"\n",
"BindVars",
"map",
"[",
"string",
"]",
"string",
"\n",
"}",
"{",
"Time",
":",
"tq",
".",
"Time",
",",
"SQL",
":",
"tq",
".",
"SQL",
",",
"BindVars",
":",
"bindVars",
",",
"}",
")",
"\n",
"}"
] | // MarshalJSON renders the json structure | [
"MarshalJSON",
"renders",
"the",
"json",
"structure"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtexplain/vtexplain.go#L104-L122 | train |
vitessio/vitess | go/vt/vtexplain/vtexplain.go | Stop | func Stop() {
// Cleanup all created fake dbs.
if explainTopo != nil {
for _, conn := range explainTopo.TabletConns {
conn.tsv.StopService()
}
for _, conn := range explainTopo.TabletConns {
conn.db.Close()
}
}
} | go | func Stop() {
// Cleanup all created fake dbs.
if explainTopo != nil {
for _, conn := range explainTopo.TabletConns {
conn.tsv.StopService()
}
for _, conn := range explainTopo.TabletConns {
conn.db.Close()
}
}
} | [
"func",
"Stop",
"(",
")",
"{",
"// Cleanup all created fake dbs.",
"if",
"explainTopo",
"!=",
"nil",
"{",
"for",
"_",
",",
"conn",
":=",
"range",
"explainTopo",
".",
"TabletConns",
"{",
"conn",
".",
"tsv",
".",
"StopService",
"(",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"conn",
":=",
"range",
"explainTopo",
".",
"TabletConns",
"{",
"conn",
".",
"db",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Stop and cleans up fake execution environment | [
"Stop",
"and",
"cleans",
"up",
"fake",
"execution",
"environment"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtexplain/vtexplain.go#L172-L182 | train |
vitessio/vitess | go/vt/vtexplain/vtexplain.go | Run | func Run(sql string) ([]*Explain, error) {
explains := make([]*Explain, 0, 16)
var (
rem string
err error
)
for {
// Need to strip comments in a loop to handle multiple comments
// in a row.
for {
s := sqlparser.StripLeadingComments(sql)
if s == sql {
break
}
sql = s
}
sql, rem, err = sqlparser.SplitStatement(sql)
if err != nil {
return nil, err
}
if sql != "" {
// Reset the global time simulator unless there's an open transaction
// in the session from the previous staement.
if vtgateSession == nil || !vtgateSession.GetInTransaction() {
batchTime = sync2.NewBatcher(*batchInterval)
}
log.V(100).Infof("explain %s", sql)
e, err := explain(sql)
if err != nil {
return nil, err
}
explains = append(explains, e)
}
sql = rem
if sql == "" {
break
}
}
return explains, nil
} | go | func Run(sql string) ([]*Explain, error) {
explains := make([]*Explain, 0, 16)
var (
rem string
err error
)
for {
// Need to strip comments in a loop to handle multiple comments
// in a row.
for {
s := sqlparser.StripLeadingComments(sql)
if s == sql {
break
}
sql = s
}
sql, rem, err = sqlparser.SplitStatement(sql)
if err != nil {
return nil, err
}
if sql != "" {
// Reset the global time simulator unless there's an open transaction
// in the session from the previous staement.
if vtgateSession == nil || !vtgateSession.GetInTransaction() {
batchTime = sync2.NewBatcher(*batchInterval)
}
log.V(100).Infof("explain %s", sql)
e, err := explain(sql)
if err != nil {
return nil, err
}
explains = append(explains, e)
}
sql = rem
if sql == "" {
break
}
}
return explains, nil
} | [
"func",
"Run",
"(",
"sql",
"string",
")",
"(",
"[",
"]",
"*",
"Explain",
",",
"error",
")",
"{",
"explains",
":=",
"make",
"(",
"[",
"]",
"*",
"Explain",
",",
"0",
",",
"16",
")",
"\n\n",
"var",
"(",
"rem",
"string",
"\n",
"err",
"error",
"\n",
")",
"\n\n",
"for",
"{",
"// Need to strip comments in a loop to handle multiple comments",
"// in a row.",
"for",
"{",
"s",
":=",
"sqlparser",
".",
"StripLeadingComments",
"(",
"sql",
")",
"\n",
"if",
"s",
"==",
"sql",
"{",
"break",
"\n",
"}",
"\n",
"sql",
"=",
"s",
"\n",
"}",
"\n\n",
"sql",
",",
"rem",
",",
"err",
"=",
"sqlparser",
".",
"SplitStatement",
"(",
"sql",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"sql",
"!=",
"\"",
"\"",
"{",
"// Reset the global time simulator unless there's an open transaction",
"// in the session from the previous staement.",
"if",
"vtgateSession",
"==",
"nil",
"||",
"!",
"vtgateSession",
".",
"GetInTransaction",
"(",
")",
"{",
"batchTime",
"=",
"sync2",
".",
"NewBatcher",
"(",
"*",
"batchInterval",
")",
"\n",
"}",
"\n",
"log",
".",
"V",
"(",
"100",
")",
".",
"Infof",
"(",
"\"",
"\"",
",",
"sql",
")",
"\n",
"e",
",",
"err",
":=",
"explain",
"(",
"sql",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"explains",
"=",
"append",
"(",
"explains",
",",
"e",
")",
"\n",
"}",
"\n\n",
"sql",
"=",
"rem",
"\n",
"if",
"sql",
"==",
"\"",
"\"",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"explains",
",",
"nil",
"\n",
"}"
] | // Run the explain analysis on the given queries | [
"Run",
"the",
"explain",
"analysis",
"on",
"the",
"given",
"queries"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtexplain/vtexplain.go#L232-L277 | train |
vitessio/vitess | go/vt/vtexplain/vtexplain.go | ExplainsAsText | func ExplainsAsText(explains []*Explain) string {
var b bytes.Buffer
for _, explain := range explains {
fmt.Fprintf(&b, "----------------------------------------------------------------------\n")
fmt.Fprintf(&b, "%s\n\n", explain.SQL)
queries := make([]outputQuery, 0, 4)
for tablet, actions := range explain.TabletActions {
for _, q := range actions.MysqlQueries {
queries = append(queries, outputQuery{
tablet: tablet,
Time: q.Time,
sql: q.SQL,
})
}
}
// Make sure to sort first by the batch time and then by the
// shard to avoid flakiness in the tests for parallel queries
sort.SliceStable(queries, func(i, j int) bool {
if queries[i].Time == queries[j].Time {
return queries[i].tablet < queries[j].tablet
}
return queries[i].Time < queries[j].Time
})
for _, q := range queries {
fmt.Fprintf(&b, "%d %s: %s\n", q.Time, q.tablet, q.sql)
}
fmt.Fprintf(&b, "\n")
}
fmt.Fprintf(&b, "----------------------------------------------------------------------\n")
return b.String()
} | go | func ExplainsAsText(explains []*Explain) string {
var b bytes.Buffer
for _, explain := range explains {
fmt.Fprintf(&b, "----------------------------------------------------------------------\n")
fmt.Fprintf(&b, "%s\n\n", explain.SQL)
queries := make([]outputQuery, 0, 4)
for tablet, actions := range explain.TabletActions {
for _, q := range actions.MysqlQueries {
queries = append(queries, outputQuery{
tablet: tablet,
Time: q.Time,
sql: q.SQL,
})
}
}
// Make sure to sort first by the batch time and then by the
// shard to avoid flakiness in the tests for parallel queries
sort.SliceStable(queries, func(i, j int) bool {
if queries[i].Time == queries[j].Time {
return queries[i].tablet < queries[j].tablet
}
return queries[i].Time < queries[j].Time
})
for _, q := range queries {
fmt.Fprintf(&b, "%d %s: %s\n", q.Time, q.tablet, q.sql)
}
fmt.Fprintf(&b, "\n")
}
fmt.Fprintf(&b, "----------------------------------------------------------------------\n")
return b.String()
} | [
"func",
"ExplainsAsText",
"(",
"explains",
"[",
"]",
"*",
"Explain",
")",
"string",
"{",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"explain",
":=",
"range",
"explains",
"{",
"fmt",
".",
"Fprintf",
"(",
"&",
"b",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"&",
"b",
",",
"\"",
"\\n",
"\\n",
"\"",
",",
"explain",
".",
"SQL",
")",
"\n\n",
"queries",
":=",
"make",
"(",
"[",
"]",
"outputQuery",
",",
"0",
",",
"4",
")",
"\n",
"for",
"tablet",
",",
"actions",
":=",
"range",
"explain",
".",
"TabletActions",
"{",
"for",
"_",
",",
"q",
":=",
"range",
"actions",
".",
"MysqlQueries",
"{",
"queries",
"=",
"append",
"(",
"queries",
",",
"outputQuery",
"{",
"tablet",
":",
"tablet",
",",
"Time",
":",
"q",
".",
"Time",
",",
"sql",
":",
"q",
".",
"SQL",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Make sure to sort first by the batch time and then by the",
"// shard to avoid flakiness in the tests for parallel queries",
"sort",
".",
"SliceStable",
"(",
"queries",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"if",
"queries",
"[",
"i",
"]",
".",
"Time",
"==",
"queries",
"[",
"j",
"]",
".",
"Time",
"{",
"return",
"queries",
"[",
"i",
"]",
".",
"tablet",
"<",
"queries",
"[",
"j",
"]",
".",
"tablet",
"\n",
"}",
"\n",
"return",
"queries",
"[",
"i",
"]",
".",
"Time",
"<",
"queries",
"[",
"j",
"]",
".",
"Time",
"\n",
"}",
")",
"\n\n",
"for",
"_",
",",
"q",
":=",
"range",
"queries",
"{",
"fmt",
".",
"Fprintf",
"(",
"&",
"b",
",",
"\"",
"\\n",
"\"",
",",
"q",
".",
"Time",
",",
"q",
".",
"tablet",
",",
"q",
".",
"sql",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"&",
"b",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"&",
"b",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"return",
"b",
".",
"String",
"(",
")",
"\n",
"}"
] | // ExplainsAsText returns a text representation of the explains in logical time
// order | [
"ExplainsAsText",
"returns",
"a",
"text",
"representation",
"of",
"the",
"explains",
"in",
"logical",
"time",
"order"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtexplain/vtexplain.go#L300-L333 | train |
vitessio/vitess | go/vt/vtexplain/vtexplain.go | ExplainsAsJSON | func ExplainsAsJSON(explains []*Explain) string {
explainJSON, _ := jsonutil.MarshalIndentNoEscape(explains, "", " ")
return string(explainJSON)
} | go | func ExplainsAsJSON(explains []*Explain) string {
explainJSON, _ := jsonutil.MarshalIndentNoEscape(explains, "", " ")
return string(explainJSON)
} | [
"func",
"ExplainsAsJSON",
"(",
"explains",
"[",
"]",
"*",
"Explain",
")",
"string",
"{",
"explainJSON",
",",
"_",
":=",
"jsonutil",
".",
"MarshalIndentNoEscape",
"(",
"explains",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"string",
"(",
"explainJSON",
")",
"\n",
"}"
] | // ExplainsAsJSON returns a json representation of the explains | [
"ExplainsAsJSON",
"returns",
"a",
"json",
"representation",
"of",
"the",
"explains"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtexplain/vtexplain.go#L336-L339 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/replication_reporter.go | Report | func (r *replicationReporter) Report(isSlaveType, shouldQueryServiceBeRunning bool) (time.Duration, error) {
if !isSlaveType {
return 0, nil
}
status, statusErr := r.agent.MysqlDaemon.SlaveStatus()
if statusErr == mysql.ErrNotSlave ||
(statusErr == nil && !status.SlaveSQLRunning && !status.SlaveIORunning) {
// MySQL is up, but slave is either not configured or not running.
// Both SQL and IO threads are stopped, so it's probably either
// stopped on purpose, or stopped because of a mysqld restart.
if !r.agent.slaveStopped() {
// As far as we've been told, it isn't stopped on purpose,
// so let's try to start it.
if *mysqlctl.DisableActiveReparents {
log.Infof("Slave is stopped. Running with --disable_active_reparents so will not try to reconnect to master...")
} else {
log.Infof("Slave is stopped. Trying to reconnect to master...")
ctx, cancel := context.WithTimeout(r.agent.batchCtx, 5*time.Second)
if err := repairReplication(ctx, r.agent); err != nil {
log.Infof("Failed to reconnect to master: %v", err)
}
cancel()
// Check status again.
status, statusErr = r.agent.MysqlDaemon.SlaveStatus()
}
}
}
if statusErr != nil {
// mysqld is not running or slave is not configured.
// We can't report healthy.
return 0, statusErr
}
if !status.SlaveRunning() {
// mysqld is running, but slave is not replicating (most likely,
// replication has been stopped). See if we can extrapolate.
if r.lastKnownTime.IsZero() {
// we can't.
return 0, health.ErrSlaveNotRunning
}
// we can extrapolate with the worst possible
// value (that is we made no replication
// progress since last time, and just fell more behind).
elapsed := r.now().Sub(r.lastKnownTime)
return elapsed + r.lastKnownValue, nil
}
// we got a real value, save it.
r.lastKnownValue = time.Duration(status.SecondsBehindMaster) * time.Second
r.lastKnownTime = r.now()
return r.lastKnownValue, nil
} | go | func (r *replicationReporter) Report(isSlaveType, shouldQueryServiceBeRunning bool) (time.Duration, error) {
if !isSlaveType {
return 0, nil
}
status, statusErr := r.agent.MysqlDaemon.SlaveStatus()
if statusErr == mysql.ErrNotSlave ||
(statusErr == nil && !status.SlaveSQLRunning && !status.SlaveIORunning) {
// MySQL is up, but slave is either not configured or not running.
// Both SQL and IO threads are stopped, so it's probably either
// stopped on purpose, or stopped because of a mysqld restart.
if !r.agent.slaveStopped() {
// As far as we've been told, it isn't stopped on purpose,
// so let's try to start it.
if *mysqlctl.DisableActiveReparents {
log.Infof("Slave is stopped. Running with --disable_active_reparents so will not try to reconnect to master...")
} else {
log.Infof("Slave is stopped. Trying to reconnect to master...")
ctx, cancel := context.WithTimeout(r.agent.batchCtx, 5*time.Second)
if err := repairReplication(ctx, r.agent); err != nil {
log.Infof("Failed to reconnect to master: %v", err)
}
cancel()
// Check status again.
status, statusErr = r.agent.MysqlDaemon.SlaveStatus()
}
}
}
if statusErr != nil {
// mysqld is not running or slave is not configured.
// We can't report healthy.
return 0, statusErr
}
if !status.SlaveRunning() {
// mysqld is running, but slave is not replicating (most likely,
// replication has been stopped). See if we can extrapolate.
if r.lastKnownTime.IsZero() {
// we can't.
return 0, health.ErrSlaveNotRunning
}
// we can extrapolate with the worst possible
// value (that is we made no replication
// progress since last time, and just fell more behind).
elapsed := r.now().Sub(r.lastKnownTime)
return elapsed + r.lastKnownValue, nil
}
// we got a real value, save it.
r.lastKnownValue = time.Duration(status.SecondsBehindMaster) * time.Second
r.lastKnownTime = r.now()
return r.lastKnownValue, nil
} | [
"func",
"(",
"r",
"*",
"replicationReporter",
")",
"Report",
"(",
"isSlaveType",
",",
"shouldQueryServiceBeRunning",
"bool",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"if",
"!",
"isSlaveType",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"\n\n",
"status",
",",
"statusErr",
":=",
"r",
".",
"agent",
".",
"MysqlDaemon",
".",
"SlaveStatus",
"(",
")",
"\n",
"if",
"statusErr",
"==",
"mysql",
".",
"ErrNotSlave",
"||",
"(",
"statusErr",
"==",
"nil",
"&&",
"!",
"status",
".",
"SlaveSQLRunning",
"&&",
"!",
"status",
".",
"SlaveIORunning",
")",
"{",
"// MySQL is up, but slave is either not configured or not running.",
"// Both SQL and IO threads are stopped, so it's probably either",
"// stopped on purpose, or stopped because of a mysqld restart.",
"if",
"!",
"r",
".",
"agent",
".",
"slaveStopped",
"(",
")",
"{",
"// As far as we've been told, it isn't stopped on purpose,",
"// so let's try to start it.",
"if",
"*",
"mysqlctl",
".",
"DisableActiveReparents",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"r",
".",
"agent",
".",
"batchCtx",
",",
"5",
"*",
"time",
".",
"Second",
")",
"\n",
"if",
"err",
":=",
"repairReplication",
"(",
"ctx",
",",
"r",
".",
"agent",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cancel",
"(",
")",
"\n",
"// Check status again.",
"status",
",",
"statusErr",
"=",
"r",
".",
"agent",
".",
"MysqlDaemon",
".",
"SlaveStatus",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"statusErr",
"!=",
"nil",
"{",
"// mysqld is not running or slave is not configured.",
"// We can't report healthy.",
"return",
"0",
",",
"statusErr",
"\n",
"}",
"\n",
"if",
"!",
"status",
".",
"SlaveRunning",
"(",
")",
"{",
"// mysqld is running, but slave is not replicating (most likely,",
"// replication has been stopped). See if we can extrapolate.",
"if",
"r",
".",
"lastKnownTime",
".",
"IsZero",
"(",
")",
"{",
"// we can't.",
"return",
"0",
",",
"health",
".",
"ErrSlaveNotRunning",
"\n",
"}",
"\n\n",
"// we can extrapolate with the worst possible",
"// value (that is we made no replication",
"// progress since last time, and just fell more behind).",
"elapsed",
":=",
"r",
".",
"now",
"(",
")",
".",
"Sub",
"(",
"r",
".",
"lastKnownTime",
")",
"\n",
"return",
"elapsed",
"+",
"r",
".",
"lastKnownValue",
",",
"nil",
"\n",
"}",
"\n\n",
"// we got a real value, save it.",
"r",
".",
"lastKnownValue",
"=",
"time",
".",
"Duration",
"(",
"status",
".",
"SecondsBehindMaster",
")",
"*",
"time",
".",
"Second",
"\n",
"r",
".",
"lastKnownTime",
"=",
"r",
".",
"now",
"(",
")",
"\n",
"return",
"r",
".",
"lastKnownValue",
",",
"nil",
"\n",
"}"
] | // Report is part of the health.Reporter interface | [
"Report",
"is",
"part",
"of",
"the",
"health",
".",
"Reporter",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/replication_reporter.go#L52-L104 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/replication_reporter.go | repairReplication | func repairReplication(ctx context.Context, agent *ActionAgent) error {
if *mysqlctl.DisableActiveReparents {
return fmt.Errorf("can't repair replication with --disable_active_reparents")
}
ts := agent.TopoServer
tablet := agent.Tablet()
si, err := ts.GetShard(ctx, tablet.Keyspace, tablet.Shard)
if err != nil {
return err
}
if !si.HasMaster() {
return fmt.Errorf("no master tablet for shard %v/%v", tablet.Keyspace, tablet.Shard)
}
// If Orchestrator is configured and if Orchestrator is actively reparenting, we should not repairReplication
if agent.orc != nil {
re, err := agent.orc.InActiveShardRecovery(tablet)
if err != nil {
return err
}
if re {
return fmt.Errorf("orchestrator actively reparenting shard %v, skipping repairReplication", si)
}
// Before repairing replication, tell Orchestrator to enter maintenance mode for this tablet and to
// lock any other actions on this tablet by Orchestrator.
if err := agent.orc.BeginMaintenance(agent.Tablet(), "vttablet has been told to StopSlave"); err != nil {
log.Warningf("Orchestrator BeginMaintenance failed: %v", err)
return vterrors.Wrap(err, "orchestrator BeginMaintenance failed, skipping repairReplication")
}
}
return agent.setMasterRepairReplication(ctx, si.MasterAlias, 0, true)
} | go | func repairReplication(ctx context.Context, agent *ActionAgent) error {
if *mysqlctl.DisableActiveReparents {
return fmt.Errorf("can't repair replication with --disable_active_reparents")
}
ts := agent.TopoServer
tablet := agent.Tablet()
si, err := ts.GetShard(ctx, tablet.Keyspace, tablet.Shard)
if err != nil {
return err
}
if !si.HasMaster() {
return fmt.Errorf("no master tablet for shard %v/%v", tablet.Keyspace, tablet.Shard)
}
// If Orchestrator is configured and if Orchestrator is actively reparenting, we should not repairReplication
if agent.orc != nil {
re, err := agent.orc.InActiveShardRecovery(tablet)
if err != nil {
return err
}
if re {
return fmt.Errorf("orchestrator actively reparenting shard %v, skipping repairReplication", si)
}
// Before repairing replication, tell Orchestrator to enter maintenance mode for this tablet and to
// lock any other actions on this tablet by Orchestrator.
if err := agent.orc.BeginMaintenance(agent.Tablet(), "vttablet has been told to StopSlave"); err != nil {
log.Warningf("Orchestrator BeginMaintenance failed: %v", err)
return vterrors.Wrap(err, "orchestrator BeginMaintenance failed, skipping repairReplication")
}
}
return agent.setMasterRepairReplication(ctx, si.MasterAlias, 0, true)
} | [
"func",
"repairReplication",
"(",
"ctx",
"context",
".",
"Context",
",",
"agent",
"*",
"ActionAgent",
")",
"error",
"{",
"if",
"*",
"mysqlctl",
".",
"DisableActiveReparents",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"ts",
":=",
"agent",
".",
"TopoServer",
"\n",
"tablet",
":=",
"agent",
".",
"Tablet",
"(",
")",
"\n\n",
"si",
",",
"err",
":=",
"ts",
".",
"GetShard",
"(",
"ctx",
",",
"tablet",
".",
"Keyspace",
",",
"tablet",
".",
"Shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"si",
".",
"HasMaster",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tablet",
".",
"Keyspace",
",",
"tablet",
".",
"Shard",
")",
"\n",
"}",
"\n\n",
"// If Orchestrator is configured and if Orchestrator is actively reparenting, we should not repairReplication",
"if",
"agent",
".",
"orc",
"!=",
"nil",
"{",
"re",
",",
"err",
":=",
"agent",
".",
"orc",
".",
"InActiveShardRecovery",
"(",
"tablet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"re",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"si",
")",
"\n",
"}",
"\n\n",
"// Before repairing replication, tell Orchestrator to enter maintenance mode for this tablet and to",
"// lock any other actions on this tablet by Orchestrator.",
"if",
"err",
":=",
"agent",
".",
"orc",
".",
"BeginMaintenance",
"(",
"agent",
".",
"Tablet",
"(",
")",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"agent",
".",
"setMasterRepairReplication",
"(",
"ctx",
",",
"si",
".",
"MasterAlias",
",",
"0",
",",
"true",
")",
"\n",
"}"
] | // repairReplication tries to connect this slave to whoever is
// the current master of the shard, and start replicating. | [
"repairReplication",
"tries",
"to",
"connect",
"this",
"slave",
"to",
"whoever",
"is",
"the",
"current",
"master",
"of",
"the",
"shard",
"and",
"start",
"replicating",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/replication_reporter.go#L113-L148 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | RegisterStats | func (dg *discoveryGateway) RegisterStats() {
stats.NewGaugeDurationFunc(
"TopologyWatcherMaxRefreshLag",
"maximum time since the topology watcher refreshed a cell",
dg.topologyWatcherMaxRefreshLag,
)
stats.NewGaugeFunc(
"TopologyWatcherChecksum",
"crc32 checksum of the topology watcher state",
dg.topologyWatcherChecksum,
)
} | go | func (dg *discoveryGateway) RegisterStats() {
stats.NewGaugeDurationFunc(
"TopologyWatcherMaxRefreshLag",
"maximum time since the topology watcher refreshed a cell",
dg.topologyWatcherMaxRefreshLag,
)
stats.NewGaugeFunc(
"TopologyWatcherChecksum",
"crc32 checksum of the topology watcher state",
dg.topologyWatcherChecksum,
)
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"RegisterStats",
"(",
")",
"{",
"stats",
".",
"NewGaugeDurationFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dg",
".",
"topologyWatcherMaxRefreshLag",
",",
")",
"\n\n",
"stats",
".",
"NewGaugeFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dg",
".",
"topologyWatcherChecksum",
",",
")",
"\n",
"}"
] | // RegisterStats registers the stats to export the lag since the last refresh
// and the checksum of the topology | [
"RegisterStats",
"registers",
"the",
"stats",
"to",
"export",
"the",
"lag",
"since",
"the",
"last",
"refresh",
"and",
"the",
"checksum",
"of",
"the",
"topology"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L139-L151 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | topologyWatcherMaxRefreshLag | func (dg *discoveryGateway) topologyWatcherMaxRefreshLag() time.Duration {
var lag time.Duration
for _, tw := range dg.tabletsWatchers {
cellLag := tw.RefreshLag()
if cellLag > lag {
lag = cellLag
}
}
return lag
} | go | func (dg *discoveryGateway) topologyWatcherMaxRefreshLag() time.Duration {
var lag time.Duration
for _, tw := range dg.tabletsWatchers {
cellLag := tw.RefreshLag()
if cellLag > lag {
lag = cellLag
}
}
return lag
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"topologyWatcherMaxRefreshLag",
"(",
")",
"time",
".",
"Duration",
"{",
"var",
"lag",
"time",
".",
"Duration",
"\n",
"for",
"_",
",",
"tw",
":=",
"range",
"dg",
".",
"tabletsWatchers",
"{",
"cellLag",
":=",
"tw",
".",
"RefreshLag",
"(",
")",
"\n",
"if",
"cellLag",
">",
"lag",
"{",
"lag",
"=",
"cellLag",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"lag",
"\n",
"}"
] | // topologyWatcherMaxRefreshLag returns the maximum lag since the watched
// cells were refreshed from the topo server | [
"topologyWatcherMaxRefreshLag",
"returns",
"the",
"maximum",
"lag",
"since",
"the",
"watched",
"cells",
"were",
"refreshed",
"from",
"the",
"topo",
"server"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L155-L164 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | topologyWatcherChecksum | func (dg *discoveryGateway) topologyWatcherChecksum() int64 {
var checksum int64
for _, tw := range dg.tabletsWatchers {
checksum = checksum ^ int64(tw.TopoChecksum())
}
return checksum
} | go | func (dg *discoveryGateway) topologyWatcherChecksum() int64 {
var checksum int64
for _, tw := range dg.tabletsWatchers {
checksum = checksum ^ int64(tw.TopoChecksum())
}
return checksum
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"topologyWatcherChecksum",
"(",
")",
"int64",
"{",
"var",
"checksum",
"int64",
"\n",
"for",
"_",
",",
"tw",
":=",
"range",
"dg",
".",
"tabletsWatchers",
"{",
"checksum",
"=",
"checksum",
"^",
"int64",
"(",
"tw",
".",
"TopoChecksum",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"checksum",
"\n",
"}"
] | // topologyWatcherChecksum returns a checksum of the topology watcher state | [
"topologyWatcherChecksum",
"returns",
"a",
"checksum",
"of",
"the",
"topology",
"watcher",
"state"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L167-L173 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | StatsUpdate | func (dg *discoveryGateway) StatsUpdate(ts *discovery.TabletStats) {
dg.tsc.StatsUpdate(ts)
if ts.Target.TabletType == topodatapb.TabletType_MASTER {
dg.buffer.StatsUpdate(ts)
}
} | go | func (dg *discoveryGateway) StatsUpdate(ts *discovery.TabletStats) {
dg.tsc.StatsUpdate(ts)
if ts.Target.TabletType == topodatapb.TabletType_MASTER {
dg.buffer.StatsUpdate(ts)
}
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"StatsUpdate",
"(",
"ts",
"*",
"discovery",
".",
"TabletStats",
")",
"{",
"dg",
".",
"tsc",
".",
"StatsUpdate",
"(",
"ts",
")",
"\n\n",
"if",
"ts",
".",
"Target",
".",
"TabletType",
"==",
"topodatapb",
".",
"TabletType_MASTER",
"{",
"dg",
".",
"buffer",
".",
"StatsUpdate",
"(",
"ts",
")",
"\n",
"}",
"\n",
"}"
] | // StatsUpdate forwards HealthCheck updates to TabletStatsCache and MasterBuffer.
// It is part of the discovery.HealthCheckStatsListener interface. | [
"StatsUpdate",
"forwards",
"HealthCheck",
"updates",
"to",
"TabletStatsCache",
"and",
"MasterBuffer",
".",
"It",
"is",
"part",
"of",
"the",
"discovery",
".",
"HealthCheckStatsListener",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L177-L183 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | WaitForTablets | func (dg *discoveryGateway) WaitForTablets(ctx context.Context, tabletTypesToWait []topodatapb.TabletType) error {
// Skip waiting for tablets if we are not told to do so.
if len(tabletTypesToWait) == 0 {
return nil
}
// Finds the targets to look for.
targets, err := srvtopo.FindAllTargets(ctx, dg.srvTopoServer, dg.localCell, tabletTypesToWait)
if err != nil {
return err
}
return dg.tsc.WaitForAllServingTablets(ctx, targets)
} | go | func (dg *discoveryGateway) WaitForTablets(ctx context.Context, tabletTypesToWait []topodatapb.TabletType) error {
// Skip waiting for tablets if we are not told to do so.
if len(tabletTypesToWait) == 0 {
return nil
}
// Finds the targets to look for.
targets, err := srvtopo.FindAllTargets(ctx, dg.srvTopoServer, dg.localCell, tabletTypesToWait)
if err != nil {
return err
}
return dg.tsc.WaitForAllServingTablets(ctx, targets)
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"WaitForTablets",
"(",
"ctx",
"context",
".",
"Context",
",",
"tabletTypesToWait",
"[",
"]",
"topodatapb",
".",
"TabletType",
")",
"error",
"{",
"// Skip waiting for tablets if we are not told to do so.",
"if",
"len",
"(",
"tabletTypesToWait",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Finds the targets to look for.",
"targets",
",",
"err",
":=",
"srvtopo",
".",
"FindAllTargets",
"(",
"ctx",
",",
"dg",
".",
"srvTopoServer",
",",
"dg",
".",
"localCell",
",",
"tabletTypesToWait",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"dg",
".",
"tsc",
".",
"WaitForAllServingTablets",
"(",
"ctx",
",",
"targets",
")",
"\n",
"}"
] | // WaitForTablets is part of the gateway.Gateway interface. | [
"WaitForTablets",
"is",
"part",
"of",
"the",
"gateway",
".",
"Gateway",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L186-L199 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | GetAggregateStats | func (dg *discoveryGateway) GetAggregateStats(target *querypb.Target) (*querypb.AggregateStats, queryservice.QueryService, error) {
stats, err := dg.tsc.GetAggregateStats(target)
return stats, dg, err
} | go | func (dg *discoveryGateway) GetAggregateStats(target *querypb.Target) (*querypb.AggregateStats, queryservice.QueryService, error) {
stats, err := dg.tsc.GetAggregateStats(target)
return stats, dg, err
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"GetAggregateStats",
"(",
"target",
"*",
"querypb",
".",
"Target",
")",
"(",
"*",
"querypb",
".",
"AggregateStats",
",",
"queryservice",
".",
"QueryService",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"dg",
".",
"tsc",
".",
"GetAggregateStats",
"(",
"target",
")",
"\n",
"return",
"stats",
",",
"dg",
",",
"err",
"\n",
"}"
] | // GetAggregateStats is part of the srvtopo.TargetStats interface. | [
"GetAggregateStats",
"is",
"part",
"of",
"the",
"srvtopo",
".",
"TargetStats",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L202-L205 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | GetMasterCell | func (dg *discoveryGateway) GetMasterCell(keyspace, shard string) (string, queryservice.QueryService, error) {
cell, err := dg.tsc.GetMasterCell(keyspace, shard)
return cell, dg, err
} | go | func (dg *discoveryGateway) GetMasterCell(keyspace, shard string) (string, queryservice.QueryService, error) {
cell, err := dg.tsc.GetMasterCell(keyspace, shard)
return cell, dg, err
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"GetMasterCell",
"(",
"keyspace",
",",
"shard",
"string",
")",
"(",
"string",
",",
"queryservice",
".",
"QueryService",
",",
"error",
")",
"{",
"cell",
",",
"err",
":=",
"dg",
".",
"tsc",
".",
"GetMasterCell",
"(",
"keyspace",
",",
"shard",
")",
"\n",
"return",
"cell",
",",
"dg",
",",
"err",
"\n",
"}"
] | // GetMasterCell is part of the srvtopo.TargetStats interface. | [
"GetMasterCell",
"is",
"part",
"of",
"the",
"srvtopo",
".",
"TargetStats",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L208-L211 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | Close | func (dg *discoveryGateway) Close(ctx context.Context) error {
dg.buffer.Shutdown()
for _, ctw := range dg.tabletsWatchers {
ctw.Stop()
}
return nil
} | go | func (dg *discoveryGateway) Close(ctx context.Context) error {
dg.buffer.Shutdown()
for _, ctw := range dg.tabletsWatchers {
ctw.Stop()
}
return nil
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"Close",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"dg",
".",
"buffer",
".",
"Shutdown",
"(",
")",
"\n",
"for",
"_",
",",
"ctw",
":=",
"range",
"dg",
".",
"tabletsWatchers",
"{",
"ctw",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close shuts down underlying connections.
// This function hides the inner implementation. | [
"Close",
"shuts",
"down",
"underlying",
"connections",
".",
"This",
"function",
"hides",
"the",
"inner",
"implementation",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L215-L221 | train |
vitessio/vitess | go/vt/vtgate/gateway/discoverygateway.go | withRetry | func (dg *discoveryGateway) withRetry(ctx context.Context, target *querypb.Target, unused queryservice.QueryService, name string, inTransaction bool, inner func(ctx context.Context, target *querypb.Target, conn queryservice.QueryService) (bool, error)) error {
var tabletLastUsed *topodatapb.Tablet
var err error
invalidTablets := make(map[string]bool)
if len(allowedTabletTypes) > 0 {
var match bool
for _, allowed := range allowedTabletTypes {
if allowed == target.TabletType {
match = true
break
}
}
if !match {
return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "requested tablet type %v is not part of the allowed tablet types for this vtgate: %+v", target.TabletType.String(), allowedTabletTypes)
}
}
bufferedOnce := false
for i := 0; i < dg.retryCount+1; i++ {
// Check if we should buffer MASTER queries which failed due to an ongoing
// failover.
// Note: We only buffer once and only "!inTransaction" queries i.e.
// a) no transaction is necessary (e.g. critical reads) or
// b) no transaction was created yet.
if !bufferedOnce && !inTransaction && target.TabletType == topodatapb.TabletType_MASTER {
// The next call blocks if we should buffer during a failover.
retryDone, bufferErr := dg.buffer.WaitForFailoverEnd(ctx, target.Keyspace, target.Shard, err)
if bufferErr != nil {
// Buffering failed e.g. buffer is already full. Do not retry.
err = vterrors.Errorf(
vterrors.Code(bufferErr),
"failed to automatically buffer and retry failed request during failover: %v original err (type=%T): %v",
bufferErr, err, err)
break
}
// Request may have been buffered.
if retryDone != nil {
// We're going to retry this request as part of a buffer drain.
// Notify the buffer after we retried.
defer retryDone()
bufferedOnce = true
}
}
tablets := dg.tsc.GetHealthyTabletStats(target.Keyspace, target.Shard, target.TabletType)
if len(tablets) == 0 {
// fail fast if there is no tablet
err = vterrors.New(vtrpcpb.Code_UNAVAILABLE, "no valid tablet")
break
}
shuffleTablets(dg.localCell, tablets)
// skip tablets we tried before
var ts *discovery.TabletStats
for _, t := range tablets {
if _, ok := invalidTablets[t.Key]; !ok {
ts = &t
break
}
}
if ts == nil {
if err == nil {
// do not override error from last attempt.
err = vterrors.New(vtrpcpb.Code_UNAVAILABLE, "no available connection")
}
break
}
// execute
tabletLastUsed = ts.Tablet
conn := dg.hc.GetConnection(ts.Key)
if conn == nil {
err = vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "no connection for key %v tablet %+v", ts.Key, ts.Tablet)
invalidTablets[ts.Key] = true
continue
}
startTime := time.Now()
var canRetry bool
canRetry, err = inner(ctx, ts.Target, conn)
dg.updateStats(target, startTime, err)
if canRetry {
invalidTablets[ts.Key] = true
continue
}
break
}
return NewShardError(err, target, tabletLastUsed)
} | go | func (dg *discoveryGateway) withRetry(ctx context.Context, target *querypb.Target, unused queryservice.QueryService, name string, inTransaction bool, inner func(ctx context.Context, target *querypb.Target, conn queryservice.QueryService) (bool, error)) error {
var tabletLastUsed *topodatapb.Tablet
var err error
invalidTablets := make(map[string]bool)
if len(allowedTabletTypes) > 0 {
var match bool
for _, allowed := range allowedTabletTypes {
if allowed == target.TabletType {
match = true
break
}
}
if !match {
return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "requested tablet type %v is not part of the allowed tablet types for this vtgate: %+v", target.TabletType.String(), allowedTabletTypes)
}
}
bufferedOnce := false
for i := 0; i < dg.retryCount+1; i++ {
// Check if we should buffer MASTER queries which failed due to an ongoing
// failover.
// Note: We only buffer once and only "!inTransaction" queries i.e.
// a) no transaction is necessary (e.g. critical reads) or
// b) no transaction was created yet.
if !bufferedOnce && !inTransaction && target.TabletType == topodatapb.TabletType_MASTER {
// The next call blocks if we should buffer during a failover.
retryDone, bufferErr := dg.buffer.WaitForFailoverEnd(ctx, target.Keyspace, target.Shard, err)
if bufferErr != nil {
// Buffering failed e.g. buffer is already full. Do not retry.
err = vterrors.Errorf(
vterrors.Code(bufferErr),
"failed to automatically buffer and retry failed request during failover: %v original err (type=%T): %v",
bufferErr, err, err)
break
}
// Request may have been buffered.
if retryDone != nil {
// We're going to retry this request as part of a buffer drain.
// Notify the buffer after we retried.
defer retryDone()
bufferedOnce = true
}
}
tablets := dg.tsc.GetHealthyTabletStats(target.Keyspace, target.Shard, target.TabletType)
if len(tablets) == 0 {
// fail fast if there is no tablet
err = vterrors.New(vtrpcpb.Code_UNAVAILABLE, "no valid tablet")
break
}
shuffleTablets(dg.localCell, tablets)
// skip tablets we tried before
var ts *discovery.TabletStats
for _, t := range tablets {
if _, ok := invalidTablets[t.Key]; !ok {
ts = &t
break
}
}
if ts == nil {
if err == nil {
// do not override error from last attempt.
err = vterrors.New(vtrpcpb.Code_UNAVAILABLE, "no available connection")
}
break
}
// execute
tabletLastUsed = ts.Tablet
conn := dg.hc.GetConnection(ts.Key)
if conn == nil {
err = vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "no connection for key %v tablet %+v", ts.Key, ts.Tablet)
invalidTablets[ts.Key] = true
continue
}
startTime := time.Now()
var canRetry bool
canRetry, err = inner(ctx, ts.Target, conn)
dg.updateStats(target, startTime, err)
if canRetry {
invalidTablets[ts.Key] = true
continue
}
break
}
return NewShardError(err, target, tabletLastUsed)
} | [
"func",
"(",
"dg",
"*",
"discoveryGateway",
")",
"withRetry",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"unused",
"queryservice",
".",
"QueryService",
",",
"name",
"string",
",",
"inTransaction",
"bool",
",",
"inner",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"conn",
"queryservice",
".",
"QueryService",
")",
"(",
"bool",
",",
"error",
")",
")",
"error",
"{",
"var",
"tabletLastUsed",
"*",
"topodatapb",
".",
"Tablet",
"\n",
"var",
"err",
"error",
"\n",
"invalidTablets",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n\n",
"if",
"len",
"(",
"allowedTabletTypes",
")",
">",
"0",
"{",
"var",
"match",
"bool",
"\n",
"for",
"_",
",",
"allowed",
":=",
"range",
"allowedTabletTypes",
"{",
"if",
"allowed",
"==",
"target",
".",
"TabletType",
"{",
"match",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"match",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpcpb",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
",",
"target",
".",
"TabletType",
".",
"String",
"(",
")",
",",
"allowedTabletTypes",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"bufferedOnce",
":=",
"false",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"dg",
".",
"retryCount",
"+",
"1",
";",
"i",
"++",
"{",
"// Check if we should buffer MASTER queries which failed due to an ongoing",
"// failover.",
"// Note: We only buffer once and only \"!inTransaction\" queries i.e.",
"// a) no transaction is necessary (e.g. critical reads) or",
"// b) no transaction was created yet.",
"if",
"!",
"bufferedOnce",
"&&",
"!",
"inTransaction",
"&&",
"target",
".",
"TabletType",
"==",
"topodatapb",
".",
"TabletType_MASTER",
"{",
"// The next call blocks if we should buffer during a failover.",
"retryDone",
",",
"bufferErr",
":=",
"dg",
".",
"buffer",
".",
"WaitForFailoverEnd",
"(",
"ctx",
",",
"target",
".",
"Keyspace",
",",
"target",
".",
"Shard",
",",
"err",
")",
"\n",
"if",
"bufferErr",
"!=",
"nil",
"{",
"// Buffering failed e.g. buffer is already full. Do not retry.",
"err",
"=",
"vterrors",
".",
"Errorf",
"(",
"vterrors",
".",
"Code",
"(",
"bufferErr",
")",
",",
"\"",
"\"",
",",
"bufferErr",
",",
"err",
",",
"err",
")",
"\n",
"break",
"\n",
"}",
"\n\n",
"// Request may have been buffered.",
"if",
"retryDone",
"!=",
"nil",
"{",
"// We're going to retry this request as part of a buffer drain.",
"// Notify the buffer after we retried.",
"defer",
"retryDone",
"(",
")",
"\n",
"bufferedOnce",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"tablets",
":=",
"dg",
".",
"tsc",
".",
"GetHealthyTabletStats",
"(",
"target",
".",
"Keyspace",
",",
"target",
".",
"Shard",
",",
"target",
".",
"TabletType",
")",
"\n",
"if",
"len",
"(",
"tablets",
")",
"==",
"0",
"{",
"// fail fast if there is no tablet",
"err",
"=",
"vterrors",
".",
"New",
"(",
"vtrpcpb",
".",
"Code_UNAVAILABLE",
",",
"\"",
"\"",
")",
"\n",
"break",
"\n",
"}",
"\n",
"shuffleTablets",
"(",
"dg",
".",
"localCell",
",",
"tablets",
")",
"\n\n",
"// skip tablets we tried before",
"var",
"ts",
"*",
"discovery",
".",
"TabletStats",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tablets",
"{",
"if",
"_",
",",
"ok",
":=",
"invalidTablets",
"[",
"t",
".",
"Key",
"]",
";",
"!",
"ok",
"{",
"ts",
"=",
"&",
"t",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"ts",
"==",
"nil",
"{",
"if",
"err",
"==",
"nil",
"{",
"// do not override error from last attempt.",
"err",
"=",
"vterrors",
".",
"New",
"(",
"vtrpcpb",
".",
"Code_UNAVAILABLE",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n\n",
"// execute",
"tabletLastUsed",
"=",
"ts",
".",
"Tablet",
"\n",
"conn",
":=",
"dg",
".",
"hc",
".",
"GetConnection",
"(",
"ts",
".",
"Key",
")",
"\n",
"if",
"conn",
"==",
"nil",
"{",
"err",
"=",
"vterrors",
".",
"Errorf",
"(",
"vtrpcpb",
".",
"Code_UNAVAILABLE",
",",
"\"",
"\"",
",",
"ts",
".",
"Key",
",",
"ts",
".",
"Tablet",
")",
"\n",
"invalidTablets",
"[",
"ts",
".",
"Key",
"]",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n\n",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"var",
"canRetry",
"bool",
"\n",
"canRetry",
",",
"err",
"=",
"inner",
"(",
"ctx",
",",
"ts",
".",
"Target",
",",
"conn",
")",
"\n",
"dg",
".",
"updateStats",
"(",
"target",
",",
"startTime",
",",
"err",
")",
"\n",
"if",
"canRetry",
"{",
"invalidTablets",
"[",
"ts",
".",
"Key",
"]",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"return",
"NewShardError",
"(",
"err",
",",
"target",
",",
"tabletLastUsed",
")",
"\n",
"}"
] | // withRetry gets available connections and executes the action. If there are retryable errors,
// it retries retryCount times before failing. It does not retry if the connection is in
// the middle of a transaction. While returning the error check if it maybe a result of
// a resharding event, and set the re-resolve bit and let the upper layers
// re-resolve and retry. | [
"withRetry",
"gets",
"available",
"connections",
"and",
"executes",
"the",
"action",
".",
"If",
"there",
"are",
"retryable",
"errors",
"it",
"retries",
"retryCount",
"times",
"before",
"failing",
".",
"It",
"does",
"not",
"retry",
"if",
"the",
"connection",
"is",
"in",
"the",
"middle",
"of",
"a",
"transaction",
".",
"While",
"returning",
"the",
"error",
"check",
"if",
"it",
"maybe",
"a",
"result",
"of",
"a",
"resharding",
"event",
"and",
"set",
"the",
"re",
"-",
"resolve",
"bit",
"and",
"let",
"the",
"upper",
"layers",
"re",
"-",
"resolve",
"and",
"retry",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/discoverygateway.go#L241-L331 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateFullQuery | func GenerateFullQuery(statement sqlparser.Statement) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
statement.Format(buf)
return buf.ParsedQuery()
} | go | func GenerateFullQuery(statement sqlparser.Statement) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
statement.Format(buf)
return buf.ParsedQuery()
} | [
"func",
"GenerateFullQuery",
"(",
"statement",
"sqlparser",
".",
"Statement",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"buf",
":=",
"sqlparser",
".",
"NewTrackedBuffer",
"(",
"nil",
")",
"\n",
"statement",
".",
"Format",
"(",
"buf",
")",
"\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // GenerateFullQuery generates the full query from the ast. | [
"GenerateFullQuery",
"generates",
"the",
"full",
"query",
"from",
"the",
"ast",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L25-L29 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateFieldQuery | func GenerateFieldQuery(statement sqlparser.Statement) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(sqlparser.FormatImpossibleQuery).WriteNode(statement)
if buf.HasBindVars() {
return nil
}
return buf.ParsedQuery()
} | go | func GenerateFieldQuery(statement sqlparser.Statement) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(sqlparser.FormatImpossibleQuery).WriteNode(statement)
if buf.HasBindVars() {
return nil
}
return buf.ParsedQuery()
} | [
"func",
"GenerateFieldQuery",
"(",
"statement",
"sqlparser",
".",
"Statement",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"buf",
":=",
"sqlparser",
".",
"NewTrackedBuffer",
"(",
"sqlparser",
".",
"FormatImpossibleQuery",
")",
".",
"WriteNode",
"(",
"statement",
")",
"\n\n",
"if",
"buf",
".",
"HasBindVars",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // GenerateFieldQuery generates a query to just fetch the field info
// by adding impossible where clauses as needed. | [
"GenerateFieldQuery",
"generates",
"a",
"query",
"to",
"just",
"fetch",
"the",
"field",
"info",
"by",
"adding",
"impossible",
"where",
"clauses",
"as",
"needed",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L33-L41 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateLimitQuery | func GenerateLimitQuery(selStmt sqlparser.SelectStatement) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
switch sel := selStmt.(type) {
case *sqlparser.Select:
limit := sel.Limit
if limit == nil {
sel.Limit = execLimit
defer func() {
sel.Limit = nil
}()
}
case *sqlparser.Union:
// Code is identical to *Select, but this one is a *Union.
limit := sel.Limit
if limit == nil {
sel.Limit = execLimit
defer func() {
sel.Limit = nil
}()
}
}
buf.Myprintf("%v", selStmt)
return buf.ParsedQuery()
} | go | func GenerateLimitQuery(selStmt sqlparser.SelectStatement) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
switch sel := selStmt.(type) {
case *sqlparser.Select:
limit := sel.Limit
if limit == nil {
sel.Limit = execLimit
defer func() {
sel.Limit = nil
}()
}
case *sqlparser.Union:
// Code is identical to *Select, but this one is a *Union.
limit := sel.Limit
if limit == nil {
sel.Limit = execLimit
defer func() {
sel.Limit = nil
}()
}
}
buf.Myprintf("%v", selStmt)
return buf.ParsedQuery()
} | [
"func",
"GenerateLimitQuery",
"(",
"selStmt",
"sqlparser",
".",
"SelectStatement",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"buf",
":=",
"sqlparser",
".",
"NewTrackedBuffer",
"(",
"nil",
")",
"\n",
"switch",
"sel",
":=",
"selStmt",
".",
"(",
"type",
")",
"{",
"case",
"*",
"sqlparser",
".",
"Select",
":",
"limit",
":=",
"sel",
".",
"Limit",
"\n",
"if",
"limit",
"==",
"nil",
"{",
"sel",
".",
"Limit",
"=",
"execLimit",
"\n",
"defer",
"func",
"(",
")",
"{",
"sel",
".",
"Limit",
"=",
"nil",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"case",
"*",
"sqlparser",
".",
"Union",
":",
"// Code is identical to *Select, but this one is a *Union.",
"limit",
":=",
"sel",
".",
"Limit",
"\n",
"if",
"limit",
"==",
"nil",
"{",
"sel",
".",
"Limit",
"=",
"execLimit",
"\n",
"defer",
"func",
"(",
")",
"{",
"sel",
".",
"Limit",
"=",
"nil",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"buf",
".",
"Myprintf",
"(",
"\"",
"\"",
",",
"selStmt",
")",
"\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // GenerateLimitQuery generates a select query with a limit clause. | [
"GenerateLimitQuery",
"generates",
"a",
"select",
"query",
"with",
"a",
"limit",
"clause",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L44-L67 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateInsertOuterQuery | func GenerateInsertOuterQuery(ins *sqlparser.Insert) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("%s %v%sinto %v%v values %a",
ins.Action,
ins.Comments,
ins.Ignore,
ins.Table,
ins.Columns,
":#values",
)
return buf.ParsedQuery()
} | go | func GenerateInsertOuterQuery(ins *sqlparser.Insert) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("%s %v%sinto %v%v values %a",
ins.Action,
ins.Comments,
ins.Ignore,
ins.Table,
ins.Columns,
":#values",
)
return buf.ParsedQuery()
} | [
"func",
"GenerateInsertOuterQuery",
"(",
"ins",
"*",
"sqlparser",
".",
"Insert",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"buf",
":=",
"sqlparser",
".",
"NewTrackedBuffer",
"(",
"nil",
")",
"\n",
"buf",
".",
"Myprintf",
"(",
"\"",
"\"",
",",
"ins",
".",
"Action",
",",
"ins",
".",
"Comments",
",",
"ins",
".",
"Ignore",
",",
"ins",
".",
"Table",
",",
"ins",
".",
"Columns",
",",
"\"",
"\"",
",",
")",
"\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // GenerateInsertOuterQuery generates the outer query for inserts. | [
"GenerateInsertOuterQuery",
"generates",
"the",
"outer",
"query",
"for",
"inserts",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L70-L81 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateUpdateOuterQuery | func GenerateUpdateOuterQuery(upd *sqlparser.Update, aliased *sqlparser.AliasedTableExpr, formatter sqlparser.NodeFormatter) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(formatter)
buf.Myprintf("update %v%v set %v where %a%v", upd.Comments, aliased.RemoveHints(), upd.Exprs, ":#pk", upd.OrderBy)
return buf.ParsedQuery()
} | go | func GenerateUpdateOuterQuery(upd *sqlparser.Update, aliased *sqlparser.AliasedTableExpr, formatter sqlparser.NodeFormatter) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(formatter)
buf.Myprintf("update %v%v set %v where %a%v", upd.Comments, aliased.RemoveHints(), upd.Exprs, ":#pk", upd.OrderBy)
return buf.ParsedQuery()
} | [
"func",
"GenerateUpdateOuterQuery",
"(",
"upd",
"*",
"sqlparser",
".",
"Update",
",",
"aliased",
"*",
"sqlparser",
".",
"AliasedTableExpr",
",",
"formatter",
"sqlparser",
".",
"NodeFormatter",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"buf",
":=",
"sqlparser",
".",
"NewTrackedBuffer",
"(",
"formatter",
")",
"\n",
"buf",
".",
"Myprintf",
"(",
"\"",
"\"",
",",
"upd",
".",
"Comments",
",",
"aliased",
".",
"RemoveHints",
"(",
")",
",",
"upd",
".",
"Exprs",
",",
"\"",
"\"",
",",
"upd",
".",
"OrderBy",
")",
"\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // GenerateUpdateOuterQuery generates the outer query for updates.
// If there is no custom formatting needed, formatter can be nil. | [
"GenerateUpdateOuterQuery",
"generates",
"the",
"outer",
"query",
"for",
"updates",
".",
"If",
"there",
"is",
"no",
"custom",
"formatting",
"needed",
"formatter",
"can",
"be",
"nil",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L85-L89 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateDeleteOuterQuery | func GenerateDeleteOuterQuery(del *sqlparser.Delete, aliased *sqlparser.AliasedTableExpr) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("delete %vfrom %v where %a%v", del.Comments, aliased.RemoveHints(), ":#pk", del.OrderBy)
return buf.ParsedQuery()
} | go | func GenerateDeleteOuterQuery(del *sqlparser.Delete, aliased *sqlparser.AliasedTableExpr) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("delete %vfrom %v where %a%v", del.Comments, aliased.RemoveHints(), ":#pk", del.OrderBy)
return buf.ParsedQuery()
} | [
"func",
"GenerateDeleteOuterQuery",
"(",
"del",
"*",
"sqlparser",
".",
"Delete",
",",
"aliased",
"*",
"sqlparser",
".",
"AliasedTableExpr",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"buf",
":=",
"sqlparser",
".",
"NewTrackedBuffer",
"(",
"nil",
")",
"\n",
"buf",
".",
"Myprintf",
"(",
"\"",
"\"",
",",
"del",
".",
"Comments",
",",
"aliased",
".",
"RemoveHints",
"(",
")",
",",
"\"",
"\"",
",",
"del",
".",
"OrderBy",
")",
"\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // GenerateDeleteOuterQuery generates the outer query for deletes. | [
"GenerateDeleteOuterQuery",
"generates",
"the",
"outer",
"query",
"for",
"deletes",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L92-L96 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateUpdateSubquery | func GenerateUpdateSubquery(upd *sqlparser.Update, table *schema.Table, aliased *sqlparser.AliasedTableExpr) *sqlparser.ParsedQuery {
return GenerateSubquery(
table.Indexes[0].Columns,
aliased,
upd.Where,
upd.OrderBy,
upd.Limit,
true,
)
} | go | func GenerateUpdateSubquery(upd *sqlparser.Update, table *schema.Table, aliased *sqlparser.AliasedTableExpr) *sqlparser.ParsedQuery {
return GenerateSubquery(
table.Indexes[0].Columns,
aliased,
upd.Where,
upd.OrderBy,
upd.Limit,
true,
)
} | [
"func",
"GenerateUpdateSubquery",
"(",
"upd",
"*",
"sqlparser",
".",
"Update",
",",
"table",
"*",
"schema",
".",
"Table",
",",
"aliased",
"*",
"sqlparser",
".",
"AliasedTableExpr",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"return",
"GenerateSubquery",
"(",
"table",
".",
"Indexes",
"[",
"0",
"]",
".",
"Columns",
",",
"aliased",
",",
"upd",
".",
"Where",
",",
"upd",
".",
"OrderBy",
",",
"upd",
".",
"Limit",
",",
"true",
",",
")",
"\n",
"}"
] | // GenerateUpdateSubquery generates the subquery for updates. | [
"GenerateUpdateSubquery",
"generates",
"the",
"subquery",
"for",
"updates",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L99-L108 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateDeleteSubquery | func GenerateDeleteSubquery(del *sqlparser.Delete, table *schema.Table, aliased *sqlparser.AliasedTableExpr) *sqlparser.ParsedQuery {
return GenerateSubquery(
table.Indexes[0].Columns,
aliased,
del.Where,
del.OrderBy,
del.Limit,
true,
)
} | go | func GenerateDeleteSubquery(del *sqlparser.Delete, table *schema.Table, aliased *sqlparser.AliasedTableExpr) *sqlparser.ParsedQuery {
return GenerateSubquery(
table.Indexes[0].Columns,
aliased,
del.Where,
del.OrderBy,
del.Limit,
true,
)
} | [
"func",
"GenerateDeleteSubquery",
"(",
"del",
"*",
"sqlparser",
".",
"Delete",
",",
"table",
"*",
"schema",
".",
"Table",
",",
"aliased",
"*",
"sqlparser",
".",
"AliasedTableExpr",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"return",
"GenerateSubquery",
"(",
"table",
".",
"Indexes",
"[",
"0",
"]",
".",
"Columns",
",",
"aliased",
",",
"del",
".",
"Where",
",",
"del",
".",
"OrderBy",
",",
"del",
".",
"Limit",
",",
"true",
",",
")",
"\n",
"}"
] | // GenerateDeleteSubquery generates the subquery for deletes. | [
"GenerateDeleteSubquery",
"generates",
"the",
"subquery",
"for",
"deletes",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L111-L120 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/query_gen.go | GenerateSubquery | func GenerateSubquery(columns []sqlparser.ColIdent, table *sqlparser.AliasedTableExpr, where *sqlparser.Where, order sqlparser.OrderBy, limit *sqlparser.Limit, forUpdate bool) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
if limit == nil {
limit = execLimit
}
buf.WriteString("select ")
prefix := ""
for _, c := range columns {
buf.Myprintf("%s%v", prefix, c)
prefix = ", "
}
buf.Myprintf(" from %v%v%v%v", table, where, order, limit)
if forUpdate {
buf.Myprintf(sqlparser.ForUpdateStr)
}
return buf.ParsedQuery()
} | go | func GenerateSubquery(columns []sqlparser.ColIdent, table *sqlparser.AliasedTableExpr, where *sqlparser.Where, order sqlparser.OrderBy, limit *sqlparser.Limit, forUpdate bool) *sqlparser.ParsedQuery {
buf := sqlparser.NewTrackedBuffer(nil)
if limit == nil {
limit = execLimit
}
buf.WriteString("select ")
prefix := ""
for _, c := range columns {
buf.Myprintf("%s%v", prefix, c)
prefix = ", "
}
buf.Myprintf(" from %v%v%v%v", table, where, order, limit)
if forUpdate {
buf.Myprintf(sqlparser.ForUpdateStr)
}
return buf.ParsedQuery()
} | [
"func",
"GenerateSubquery",
"(",
"columns",
"[",
"]",
"sqlparser",
".",
"ColIdent",
",",
"table",
"*",
"sqlparser",
".",
"AliasedTableExpr",
",",
"where",
"*",
"sqlparser",
".",
"Where",
",",
"order",
"sqlparser",
".",
"OrderBy",
",",
"limit",
"*",
"sqlparser",
".",
"Limit",
",",
"forUpdate",
"bool",
")",
"*",
"sqlparser",
".",
"ParsedQuery",
"{",
"buf",
":=",
"sqlparser",
".",
"NewTrackedBuffer",
"(",
"nil",
")",
"\n",
"if",
"limit",
"==",
"nil",
"{",
"limit",
"=",
"execLimit",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"prefix",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"columns",
"{",
"buf",
".",
"Myprintf",
"(",
"\"",
"\"",
",",
"prefix",
",",
"c",
")",
"\n",
"prefix",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"buf",
".",
"Myprintf",
"(",
"\"",
"\"",
",",
"table",
",",
"where",
",",
"order",
",",
"limit",
")",
"\n",
"if",
"forUpdate",
"{",
"buf",
".",
"Myprintf",
"(",
"sqlparser",
".",
"ForUpdateStr",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // GenerateSubquery generates a subquery based on the input parameters. | [
"GenerateSubquery",
"generates",
"a",
"subquery",
"based",
"on",
"the",
"input",
"parameters",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/query_gen.go#L123-L139 | train |
vitessio/vitess | go/vt/grpcclient/snappy.go | Compress | func (s SnappyCompressor) Compress(w io.Writer) (io.WriteCloser, error) {
return snappy.NewBufferedWriter(w), nil
} | go | func (s SnappyCompressor) Compress(w io.Writer) (io.WriteCloser, error) {
return snappy.NewBufferedWriter(w), nil
} | [
"func",
"(",
"s",
"SnappyCompressor",
")",
"Compress",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"io",
".",
"WriteCloser",
",",
"error",
")",
"{",
"return",
"snappy",
".",
"NewBufferedWriter",
"(",
"w",
")",
",",
"nil",
"\n",
"}"
] | // Compress wraps with a SnappyReader | [
"Compress",
"wraps",
"with",
"a",
"SnappyReader"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/grpcclient/snappy.go#L25-L27 | train |
vitessio/vitess | go/vt/grpcclient/snappy.go | Decompress | func (s SnappyCompressor) Decompress(r io.Reader) (io.Reader, error) {
return snappy.NewReader(r), nil
} | go | func (s SnappyCompressor) Decompress(r io.Reader) (io.Reader, error) {
return snappy.NewReader(r), nil
} | [
"func",
"(",
"s",
"SnappyCompressor",
")",
"Decompress",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"io",
".",
"Reader",
",",
"error",
")",
"{",
"return",
"snappy",
".",
"NewReader",
"(",
"r",
")",
",",
"nil",
"\n",
"}"
] | // Decompress wraps with a SnappyReader | [
"Decompress",
"wraps",
"with",
"a",
"SnappyReader"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/grpcclient/snappy.go#L30-L32 | train |
vitessio/vitess | go/vt/servenv/service_map.go | updateServiceMap | func updateServiceMap() {
for _, s := range serviceMapFlag {
if s[0] == '-' {
delete(serviceMap, s[1:])
} else {
serviceMap[s] = true
}
}
} | go | func updateServiceMap() {
for _, s := range serviceMapFlag {
if s[0] == '-' {
delete(serviceMap, s[1:])
} else {
serviceMap[s] = true
}
}
} | [
"func",
"updateServiceMap",
"(",
")",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"serviceMapFlag",
"{",
"if",
"s",
"[",
"0",
"]",
"==",
"'-'",
"{",
"delete",
"(",
"serviceMap",
",",
"s",
"[",
"1",
":",
"]",
")",
"\n",
"}",
"else",
"{",
"serviceMap",
"[",
"s",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // updateServiceMap takes the command line parameter, and updates the
// ServiceMap accordingly | [
"updateServiceMap",
"takes",
"the",
"command",
"line",
"parameter",
"and",
"updates",
"the",
"ServiceMap",
"accordingly"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/service_map.go#L50-L58 | train |
vitessio/vitess | go/vt/topo/tablet.go | IsTrivialTypeChange | func IsTrivialTypeChange(oldTabletType, newTabletType topodatapb.TabletType) bool {
switch oldTabletType {
case topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY, topodatapb.TabletType_SPARE, topodatapb.TabletType_BACKUP, topodatapb.TabletType_EXPERIMENTAL, topodatapb.TabletType_DRAINED:
switch newTabletType {
case topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY, topodatapb.TabletType_SPARE, topodatapb.TabletType_BACKUP, topodatapb.TabletType_EXPERIMENTAL, topodatapb.TabletType_DRAINED:
return true
}
case topodatapb.TabletType_RESTORE:
switch newTabletType {
case topodatapb.TabletType_SPARE:
return true
}
}
return false
} | go | func IsTrivialTypeChange(oldTabletType, newTabletType topodatapb.TabletType) bool {
switch oldTabletType {
case topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY, topodatapb.TabletType_SPARE, topodatapb.TabletType_BACKUP, topodatapb.TabletType_EXPERIMENTAL, topodatapb.TabletType_DRAINED:
switch newTabletType {
case topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY, topodatapb.TabletType_SPARE, topodatapb.TabletType_BACKUP, topodatapb.TabletType_EXPERIMENTAL, topodatapb.TabletType_DRAINED:
return true
}
case topodatapb.TabletType_RESTORE:
switch newTabletType {
case topodatapb.TabletType_SPARE:
return true
}
}
return false
} | [
"func",
"IsTrivialTypeChange",
"(",
"oldTabletType",
",",
"newTabletType",
"topodatapb",
".",
"TabletType",
")",
"bool",
"{",
"switch",
"oldTabletType",
"{",
"case",
"topodatapb",
".",
"TabletType_REPLICA",
",",
"topodatapb",
".",
"TabletType_RDONLY",
",",
"topodatapb",
".",
"TabletType_SPARE",
",",
"topodatapb",
".",
"TabletType_BACKUP",
",",
"topodatapb",
".",
"TabletType_EXPERIMENTAL",
",",
"topodatapb",
".",
"TabletType_DRAINED",
":",
"switch",
"newTabletType",
"{",
"case",
"topodatapb",
".",
"TabletType_REPLICA",
",",
"topodatapb",
".",
"TabletType_RDONLY",
",",
"topodatapb",
".",
"TabletType_SPARE",
",",
"topodatapb",
".",
"TabletType_BACKUP",
",",
"topodatapb",
".",
"TabletType_EXPERIMENTAL",
",",
"topodatapb",
".",
"TabletType_DRAINED",
":",
"return",
"true",
"\n",
"}",
"\n",
"case",
"topodatapb",
".",
"TabletType_RESTORE",
":",
"switch",
"newTabletType",
"{",
"case",
"topodatapb",
".",
"TabletType_SPARE",
":",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsTrivialTypeChange returns if this db type be trivially reassigned
// without changes to the replication graph | [
"IsTrivialTypeChange",
"returns",
"if",
"this",
"db",
"type",
"be",
"trivially",
"reassigned",
"without",
"changes",
"to",
"the",
"replication",
"graph"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L41-L55 | train |
vitessio/vitess | go/vt/topo/tablet.go | IsInServingGraph | func IsInServingGraph(tt topodatapb.TabletType) bool {
switch tt {
case topodatapb.TabletType_MASTER, topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY:
return true
}
return false
} | go | func IsInServingGraph(tt topodatapb.TabletType) bool {
switch tt {
case topodatapb.TabletType_MASTER, topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY:
return true
}
return false
} | [
"func",
"IsInServingGraph",
"(",
"tt",
"topodatapb",
".",
"TabletType",
")",
"bool",
"{",
"switch",
"tt",
"{",
"case",
"topodatapb",
".",
"TabletType_MASTER",
",",
"topodatapb",
".",
"TabletType_REPLICA",
",",
"topodatapb",
".",
"TabletType_RDONLY",
":",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsInServingGraph returns if a tablet appears in the serving graph | [
"IsInServingGraph",
"returns",
"if",
"a",
"tablet",
"appears",
"in",
"the",
"serving",
"graph"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L58-L64 | train |
vitessio/vitess | go/vt/topo/tablet.go | IsRunningQueryService | func IsRunningQueryService(tt topodatapb.TabletType) bool {
switch tt {
case topodatapb.TabletType_MASTER, topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY, topodatapb.TabletType_EXPERIMENTAL, topodatapb.TabletType_DRAINED:
return true
}
return false
} | go | func IsRunningQueryService(tt topodatapb.TabletType) bool {
switch tt {
case topodatapb.TabletType_MASTER, topodatapb.TabletType_REPLICA, topodatapb.TabletType_RDONLY, topodatapb.TabletType_EXPERIMENTAL, topodatapb.TabletType_DRAINED:
return true
}
return false
} | [
"func",
"IsRunningQueryService",
"(",
"tt",
"topodatapb",
".",
"TabletType",
")",
"bool",
"{",
"switch",
"tt",
"{",
"case",
"topodatapb",
".",
"TabletType_MASTER",
",",
"topodatapb",
".",
"TabletType_REPLICA",
",",
"topodatapb",
".",
"TabletType_RDONLY",
",",
"topodatapb",
".",
"TabletType_EXPERIMENTAL",
",",
"topodatapb",
".",
"TabletType_DRAINED",
":",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsRunningQueryService returns if a tablet is running the query service | [
"IsRunningQueryService",
"returns",
"if",
"a",
"tablet",
"is",
"running",
"the",
"query",
"service"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L67-L73 | train |
vitessio/vitess | go/vt/topo/tablet.go | NewTablet | func NewTablet(uid uint32, cell, host string) *topodatapb.Tablet {
return &topodatapb.Tablet{
Alias: &topodatapb.TabletAlias{
Cell: cell,
Uid: uid,
},
Hostname: host,
PortMap: make(map[string]int32),
}
} | go | func NewTablet(uid uint32, cell, host string) *topodatapb.Tablet {
return &topodatapb.Tablet{
Alias: &topodatapb.TabletAlias{
Cell: cell,
Uid: uid,
},
Hostname: host,
PortMap: make(map[string]int32),
}
} | [
"func",
"NewTablet",
"(",
"uid",
"uint32",
",",
"cell",
",",
"host",
"string",
")",
"*",
"topodatapb",
".",
"Tablet",
"{",
"return",
"&",
"topodatapb",
".",
"Tablet",
"{",
"Alias",
":",
"&",
"topodatapb",
".",
"TabletAlias",
"{",
"Cell",
":",
"cell",
",",
"Uid",
":",
"uid",
",",
"}",
",",
"Hostname",
":",
"host",
",",
"PortMap",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"int32",
")",
",",
"}",
"\n",
"}"
] | // NewTablet create a new Tablet record with the given id, cell, and hostname. | [
"NewTablet",
"create",
"a",
"new",
"Tablet",
"record",
"with",
"the",
"given",
"id",
"cell",
"and",
"hostname",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L121-L130 | train |
vitessio/vitess | go/vt/topo/tablet.go | String | func (ti *TabletInfo) String() string {
return fmt.Sprintf("Tablet{%v}", topoproto.TabletAliasString(ti.Alias))
} | go | func (ti *TabletInfo) String() string {
return fmt.Sprintf("Tablet{%v}", topoproto.TabletAliasString(ti.Alias))
} | [
"func",
"(",
"ti",
"*",
"TabletInfo",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"ti",
".",
"Alias",
")",
")",
"\n",
"}"
] | // String returns a string describing the tablet. | [
"String",
"returns",
"a",
"string",
"describing",
"the",
"tablet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L169-L171 | train |
vitessio/vitess | go/vt/topo/tablet.go | NewTabletInfo | func NewTabletInfo(tablet *topodatapb.Tablet, version Version) *TabletInfo {
return &TabletInfo{version: version, Tablet: tablet}
} | go | func NewTabletInfo(tablet *topodatapb.Tablet, version Version) *TabletInfo {
return &TabletInfo{version: version, Tablet: tablet}
} | [
"func",
"NewTabletInfo",
"(",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
",",
"version",
"Version",
")",
"*",
"TabletInfo",
"{",
"return",
"&",
"TabletInfo",
"{",
"version",
":",
"version",
",",
"Tablet",
":",
"tablet",
"}",
"\n",
"}"
] | // NewTabletInfo returns a TabletInfo basing on tablet with the
// version set. This function should be only used by Server
// implementations. | [
"NewTabletInfo",
"returns",
"a",
"TabletInfo",
"basing",
"on",
"tablet",
"with",
"the",
"version",
"set",
".",
"This",
"function",
"should",
"be",
"only",
"used",
"by",
"Server",
"implementations",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L213-L215 | train |
vitessio/vitess | go/vt/topo/tablet.go | GetTablet | func (ts *Server) GetTablet(ctx context.Context, alias *topodatapb.TabletAlias) (*TabletInfo, error) {
conn, err := ts.ConnForCell(ctx, alias.Cell)
if err != nil {
return nil, err
}
span, ctx := trace.NewSpan(ctx, "TopoServer.GetTablet")
span.Annotate("tablet", topoproto.TabletAliasString(alias))
defer span.Finish()
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(alias), TabletFile)
data, version, err := conn.Get(ctx, tabletPath)
if err != nil {
return nil, err
}
tablet := &topodatapb.Tablet{}
if err := proto.Unmarshal(data, tablet); err != nil {
return nil, err
}
return &TabletInfo{
version: version,
Tablet: tablet,
}, nil
} | go | func (ts *Server) GetTablet(ctx context.Context, alias *topodatapb.TabletAlias) (*TabletInfo, error) {
conn, err := ts.ConnForCell(ctx, alias.Cell)
if err != nil {
return nil, err
}
span, ctx := trace.NewSpan(ctx, "TopoServer.GetTablet")
span.Annotate("tablet", topoproto.TabletAliasString(alias))
defer span.Finish()
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(alias), TabletFile)
data, version, err := conn.Get(ctx, tabletPath)
if err != nil {
return nil, err
}
tablet := &topodatapb.Tablet{}
if err := proto.Unmarshal(data, tablet); err != nil {
return nil, err
}
return &TabletInfo{
version: version,
Tablet: tablet,
}, nil
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"GetTablet",
"(",
"ctx",
"context",
".",
"Context",
",",
"alias",
"*",
"topodatapb",
".",
"TabletAlias",
")",
"(",
"*",
"TabletInfo",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"ts",
".",
"ConnForCell",
"(",
"ctx",
",",
"alias",
".",
"Cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"span",
",",
"ctx",
":=",
"trace",
".",
"NewSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"span",
".",
"Annotate",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"tabletPath",
":=",
"path",
".",
"Join",
"(",
"TabletsPath",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
",",
"TabletFile",
")",
"\n",
"data",
",",
"version",
",",
"err",
":=",
"conn",
".",
"Get",
"(",
"ctx",
",",
"tabletPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tablet",
":=",
"&",
"topodatapb",
".",
"Tablet",
"{",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"tablet",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"TabletInfo",
"{",
"version",
":",
"version",
",",
"Tablet",
":",
"tablet",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GetTablet is a high level function to read tablet data.
// It generates trace spans. | [
"GetTablet",
"is",
"a",
"high",
"level",
"function",
"to",
"read",
"tablet",
"data",
".",
"It",
"generates",
"trace",
"spans",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L219-L243 | train |
vitessio/vitess | go/vt/topo/tablet.go | UpdateTablet | func (ts *Server) UpdateTablet(ctx context.Context, ti *TabletInfo) error {
conn, err := ts.ConnForCell(ctx, ti.Tablet.Alias.Cell)
if err != nil {
return err
}
span, ctx := trace.NewSpan(ctx, "TopoServer.UpdateTablet")
span.Annotate("tablet", topoproto.TabletAliasString(ti.Alias))
defer span.Finish()
data, err := proto.Marshal(ti.Tablet)
if err != nil {
return err
}
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(ti.Tablet.Alias), TabletFile)
newVersion, err := conn.Update(ctx, tabletPath, data, ti.version)
if err != nil {
return err
}
ti.version = newVersion
event.Dispatch(&events.TabletChange{
Tablet: *ti.Tablet,
Status: "updated",
})
return nil
} | go | func (ts *Server) UpdateTablet(ctx context.Context, ti *TabletInfo) error {
conn, err := ts.ConnForCell(ctx, ti.Tablet.Alias.Cell)
if err != nil {
return err
}
span, ctx := trace.NewSpan(ctx, "TopoServer.UpdateTablet")
span.Annotate("tablet", topoproto.TabletAliasString(ti.Alias))
defer span.Finish()
data, err := proto.Marshal(ti.Tablet)
if err != nil {
return err
}
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(ti.Tablet.Alias), TabletFile)
newVersion, err := conn.Update(ctx, tabletPath, data, ti.version)
if err != nil {
return err
}
ti.version = newVersion
event.Dispatch(&events.TabletChange{
Tablet: *ti.Tablet,
Status: "updated",
})
return nil
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"UpdateTablet",
"(",
"ctx",
"context",
".",
"Context",
",",
"ti",
"*",
"TabletInfo",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"ts",
".",
"ConnForCell",
"(",
"ctx",
",",
"ti",
".",
"Tablet",
".",
"Alias",
".",
"Cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"span",
",",
"ctx",
":=",
"trace",
".",
"NewSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"span",
".",
"Annotate",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"ti",
".",
"Alias",
")",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"data",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"ti",
".",
"Tablet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"tabletPath",
":=",
"path",
".",
"Join",
"(",
"TabletsPath",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"ti",
".",
"Tablet",
".",
"Alias",
")",
",",
"TabletFile",
")",
"\n",
"newVersion",
",",
"err",
":=",
"conn",
".",
"Update",
"(",
"ctx",
",",
"tabletPath",
",",
"data",
",",
"ti",
".",
"version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ti",
".",
"version",
"=",
"newVersion",
"\n\n",
"event",
".",
"Dispatch",
"(",
"&",
"events",
".",
"TabletChange",
"{",
"Tablet",
":",
"*",
"ti",
".",
"Tablet",
",",
"Status",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateTablet updates the tablet data only - not associated replication paths.
// It also uses a span, and sends the event. | [
"UpdateTablet",
"updates",
"the",
"tablet",
"data",
"only",
"-",
"not",
"associated",
"replication",
"paths",
".",
"It",
"also",
"uses",
"a",
"span",
"and",
"sends",
"the",
"event",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L247-L273 | train |
vitessio/vitess | go/vt/topo/tablet.go | UpdateTabletFields | func (ts *Server) UpdateTabletFields(ctx context.Context, alias *topodatapb.TabletAlias, update func(*topodatapb.Tablet) error) (*topodatapb.Tablet, error) {
span, ctx := trace.NewSpan(ctx, "TopoServer.UpdateTabletFields")
span.Annotate("tablet", topoproto.TabletAliasString(alias))
defer span.Finish()
for {
ti, err := ts.GetTablet(ctx, alias)
if err != nil {
return nil, err
}
if err = update(ti.Tablet); err != nil {
if IsErrType(err, NoUpdateNeeded) {
return nil, nil
}
return nil, err
}
if err = ts.UpdateTablet(ctx, ti); !IsErrType(err, BadVersion) {
return ti.Tablet, err
}
}
} | go | func (ts *Server) UpdateTabletFields(ctx context.Context, alias *topodatapb.TabletAlias, update func(*topodatapb.Tablet) error) (*topodatapb.Tablet, error) {
span, ctx := trace.NewSpan(ctx, "TopoServer.UpdateTabletFields")
span.Annotate("tablet", topoproto.TabletAliasString(alias))
defer span.Finish()
for {
ti, err := ts.GetTablet(ctx, alias)
if err != nil {
return nil, err
}
if err = update(ti.Tablet); err != nil {
if IsErrType(err, NoUpdateNeeded) {
return nil, nil
}
return nil, err
}
if err = ts.UpdateTablet(ctx, ti); !IsErrType(err, BadVersion) {
return ti.Tablet, err
}
}
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"UpdateTabletFields",
"(",
"ctx",
"context",
".",
"Context",
",",
"alias",
"*",
"topodatapb",
".",
"TabletAlias",
",",
"update",
"func",
"(",
"*",
"topodatapb",
".",
"Tablet",
")",
"error",
")",
"(",
"*",
"topodatapb",
".",
"Tablet",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"trace",
".",
"NewSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"span",
".",
"Annotate",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"for",
"{",
"ti",
",",
"err",
":=",
"ts",
".",
"GetTablet",
"(",
"ctx",
",",
"alias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"update",
"(",
"ti",
".",
"Tablet",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"IsErrType",
"(",
"err",
",",
"NoUpdateNeeded",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"ts",
".",
"UpdateTablet",
"(",
"ctx",
",",
"ti",
")",
";",
"!",
"IsErrType",
"(",
"err",
",",
"BadVersion",
")",
"{",
"return",
"ti",
".",
"Tablet",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // UpdateTabletFields is a high level helper to read a tablet record, call an
// update function on it, and then write it back. If the write fails due to
// a version mismatch, it will re-read the record and retry the update.
// If the update succeeds, it returns the updated tablet.
// If the update method returns ErrNoUpdateNeeded, nothing is written,
// and nil,nil is returned. | [
"UpdateTabletFields",
"is",
"a",
"high",
"level",
"helper",
"to",
"read",
"a",
"tablet",
"record",
"call",
"an",
"update",
"function",
"on",
"it",
"and",
"then",
"write",
"it",
"back",
".",
"If",
"the",
"write",
"fails",
"due",
"to",
"a",
"version",
"mismatch",
"it",
"will",
"re",
"-",
"read",
"the",
"record",
"and",
"retry",
"the",
"update",
".",
"If",
"the",
"update",
"succeeds",
"it",
"returns",
"the",
"updated",
"tablet",
".",
"If",
"the",
"update",
"method",
"returns",
"ErrNoUpdateNeeded",
"nothing",
"is",
"written",
"and",
"nil",
"nil",
"is",
"returned",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L281-L301 | train |
vitessio/vitess | go/vt/topo/tablet.go | Validate | func Validate(ctx context.Context, ts *Server, tabletAlias *topodatapb.TabletAlias) error {
// read the tablet record, make sure it parses
tablet, err := ts.GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
if !topoproto.TabletAliasEqual(tablet.Alias, tabletAlias) {
return vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "bad tablet alias data for tablet %v: %#v", topoproto.TabletAliasString(tabletAlias), tablet.Alias)
}
// Validate the entry in the shard replication nodes
si, err := ts.GetShardReplication(ctx, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard)
if err != nil {
return err
}
if _, err = si.GetShardReplicationNode(tabletAlias); err != nil {
return vterrors.Wrapf(err, "tablet %v not found in cell %v shard replication", tabletAlias, tablet.Alias.Cell)
}
return nil
} | go | func Validate(ctx context.Context, ts *Server, tabletAlias *topodatapb.TabletAlias) error {
// read the tablet record, make sure it parses
tablet, err := ts.GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
if !topoproto.TabletAliasEqual(tablet.Alias, tabletAlias) {
return vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "bad tablet alias data for tablet %v: %#v", topoproto.TabletAliasString(tabletAlias), tablet.Alias)
}
// Validate the entry in the shard replication nodes
si, err := ts.GetShardReplication(ctx, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard)
if err != nil {
return err
}
if _, err = si.GetShardReplicationNode(tabletAlias); err != nil {
return vterrors.Wrapf(err, "tablet %v not found in cell %v shard replication", tabletAlias, tablet.Alias.Cell)
}
return nil
} | [
"func",
"Validate",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"Server",
",",
"tabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
")",
"error",
"{",
"// read the tablet record, make sure it parses",
"tablet",
",",
"err",
":=",
"ts",
".",
"GetTablet",
"(",
"ctx",
",",
"tabletAlias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"topoproto",
".",
"TabletAliasEqual",
"(",
"tablet",
".",
"Alias",
",",
"tabletAlias",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INVALID_ARGUMENT",
",",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"tabletAlias",
")",
",",
"tablet",
".",
"Alias",
")",
"\n",
"}",
"\n\n",
"// Validate the entry in the shard replication nodes",
"si",
",",
"err",
":=",
"ts",
".",
"GetShardReplication",
"(",
"ctx",
",",
"tablet",
".",
"Alias",
".",
"Cell",
",",
"tablet",
".",
"Keyspace",
",",
"tablet",
".",
"Shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
"=",
"si",
".",
"GetShardReplicationNode",
"(",
"tabletAlias",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"tabletAlias",
",",
"tablet",
".",
"Alias",
".",
"Cell",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Validate makes sure a tablet is represented correctly in the topology server. | [
"Validate",
"makes",
"sure",
"a",
"tablet",
"is",
"represented",
"correctly",
"in",
"the",
"topology",
"server",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L304-L325 | train |
vitessio/vitess | go/vt/topo/tablet.go | CreateTablet | func (ts *Server) CreateTablet(ctx context.Context, tablet *topodatapb.Tablet) error {
conn, err := ts.ConnForCell(ctx, tablet.Alias.Cell)
if err != nil {
return err
}
data, err := proto.Marshal(tablet)
if err != nil {
return err
}
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(tablet.Alias), TabletFile)
if _, err = conn.Create(ctx, tabletPath, data); err != nil {
return err
}
if updateErr := UpdateTabletReplicationData(ctx, ts, tablet); updateErr != nil {
return updateErr
}
if err == nil {
event.Dispatch(&events.TabletChange{
Tablet: *tablet,
Status: "created",
})
}
return err
} | go | func (ts *Server) CreateTablet(ctx context.Context, tablet *topodatapb.Tablet) error {
conn, err := ts.ConnForCell(ctx, tablet.Alias.Cell)
if err != nil {
return err
}
data, err := proto.Marshal(tablet)
if err != nil {
return err
}
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(tablet.Alias), TabletFile)
if _, err = conn.Create(ctx, tabletPath, data); err != nil {
return err
}
if updateErr := UpdateTabletReplicationData(ctx, ts, tablet); updateErr != nil {
return updateErr
}
if err == nil {
event.Dispatch(&events.TabletChange{
Tablet: *tablet,
Status: "created",
})
}
return err
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"CreateTablet",
"(",
"ctx",
"context",
".",
"Context",
",",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"ts",
".",
"ConnForCell",
"(",
"ctx",
",",
"tablet",
".",
"Alias",
".",
"Cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"data",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"tablet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"tabletPath",
":=",
"path",
".",
"Join",
"(",
"TabletsPath",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"tablet",
".",
"Alias",
")",
",",
"TabletFile",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"conn",
".",
"Create",
"(",
"ctx",
",",
"tabletPath",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"updateErr",
":=",
"UpdateTabletReplicationData",
"(",
"ctx",
",",
"ts",
",",
"tablet",
")",
";",
"updateErr",
"!=",
"nil",
"{",
"return",
"updateErr",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"event",
".",
"Dispatch",
"(",
"&",
"events",
".",
"TabletChange",
"{",
"Tablet",
":",
"*",
"tablet",
",",
"Status",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // CreateTablet creates a new tablet and all associated paths for the
// replication graph. | [
"CreateTablet",
"creates",
"a",
"new",
"tablet",
"and",
"all",
"associated",
"paths",
"for",
"the",
"replication",
"graph",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L329-L355 | train |
vitessio/vitess | go/vt/topo/tablet.go | DeleteTablet | func (ts *Server) DeleteTablet(ctx context.Context, tabletAlias *topodatapb.TabletAlias) error {
conn, err := ts.ConnForCell(ctx, tabletAlias.Cell)
if err != nil {
return err
}
// get the current tablet record, if any, to log the deletion
ti, tErr := ts.GetTablet(ctx, tabletAlias)
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(tabletAlias), TabletFile)
if err := conn.Delete(ctx, tabletPath, nil); err != nil {
return err
}
// Only try to log if we have the required info.
if tErr == nil {
// Only copy the identity info for the tablet. The rest has been deleted.
event.Dispatch(&events.TabletChange{
Tablet: topodatapb.Tablet{
Alias: tabletAlias,
Keyspace: ti.Tablet.Keyspace,
Shard: ti.Tablet.Shard,
},
Status: "deleted",
})
}
return nil
} | go | func (ts *Server) DeleteTablet(ctx context.Context, tabletAlias *topodatapb.TabletAlias) error {
conn, err := ts.ConnForCell(ctx, tabletAlias.Cell)
if err != nil {
return err
}
// get the current tablet record, if any, to log the deletion
ti, tErr := ts.GetTablet(ctx, tabletAlias)
tabletPath := path.Join(TabletsPath, topoproto.TabletAliasString(tabletAlias), TabletFile)
if err := conn.Delete(ctx, tabletPath, nil); err != nil {
return err
}
// Only try to log if we have the required info.
if tErr == nil {
// Only copy the identity info for the tablet. The rest has been deleted.
event.Dispatch(&events.TabletChange{
Tablet: topodatapb.Tablet{
Alias: tabletAlias,
Keyspace: ti.Tablet.Keyspace,
Shard: ti.Tablet.Shard,
},
Status: "deleted",
})
}
return nil
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"DeleteTablet",
"(",
"ctx",
"context",
".",
"Context",
",",
"tabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"ts",
".",
"ConnForCell",
"(",
"ctx",
",",
"tabletAlias",
".",
"Cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// get the current tablet record, if any, to log the deletion",
"ti",
",",
"tErr",
":=",
"ts",
".",
"GetTablet",
"(",
"ctx",
",",
"tabletAlias",
")",
"\n\n",
"tabletPath",
":=",
"path",
".",
"Join",
"(",
"TabletsPath",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"tabletAlias",
")",
",",
"TabletFile",
")",
"\n",
"if",
"err",
":=",
"conn",
".",
"Delete",
"(",
"ctx",
",",
"tabletPath",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Only try to log if we have the required info.",
"if",
"tErr",
"==",
"nil",
"{",
"// Only copy the identity info for the tablet. The rest has been deleted.",
"event",
".",
"Dispatch",
"(",
"&",
"events",
".",
"TabletChange",
"{",
"Tablet",
":",
"topodatapb",
".",
"Tablet",
"{",
"Alias",
":",
"tabletAlias",
",",
"Keyspace",
":",
"ti",
".",
"Tablet",
".",
"Keyspace",
",",
"Shard",
":",
"ti",
".",
"Tablet",
".",
"Shard",
",",
"}",
",",
"Status",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // DeleteTablet wraps the underlying conn.Delete
// and dispatches the event. | [
"DeleteTablet",
"wraps",
"the",
"underlying",
"conn",
".",
"Delete",
"and",
"dispatches",
"the",
"event",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L359-L386 | train |
vitessio/vitess | go/vt/topo/tablet.go | UpdateTabletReplicationData | func UpdateTabletReplicationData(ctx context.Context, ts *Server, tablet *topodatapb.Tablet) error {
return UpdateShardReplicationRecord(ctx, ts, tablet.Keyspace, tablet.Shard, tablet.Alias)
} | go | func UpdateTabletReplicationData(ctx context.Context, ts *Server, tablet *topodatapb.Tablet) error {
return UpdateShardReplicationRecord(ctx, ts, tablet.Keyspace, tablet.Shard, tablet.Alias)
} | [
"func",
"UpdateTabletReplicationData",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"Server",
",",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
")",
"error",
"{",
"return",
"UpdateShardReplicationRecord",
"(",
"ctx",
",",
"ts",
",",
"tablet",
".",
"Keyspace",
",",
"tablet",
".",
"Shard",
",",
"tablet",
".",
"Alias",
")",
"\n",
"}"
] | // UpdateTabletReplicationData creates or updates the replication
// graph data for a tablet | [
"UpdateTabletReplicationData",
"creates",
"or",
"updates",
"the",
"replication",
"graph",
"data",
"for",
"a",
"tablet"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L390-L392 | train |
vitessio/vitess | go/vt/topo/tablet.go | DeleteTabletReplicationData | func DeleteTabletReplicationData(ctx context.Context, ts *Server, tablet *topodatapb.Tablet) error {
return RemoveShardReplicationRecord(ctx, ts, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard, tablet.Alias)
} | go | func DeleteTabletReplicationData(ctx context.Context, ts *Server, tablet *topodatapb.Tablet) error {
return RemoveShardReplicationRecord(ctx, ts, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard, tablet.Alias)
} | [
"func",
"DeleteTabletReplicationData",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"Server",
",",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
")",
"error",
"{",
"return",
"RemoveShardReplicationRecord",
"(",
"ctx",
",",
"ts",
",",
"tablet",
".",
"Alias",
".",
"Cell",
",",
"tablet",
".",
"Keyspace",
",",
"tablet",
".",
"Shard",
",",
"tablet",
".",
"Alias",
")",
"\n",
"}"
] | // DeleteTabletReplicationData deletes replication data. | [
"DeleteTabletReplicationData",
"deletes",
"replication",
"data",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/tablet.go#L395-L397 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | NewTxPool | func NewTxPool(
prefix string,
capacity int,
foundRowsCapacity int,
timeout time.Duration,
idleTimeout time.Duration,
waiterCap int,
checker connpool.MySQLChecker,
limiter txlimiter.TxLimiter) *TxPool {
axp := &TxPool{
conns: connpool.New(prefix+"TransactionPool", capacity, idleTimeout, checker),
foundRowsPool: connpool.New(prefix+"FoundRowsPool", foundRowsCapacity, idleTimeout, checker),
activePool: pools.NewNumbered(),
lastID: sync2.NewAtomicInt64(time.Now().UnixNano()),
timeout: sync2.NewAtomicDuration(timeout),
waiterCap: sync2.NewAtomicInt64(int64(waiterCap)),
waiters: sync2.NewAtomicInt64(0),
ticks: timer.NewTimer(timeout / 10),
checker: checker,
limiter: limiter,
}
txOnce.Do(func() {
// Careful: conns also exports name+"xxx" vars,
// but we know it doesn't export Timeout.
stats.NewGaugeDurationFunc(prefix+"TransactionPoolTimeout", "Transaction pool timeout", axp.timeout.Get)
stats.NewGaugeFunc(prefix+"TransactionPoolWaiters", "Transaction pool waiters", axp.waiters.Get)
})
return axp
} | go | func NewTxPool(
prefix string,
capacity int,
foundRowsCapacity int,
timeout time.Duration,
idleTimeout time.Duration,
waiterCap int,
checker connpool.MySQLChecker,
limiter txlimiter.TxLimiter) *TxPool {
axp := &TxPool{
conns: connpool.New(prefix+"TransactionPool", capacity, idleTimeout, checker),
foundRowsPool: connpool.New(prefix+"FoundRowsPool", foundRowsCapacity, idleTimeout, checker),
activePool: pools.NewNumbered(),
lastID: sync2.NewAtomicInt64(time.Now().UnixNano()),
timeout: sync2.NewAtomicDuration(timeout),
waiterCap: sync2.NewAtomicInt64(int64(waiterCap)),
waiters: sync2.NewAtomicInt64(0),
ticks: timer.NewTimer(timeout / 10),
checker: checker,
limiter: limiter,
}
txOnce.Do(func() {
// Careful: conns also exports name+"xxx" vars,
// but we know it doesn't export Timeout.
stats.NewGaugeDurationFunc(prefix+"TransactionPoolTimeout", "Transaction pool timeout", axp.timeout.Get)
stats.NewGaugeFunc(prefix+"TransactionPoolWaiters", "Transaction pool waiters", axp.waiters.Get)
})
return axp
} | [
"func",
"NewTxPool",
"(",
"prefix",
"string",
",",
"capacity",
"int",
",",
"foundRowsCapacity",
"int",
",",
"timeout",
"time",
".",
"Duration",
",",
"idleTimeout",
"time",
".",
"Duration",
",",
"waiterCap",
"int",
",",
"checker",
"connpool",
".",
"MySQLChecker",
",",
"limiter",
"txlimiter",
".",
"TxLimiter",
")",
"*",
"TxPool",
"{",
"axp",
":=",
"&",
"TxPool",
"{",
"conns",
":",
"connpool",
".",
"New",
"(",
"prefix",
"+",
"\"",
"\"",
",",
"capacity",
",",
"idleTimeout",
",",
"checker",
")",
",",
"foundRowsPool",
":",
"connpool",
".",
"New",
"(",
"prefix",
"+",
"\"",
"\"",
",",
"foundRowsCapacity",
",",
"idleTimeout",
",",
"checker",
")",
",",
"activePool",
":",
"pools",
".",
"NewNumbered",
"(",
")",
",",
"lastID",
":",
"sync2",
".",
"NewAtomicInt64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
",",
"timeout",
":",
"sync2",
".",
"NewAtomicDuration",
"(",
"timeout",
")",
",",
"waiterCap",
":",
"sync2",
".",
"NewAtomicInt64",
"(",
"int64",
"(",
"waiterCap",
")",
")",
",",
"waiters",
":",
"sync2",
".",
"NewAtomicInt64",
"(",
"0",
")",
",",
"ticks",
":",
"timer",
".",
"NewTimer",
"(",
"timeout",
"/",
"10",
")",
",",
"checker",
":",
"checker",
",",
"limiter",
":",
"limiter",
",",
"}",
"\n",
"txOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"// Careful: conns also exports name+\"xxx\" vars,",
"// but we know it doesn't export Timeout.",
"stats",
".",
"NewGaugeDurationFunc",
"(",
"prefix",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"axp",
".",
"timeout",
".",
"Get",
")",
"\n",
"stats",
".",
"NewGaugeFunc",
"(",
"prefix",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"axp",
".",
"waiters",
".",
"Get",
")",
"\n",
"}",
")",
"\n",
"return",
"axp",
"\n",
"}"
] | // NewTxPool creates a new TxPool. It's not operational until it's Open'd. | [
"NewTxPool",
"creates",
"a",
"new",
"TxPool",
".",
"It",
"s",
"not",
"operational",
"until",
"it",
"s",
"Open",
"d",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L106-L134 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | Open | func (axp *TxPool) Open(appParams, dbaParams, appDebugParams *mysql.ConnParams) {
log.Infof("Starting transaction id: %d", axp.lastID)
axp.conns.Open(appParams, dbaParams, appDebugParams)
foundRowsParam := *appParams
foundRowsParam.EnableClientFoundRows()
axp.foundRowsPool.Open(&foundRowsParam, dbaParams, appDebugParams)
axp.ticks.Start(func() { axp.transactionKiller() })
} | go | func (axp *TxPool) Open(appParams, dbaParams, appDebugParams *mysql.ConnParams) {
log.Infof("Starting transaction id: %d", axp.lastID)
axp.conns.Open(appParams, dbaParams, appDebugParams)
foundRowsParam := *appParams
foundRowsParam.EnableClientFoundRows()
axp.foundRowsPool.Open(&foundRowsParam, dbaParams, appDebugParams)
axp.ticks.Start(func() { axp.transactionKiller() })
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"Open",
"(",
"appParams",
",",
"dbaParams",
",",
"appDebugParams",
"*",
"mysql",
".",
"ConnParams",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"axp",
".",
"lastID",
")",
"\n",
"axp",
".",
"conns",
".",
"Open",
"(",
"appParams",
",",
"dbaParams",
",",
"appDebugParams",
")",
"\n",
"foundRowsParam",
":=",
"*",
"appParams",
"\n",
"foundRowsParam",
".",
"EnableClientFoundRows",
"(",
")",
"\n",
"axp",
".",
"foundRowsPool",
".",
"Open",
"(",
"&",
"foundRowsParam",
",",
"dbaParams",
",",
"appDebugParams",
")",
"\n",
"axp",
".",
"ticks",
".",
"Start",
"(",
"func",
"(",
")",
"{",
"axp",
".",
"transactionKiller",
"(",
")",
"}",
")",
"\n",
"}"
] | // Open makes the TxPool operational. This also starts the transaction killer
// that will kill long-running transactions. | [
"Open",
"makes",
"the",
"TxPool",
"operational",
".",
"This",
"also",
"starts",
"the",
"transaction",
"killer",
"that",
"will",
"kill",
"long",
"-",
"running",
"transactions",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L138-L145 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | Close | func (axp *TxPool) Close() {
axp.ticks.Stop()
for _, v := range axp.activePool.GetOutdated(time.Duration(0), "for closing") {
conn := v.(*TxConnection)
log.Warningf("killing transaction for shutdown: %s", conn.Format(nil))
tabletenv.InternalErrors.Add("StrayTransactions", 1)
conn.Close()
conn.conclude(TxClose, "pool closed")
}
axp.conns.Close()
axp.foundRowsPool.Close()
} | go | func (axp *TxPool) Close() {
axp.ticks.Stop()
for _, v := range axp.activePool.GetOutdated(time.Duration(0), "for closing") {
conn := v.(*TxConnection)
log.Warningf("killing transaction for shutdown: %s", conn.Format(nil))
tabletenv.InternalErrors.Add("StrayTransactions", 1)
conn.Close()
conn.conclude(TxClose, "pool closed")
}
axp.conns.Close()
axp.foundRowsPool.Close()
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"Close",
"(",
")",
"{",
"axp",
".",
"ticks",
".",
"Stop",
"(",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"axp",
".",
"activePool",
".",
"GetOutdated",
"(",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"\"",
"\"",
")",
"{",
"conn",
":=",
"v",
".",
"(",
"*",
"TxConnection",
")",
"\n",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"conn",
".",
"Format",
"(",
"nil",
")",
")",
"\n",
"tabletenv",
".",
"InternalErrors",
".",
"Add",
"(",
"\"",
"\"",
",",
"1",
")",
"\n",
"conn",
".",
"Close",
"(",
")",
"\n",
"conn",
".",
"conclude",
"(",
"TxClose",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"axp",
".",
"conns",
".",
"Close",
"(",
")",
"\n",
"axp",
".",
"foundRowsPool",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close closes the TxPool. A closed pool can be reopened. | [
"Close",
"closes",
"the",
"TxPool",
".",
"A",
"closed",
"pool",
"can",
"be",
"reopened",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L148-L159 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | AdjustLastID | func (axp *TxPool) AdjustLastID(id int64) {
if current := axp.lastID.Get(); current < id {
log.Infof("Adjusting transaction id to: %d", id)
axp.lastID.Set(id)
}
} | go | func (axp *TxPool) AdjustLastID(id int64) {
if current := axp.lastID.Get(); current < id {
log.Infof("Adjusting transaction id to: %d", id)
axp.lastID.Set(id)
}
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"AdjustLastID",
"(",
"id",
"int64",
")",
"{",
"if",
"current",
":=",
"axp",
".",
"lastID",
".",
"Get",
"(",
")",
";",
"current",
"<",
"id",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"axp",
".",
"lastID",
".",
"Set",
"(",
"id",
")",
"\n",
"}",
"\n",
"}"
] | // AdjustLastID adjusts the last transaction id to be at least
// as large as the input value. This will ensure that there are
// no dtid collisions with future transactions. | [
"AdjustLastID",
"adjusts",
"the",
"last",
"transaction",
"id",
"to",
"be",
"at",
"least",
"as",
"large",
"as",
"the",
"input",
"value",
".",
"This",
"will",
"ensure",
"that",
"there",
"are",
"no",
"dtid",
"collisions",
"with",
"future",
"transactions",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L164-L169 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | RollbackNonBusy | func (axp *TxPool) RollbackNonBusy(ctx context.Context) {
for _, v := range axp.activePool.GetOutdated(time.Duration(0), "for transition") {
axp.LocalConclude(ctx, v.(*TxConnection))
}
} | go | func (axp *TxPool) RollbackNonBusy(ctx context.Context) {
for _, v := range axp.activePool.GetOutdated(time.Duration(0), "for transition") {
axp.LocalConclude(ctx, v.(*TxConnection))
}
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"RollbackNonBusy",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"axp",
".",
"activePool",
".",
"GetOutdated",
"(",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"\"",
"\"",
")",
"{",
"axp",
".",
"LocalConclude",
"(",
"ctx",
",",
"v",
".",
"(",
"*",
"TxConnection",
")",
")",
"\n",
"}",
"\n",
"}"
] | // RollbackNonBusy rolls back all transactions that are not in use.
// Transactions can be in use for situations like executing statements
// or in prepared state. | [
"RollbackNonBusy",
"rolls",
"back",
"all",
"transactions",
"that",
"are",
"not",
"in",
"use",
".",
"Transactions",
"can",
"be",
"in",
"use",
"for",
"situations",
"like",
"executing",
"statements",
"or",
"in",
"prepared",
"state",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L174-L178 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | Get | func (axp *TxPool) Get(transactionID int64, reason string) (*TxConnection, error) {
v, err := axp.activePool.Get(transactionID, reason)
if err != nil {
return nil, vterrors.Errorf(vtrpcpb.Code_ABORTED, "transaction %d: %v", transactionID, err)
}
return v.(*TxConnection), nil
} | go | func (axp *TxPool) Get(transactionID int64, reason string) (*TxConnection, error) {
v, err := axp.activePool.Get(transactionID, reason)
if err != nil {
return nil, vterrors.Errorf(vtrpcpb.Code_ABORTED, "transaction %d: %v", transactionID, err)
}
return v.(*TxConnection), nil
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"Get",
"(",
"transactionID",
"int64",
",",
"reason",
"string",
")",
"(",
"*",
"TxConnection",
",",
"error",
")",
"{",
"v",
",",
"err",
":=",
"axp",
".",
"activePool",
".",
"Get",
"(",
"transactionID",
",",
"reason",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"vterrors",
".",
"Errorf",
"(",
"vtrpcpb",
".",
"Code_ABORTED",
",",
"\"",
"\"",
",",
"transactionID",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"v",
".",
"(",
"*",
"TxConnection",
")",
",",
"nil",
"\n",
"}"
] | // Get fetches the connection associated to the transactionID.
// You must call Recycle on TxConnection once done. | [
"Get",
"fetches",
"the",
"connection",
"associated",
"to",
"the",
"transactionID",
".",
"You",
"must",
"call",
"Recycle",
"on",
"TxConnection",
"once",
"done",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L311-L317 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | LocalBegin | func (axp *TxPool) LocalBegin(ctx context.Context, options *querypb.ExecuteOptions) (*TxConnection, string, error) {
span, ctx := trace.NewSpan(ctx, "TxPool.LocalBegin")
defer span.Finish()
transactionID, beginSQL, err := axp.Begin(ctx, options)
if err != nil {
return nil, "", err
}
conn, err := axp.Get(transactionID, "for local query")
return conn, beginSQL, err
} | go | func (axp *TxPool) LocalBegin(ctx context.Context, options *querypb.ExecuteOptions) (*TxConnection, string, error) {
span, ctx := trace.NewSpan(ctx, "TxPool.LocalBegin")
defer span.Finish()
transactionID, beginSQL, err := axp.Begin(ctx, options)
if err != nil {
return nil, "", err
}
conn, err := axp.Get(transactionID, "for local query")
return conn, beginSQL, err
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"LocalBegin",
"(",
"ctx",
"context",
".",
"Context",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
")",
"(",
"*",
"TxConnection",
",",
"string",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"trace",
".",
"NewSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"transactionID",
",",
"beginSQL",
",",
"err",
":=",
"axp",
".",
"Begin",
"(",
"ctx",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"conn",
",",
"err",
":=",
"axp",
".",
"Get",
"(",
"transactionID",
",",
"\"",
"\"",
")",
"\n",
"return",
"conn",
",",
"beginSQL",
",",
"err",
"\n",
"}"
] | // LocalBegin is equivalent to Begin->Get.
// It's used for executing transactions within a request. It's safe
// to always call LocalConclude at the end. | [
"LocalBegin",
"is",
"equivalent",
"to",
"Begin",
"-",
">",
"Get",
".",
"It",
"s",
"used",
"for",
"executing",
"transactions",
"within",
"a",
"request",
".",
"It",
"s",
"safe",
"to",
"always",
"call",
"LocalConclude",
"at",
"the",
"end",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L322-L332 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | LocalCommit | func (axp *TxPool) LocalCommit(ctx context.Context, conn *TxConnection, mc messageCommitter) (string, error) {
span, ctx := trace.NewSpan(ctx, "TxPool.LocalCommit")
defer span.Finish()
defer conn.conclude(TxCommit, "transaction committed")
defer mc.LockDB(conn.NewMessages, conn.ChangedMessages)()
if conn.Autocommit {
mc.UpdateCaches(conn.NewMessages, conn.ChangedMessages)
return "", nil
}
if _, err := conn.Exec(ctx, "commit", 1, false); err != nil {
conn.Close()
return "", err
}
mc.UpdateCaches(conn.NewMessages, conn.ChangedMessages)
return "commit", nil
} | go | func (axp *TxPool) LocalCommit(ctx context.Context, conn *TxConnection, mc messageCommitter) (string, error) {
span, ctx := trace.NewSpan(ctx, "TxPool.LocalCommit")
defer span.Finish()
defer conn.conclude(TxCommit, "transaction committed")
defer mc.LockDB(conn.NewMessages, conn.ChangedMessages)()
if conn.Autocommit {
mc.UpdateCaches(conn.NewMessages, conn.ChangedMessages)
return "", nil
}
if _, err := conn.Exec(ctx, "commit", 1, false); err != nil {
conn.Close()
return "", err
}
mc.UpdateCaches(conn.NewMessages, conn.ChangedMessages)
return "commit", nil
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"LocalCommit",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"*",
"TxConnection",
",",
"mc",
"messageCommitter",
")",
"(",
"string",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"trace",
".",
"NewSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n",
"defer",
"conn",
".",
"conclude",
"(",
"TxCommit",
",",
"\"",
"\"",
")",
"\n",
"defer",
"mc",
".",
"LockDB",
"(",
"conn",
".",
"NewMessages",
",",
"conn",
".",
"ChangedMessages",
")",
"(",
")",
"\n\n",
"if",
"conn",
".",
"Autocommit",
"{",
"mc",
".",
"UpdateCaches",
"(",
"conn",
".",
"NewMessages",
",",
"conn",
".",
"ChangedMessages",
")",
"\n",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"conn",
".",
"Exec",
"(",
"ctx",
",",
"\"",
"\"",
",",
"1",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"mc",
".",
"UpdateCaches",
"(",
"conn",
".",
"NewMessages",
",",
"conn",
".",
"ChangedMessages",
")",
"\n",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] | // LocalCommit is the commit function for LocalBegin. | [
"LocalCommit",
"is",
"the",
"commit",
"function",
"for",
"LocalBegin",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L335-L352 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | LocalConclude | func (axp *TxPool) LocalConclude(ctx context.Context, conn *TxConnection) {
span, ctx := trace.NewSpan(ctx, "TxPool.LocalConclude")
defer span.Finish()
if conn.DBConn != nil {
_ = axp.localRollback(ctx, conn)
}
} | go | func (axp *TxPool) LocalConclude(ctx context.Context, conn *TxConnection) {
span, ctx := trace.NewSpan(ctx, "TxPool.LocalConclude")
defer span.Finish()
if conn.DBConn != nil {
_ = axp.localRollback(ctx, conn)
}
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"LocalConclude",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"*",
"TxConnection",
")",
"{",
"span",
",",
"ctx",
":=",
"trace",
".",
"NewSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n",
"if",
"conn",
".",
"DBConn",
"!=",
"nil",
"{",
"_",
"=",
"axp",
".",
"localRollback",
"(",
"ctx",
",",
"conn",
")",
"\n",
"}",
"\n",
"}"
] | // LocalConclude concludes a transaction started by LocalBegin.
// If the transaction was not previously concluded, it's rolled back. | [
"LocalConclude",
"concludes",
"a",
"transaction",
"started",
"by",
"LocalBegin",
".",
"If",
"the",
"transaction",
"was",
"not",
"previously",
"concluded",
"it",
"s",
"rolled",
"back",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L356-L362 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | LogActive | func (axp *TxPool) LogActive() {
axp.logMu.Lock()
defer axp.logMu.Unlock()
if time.Since(axp.lastLog) < txLogInterval {
return
}
axp.lastLog = time.Now()
conns := axp.activePool.GetAll()
for _, c := range conns {
c.(*TxConnection).LogToFile.Set(1)
}
} | go | func (axp *TxPool) LogActive() {
axp.logMu.Lock()
defer axp.logMu.Unlock()
if time.Since(axp.lastLog) < txLogInterval {
return
}
axp.lastLog = time.Now()
conns := axp.activePool.GetAll()
for _, c := range conns {
c.(*TxConnection).LogToFile.Set(1)
}
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"LogActive",
"(",
")",
"{",
"axp",
".",
"logMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"axp",
".",
"logMu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"time",
".",
"Since",
"(",
"axp",
".",
"lastLog",
")",
"<",
"txLogInterval",
"{",
"return",
"\n",
"}",
"\n",
"axp",
".",
"lastLog",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"conns",
":=",
"axp",
".",
"activePool",
".",
"GetAll",
"(",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"conns",
"{",
"c",
".",
"(",
"*",
"TxConnection",
")",
".",
"LogToFile",
".",
"Set",
"(",
"1",
")",
"\n",
"}",
"\n",
"}"
] | // LogActive causes all existing transactions to be logged when they complete.
// The logging is throttled to no more than once every txLogInterval. | [
"LogActive",
"causes",
"all",
"existing",
"transactions",
"to",
"be",
"logged",
"when",
"they",
"complete",
".",
"The",
"logging",
"is",
"throttled",
"to",
"no",
"more",
"than",
"once",
"every",
"txLogInterval",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L375-L386 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | SetTimeout | func (axp *TxPool) SetTimeout(timeout time.Duration) {
axp.timeout.Set(timeout)
axp.ticks.SetInterval(timeout / 10)
} | go | func (axp *TxPool) SetTimeout(timeout time.Duration) {
axp.timeout.Set(timeout)
axp.ticks.SetInterval(timeout / 10)
} | [
"func",
"(",
"axp",
"*",
"TxPool",
")",
"SetTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"{",
"axp",
".",
"timeout",
".",
"Set",
"(",
"timeout",
")",
"\n",
"axp",
".",
"ticks",
".",
"SetInterval",
"(",
"timeout",
"/",
"10",
")",
"\n",
"}"
] | // SetTimeout sets the transaction timeout. | [
"SetTimeout",
"sets",
"the",
"transaction",
"timeout",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L394-L397 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | Exec | func (txc *TxConnection) Exec(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
r, err := txc.DBConn.ExecOnce(ctx, query, maxrows, wantfields)
if err != nil {
if mysql.IsConnErr(err) {
select {
case <-ctx.Done():
// If the context is done, the query was killed.
// So, don't trigger a mysql check.
default:
txc.pool.checker.CheckMySQL()
}
}
return nil, err
}
return r, nil
} | go | func (txc *TxConnection) Exec(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
r, err := txc.DBConn.ExecOnce(ctx, query, maxrows, wantfields)
if err != nil {
if mysql.IsConnErr(err) {
select {
case <-ctx.Done():
// If the context is done, the query was killed.
// So, don't trigger a mysql check.
default:
txc.pool.checker.CheckMySQL()
}
}
return nil, err
}
return r, nil
} | [
"func",
"(",
"txc",
"*",
"TxConnection",
")",
"Exec",
"(",
"ctx",
"context",
".",
"Context",
",",
"query",
"string",
",",
"maxrows",
"int",
",",
"wantfields",
"bool",
")",
"(",
"*",
"sqltypes",
".",
"Result",
",",
"error",
")",
"{",
"r",
",",
"err",
":=",
"txc",
".",
"DBConn",
".",
"ExecOnce",
"(",
"ctx",
",",
"query",
",",
"maxrows",
",",
"wantfields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"mysql",
".",
"IsConnErr",
"(",
"err",
")",
"{",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"// If the context is done, the query was killed.",
"// So, don't trigger a mysql check.",
"default",
":",
"txc",
".",
"pool",
".",
"checker",
".",
"CheckMySQL",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"r",
",",
"nil",
"\n",
"}"
] | // Exec executes the statement for the current transaction. | [
"Exec",
"executes",
"the",
"statement",
"for",
"the",
"current",
"transaction",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L433-L448 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | BeginAgain | func (txc *TxConnection) BeginAgain(ctx context.Context) error {
if _, err := txc.DBConn.Exec(ctx, "commit", 1, false); err != nil {
return err
}
if _, err := txc.DBConn.Exec(ctx, "begin", 1, false); err != nil {
return err
}
return nil
} | go | func (txc *TxConnection) BeginAgain(ctx context.Context) error {
if _, err := txc.DBConn.Exec(ctx, "commit", 1, false); err != nil {
return err
}
if _, err := txc.DBConn.Exec(ctx, "begin", 1, false); err != nil {
return err
}
return nil
} | [
"func",
"(",
"txc",
"*",
"TxConnection",
")",
"BeginAgain",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"txc",
".",
"DBConn",
".",
"Exec",
"(",
"ctx",
",",
"\"",
"\"",
",",
"1",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"txc",
".",
"DBConn",
".",
"Exec",
"(",
"ctx",
",",
"\"",
"\"",
",",
"1",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // BeginAgain commits the existing transaction and begins a new one | [
"BeginAgain",
"commits",
"the",
"existing",
"transaction",
"and",
"begins",
"a",
"new",
"one"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L451-L459 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | Recycle | func (txc *TxConnection) Recycle() {
if txc.IsClosed() {
txc.conclude(TxClose, "closed")
} else {
txc.pool.activePool.Put(txc.TransactionID)
}
} | go | func (txc *TxConnection) Recycle() {
if txc.IsClosed() {
txc.conclude(TxClose, "closed")
} else {
txc.pool.activePool.Put(txc.TransactionID)
}
} | [
"func",
"(",
"txc",
"*",
"TxConnection",
")",
"Recycle",
"(",
")",
"{",
"if",
"txc",
".",
"IsClosed",
"(",
")",
"{",
"txc",
".",
"conclude",
"(",
"TxClose",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"txc",
".",
"pool",
".",
"activePool",
".",
"Put",
"(",
"txc",
".",
"TransactionID",
")",
"\n",
"}",
"\n",
"}"
] | // Recycle returns the connection to the pool. The transaction remains
// active. | [
"Recycle",
"returns",
"the",
"connection",
"to",
"the",
"pool",
".",
"The",
"transaction",
"remains",
"active",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L463-L469 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | RecordQuery | func (txc *TxConnection) RecordQuery(query string) {
txc.Queries = append(txc.Queries, query)
} | go | func (txc *TxConnection) RecordQuery(query string) {
txc.Queries = append(txc.Queries, query)
} | [
"func",
"(",
"txc",
"*",
"TxConnection",
")",
"RecordQuery",
"(",
"query",
"string",
")",
"{",
"txc",
".",
"Queries",
"=",
"append",
"(",
"txc",
".",
"Queries",
",",
"query",
")",
"\n",
"}"
] | // RecordQuery records the query against this transaction. | [
"RecordQuery",
"records",
"the",
"query",
"against",
"this",
"transaction",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L472-L474 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tx_pool.go | Format | func (txc *TxConnection) Format(params url.Values) string {
return fmt.Sprintf(
"%v\t'%v'\t'%v'\t%v\t%v\t%.6f\t%v\t%v\t\n",
txc.TransactionID,
callerid.GetPrincipal(txc.EffectiveCallerID),
callerid.GetUsername(txc.ImmediateCallerID),
txc.StartTime.Format(time.StampMicro),
txc.EndTime.Format(time.StampMicro),
txc.EndTime.Sub(txc.StartTime).Seconds(),
txc.Conclusion,
strings.Join(txc.Queries, ";"),
)
} | go | func (txc *TxConnection) Format(params url.Values) string {
return fmt.Sprintf(
"%v\t'%v'\t'%v'\t%v\t%v\t%.6f\t%v\t%v\t\n",
txc.TransactionID,
callerid.GetPrincipal(txc.EffectiveCallerID),
callerid.GetUsername(txc.ImmediateCallerID),
txc.StartTime.Format(time.StampMicro),
txc.EndTime.Format(time.StampMicro),
txc.EndTime.Sub(txc.StartTime).Seconds(),
txc.Conclusion,
strings.Join(txc.Queries, ";"),
)
} | [
"func",
"(",
"txc",
"*",
"TxConnection",
")",
"Format",
"(",
"params",
"url",
".",
"Values",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\t",
"\\t",
"\\t",
"\\t",
"\\t",
"\\t",
"\\t",
"\\t",
"\\n",
"\"",
",",
"txc",
".",
"TransactionID",
",",
"callerid",
".",
"GetPrincipal",
"(",
"txc",
".",
"EffectiveCallerID",
")",
",",
"callerid",
".",
"GetUsername",
"(",
"txc",
".",
"ImmediateCallerID",
")",
",",
"txc",
".",
"StartTime",
".",
"Format",
"(",
"time",
".",
"StampMicro",
")",
",",
"txc",
".",
"EndTime",
".",
"Format",
"(",
"time",
".",
"StampMicro",
")",
",",
"txc",
".",
"EndTime",
".",
"Sub",
"(",
"txc",
".",
"StartTime",
")",
".",
"Seconds",
"(",
")",
",",
"txc",
".",
"Conclusion",
",",
"strings",
".",
"Join",
"(",
"txc",
".",
"Queries",
",",
"\"",
"\"",
")",
",",
")",
"\n",
"}"
] | // Format returns a printable version of the connection info. | [
"Format",
"returns",
"a",
"printable",
"version",
"of",
"the",
"connection",
"info",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_pool.go#L508-L520 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/restore.go | RestoreData | func (agent *ActionAgent) RestoreData(ctx context.Context, logger logutil.Logger, deleteBeforeRestore bool) error {
if err := agent.lock(ctx); err != nil {
return err
}
defer agent.unlock()
if agent.Cnf == nil {
return fmt.Errorf("cannot perform restore without my.cnf, please restart vttablet with a my.cnf file specified")
}
return agent.restoreDataLocked(ctx, logger, deleteBeforeRestore)
} | go | func (agent *ActionAgent) RestoreData(ctx context.Context, logger logutil.Logger, deleteBeforeRestore bool) error {
if err := agent.lock(ctx); err != nil {
return err
}
defer agent.unlock()
if agent.Cnf == nil {
return fmt.Errorf("cannot perform restore without my.cnf, please restart vttablet with a my.cnf file specified")
}
return agent.restoreDataLocked(ctx, logger, deleteBeforeRestore)
} | [
"func",
"(",
"agent",
"*",
"ActionAgent",
")",
"RestoreData",
"(",
"ctx",
"context",
".",
"Context",
",",
"logger",
"logutil",
".",
"Logger",
",",
"deleteBeforeRestore",
"bool",
")",
"error",
"{",
"if",
"err",
":=",
"agent",
".",
"lock",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"agent",
".",
"unlock",
"(",
")",
"\n",
"if",
"agent",
".",
"Cnf",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"agent",
".",
"restoreDataLocked",
"(",
"ctx",
",",
"logger",
",",
"deleteBeforeRestore",
")",
"\n",
"}"
] | // RestoreData is the main entry point for backup restore.
// It will either work, fail gracefully, or return
// an error in case of a non-recoverable error.
// It takes the action lock so no RPC interferes. | [
"RestoreData",
"is",
"the",
"main",
"entry",
"point",
"for",
"backup",
"restore",
".",
"It",
"will",
"either",
"work",
"fail",
"gracefully",
"or",
"return",
"an",
"error",
"in",
"case",
"of",
"a",
"non",
"-",
"recoverable",
"error",
".",
"It",
"takes",
"the",
"action",
"lock",
"so",
"no",
"RPC",
"interferes",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/restore.go#L48-L57 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | newSymtab | func newSymtab() *symtab {
return &symtab{
tables: make(map[sqlparser.TableName]*table),
uniqueColumns: make(map[string]*column),
}
} | go | func newSymtab() *symtab {
return &symtab{
tables: make(map[sqlparser.TableName]*table),
uniqueColumns: make(map[string]*column),
}
} | [
"func",
"newSymtab",
"(",
")",
"*",
"symtab",
"{",
"return",
"&",
"symtab",
"{",
"tables",
":",
"make",
"(",
"map",
"[",
"sqlparser",
".",
"TableName",
"]",
"*",
"table",
")",
",",
"uniqueColumns",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"column",
")",
",",
"}",
"\n",
"}"
] | // newSymtab creates a new symtab. | [
"newSymtab",
"creates",
"a",
"new",
"symtab",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L70-L75 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | newSymtabWithRoute | func newSymtabWithRoute(rb *route) *symtab {
return &symtab{
tables: make(map[sqlparser.TableName]*table),
uniqueColumns: make(map[string]*column),
singleRoute: rb,
}
} | go | func newSymtabWithRoute(rb *route) *symtab {
return &symtab{
tables: make(map[sqlparser.TableName]*table),
uniqueColumns: make(map[string]*column),
singleRoute: rb,
}
} | [
"func",
"newSymtabWithRoute",
"(",
"rb",
"*",
"route",
")",
"*",
"symtab",
"{",
"return",
"&",
"symtab",
"{",
"tables",
":",
"make",
"(",
"map",
"[",
"sqlparser",
".",
"TableName",
"]",
"*",
"table",
")",
",",
"uniqueColumns",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"column",
")",
",",
"singleRoute",
":",
"rb",
",",
"}",
"\n",
"}"
] | // newSymtab creates a new symtab initialized
// to contain just one route. | [
"newSymtab",
"creates",
"a",
"new",
"symtab",
"initialized",
"to",
"contain",
"just",
"one",
"route",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L79-L85 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | AddVSchemaTable | func (st *symtab) AddVSchemaTable(alias sqlparser.TableName, vschemaTables []*vindexes.Table, rb *route) (vindexMaps []map[*column]vindexes.Vindex, err error) {
t := &table{
alias: alias,
origin: rb,
}
vindexMaps = make([]map[*column]vindexes.Vindex, len(vschemaTables))
for i, vst := range vschemaTables {
// If any input is authoritative, we make the table authoritative.
// TODO(sougou): vschema builder should validate that authoritative columns match.
if vst.ColumnListAuthoritative {
t.isAuthoritative = true
}
for _, col := range vst.Columns {
t.addColumn(col.Name, &column{
origin: rb,
st: st,
typ: col.Type,
})
}
var vindexMap map[*column]vindexes.Vindex
for _, cv := range vst.ColumnVindexes {
for i, cvcol := range cv.Columns {
col, ok := t.columns[cvcol.Lowered()]
if !ok {
col = &column{
origin: rb,
st: st,
}
t.addColumn(cvcol, col)
}
if i == 0 {
// For now, only the first column is used for vindex Map functions.
if vindexMap == nil {
vindexMap = make(map[*column]vindexes.Vindex)
}
vindexMap[col] = cv.Vindex
}
}
}
vindexMaps[i] = vindexMap
if ai := vst.AutoIncrement; ai != nil {
if _, ok := t.columns[ai.Column.Lowered()]; !ok {
t.addColumn(ai.Column, &column{
origin: rb,
st: st,
})
}
}
}
if err := st.AddTable(t); err != nil {
return nil, err
}
return vindexMaps, nil
} | go | func (st *symtab) AddVSchemaTable(alias sqlparser.TableName, vschemaTables []*vindexes.Table, rb *route) (vindexMaps []map[*column]vindexes.Vindex, err error) {
t := &table{
alias: alias,
origin: rb,
}
vindexMaps = make([]map[*column]vindexes.Vindex, len(vschemaTables))
for i, vst := range vschemaTables {
// If any input is authoritative, we make the table authoritative.
// TODO(sougou): vschema builder should validate that authoritative columns match.
if vst.ColumnListAuthoritative {
t.isAuthoritative = true
}
for _, col := range vst.Columns {
t.addColumn(col.Name, &column{
origin: rb,
st: st,
typ: col.Type,
})
}
var vindexMap map[*column]vindexes.Vindex
for _, cv := range vst.ColumnVindexes {
for i, cvcol := range cv.Columns {
col, ok := t.columns[cvcol.Lowered()]
if !ok {
col = &column{
origin: rb,
st: st,
}
t.addColumn(cvcol, col)
}
if i == 0 {
// For now, only the first column is used for vindex Map functions.
if vindexMap == nil {
vindexMap = make(map[*column]vindexes.Vindex)
}
vindexMap[col] = cv.Vindex
}
}
}
vindexMaps[i] = vindexMap
if ai := vst.AutoIncrement; ai != nil {
if _, ok := t.columns[ai.Column.Lowered()]; !ok {
t.addColumn(ai.Column, &column{
origin: rb,
st: st,
})
}
}
}
if err := st.AddTable(t); err != nil {
return nil, err
}
return vindexMaps, nil
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"AddVSchemaTable",
"(",
"alias",
"sqlparser",
".",
"TableName",
",",
"vschemaTables",
"[",
"]",
"*",
"vindexes",
".",
"Table",
",",
"rb",
"*",
"route",
")",
"(",
"vindexMaps",
"[",
"]",
"map",
"[",
"*",
"column",
"]",
"vindexes",
".",
"Vindex",
",",
"err",
"error",
")",
"{",
"t",
":=",
"&",
"table",
"{",
"alias",
":",
"alias",
",",
"origin",
":",
"rb",
",",
"}",
"\n\n",
"vindexMaps",
"=",
"make",
"(",
"[",
"]",
"map",
"[",
"*",
"column",
"]",
"vindexes",
".",
"Vindex",
",",
"len",
"(",
"vschemaTables",
")",
")",
"\n",
"for",
"i",
",",
"vst",
":=",
"range",
"vschemaTables",
"{",
"// If any input is authoritative, we make the table authoritative.",
"// TODO(sougou): vschema builder should validate that authoritative columns match.",
"if",
"vst",
".",
"ColumnListAuthoritative",
"{",
"t",
".",
"isAuthoritative",
"=",
"true",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"col",
":=",
"range",
"vst",
".",
"Columns",
"{",
"t",
".",
"addColumn",
"(",
"col",
".",
"Name",
",",
"&",
"column",
"{",
"origin",
":",
"rb",
",",
"st",
":",
"st",
",",
"typ",
":",
"col",
".",
"Type",
",",
"}",
")",
"\n",
"}",
"\n\n",
"var",
"vindexMap",
"map",
"[",
"*",
"column",
"]",
"vindexes",
".",
"Vindex",
"\n",
"for",
"_",
",",
"cv",
":=",
"range",
"vst",
".",
"ColumnVindexes",
"{",
"for",
"i",
",",
"cvcol",
":=",
"range",
"cv",
".",
"Columns",
"{",
"col",
",",
"ok",
":=",
"t",
".",
"columns",
"[",
"cvcol",
".",
"Lowered",
"(",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"col",
"=",
"&",
"column",
"{",
"origin",
":",
"rb",
",",
"st",
":",
"st",
",",
"}",
"\n",
"t",
".",
"addColumn",
"(",
"cvcol",
",",
"col",
")",
"\n",
"}",
"\n",
"if",
"i",
"==",
"0",
"{",
"// For now, only the first column is used for vindex Map functions.",
"if",
"vindexMap",
"==",
"nil",
"{",
"vindexMap",
"=",
"make",
"(",
"map",
"[",
"*",
"column",
"]",
"vindexes",
".",
"Vindex",
")",
"\n",
"}",
"\n",
"vindexMap",
"[",
"col",
"]",
"=",
"cv",
".",
"Vindex",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"vindexMaps",
"[",
"i",
"]",
"=",
"vindexMap",
"\n\n",
"if",
"ai",
":=",
"vst",
".",
"AutoIncrement",
";",
"ai",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"t",
".",
"columns",
"[",
"ai",
".",
"Column",
".",
"Lowered",
"(",
")",
"]",
";",
"!",
"ok",
"{",
"t",
".",
"addColumn",
"(",
"ai",
".",
"Column",
",",
"&",
"column",
"{",
"origin",
":",
"rb",
",",
"st",
":",
"st",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"\n",
"if",
"err",
":=",
"st",
".",
"AddTable",
"(",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"vindexMaps",
",",
"nil",
"\n",
"}"
] | // AddVSchemaTable takes a list of vschema tables as input and
// creates a table with multiple route options. It returns a
// list of vindex maps, one for each input. | [
"AddVSchemaTable",
"takes",
"a",
"list",
"of",
"vschema",
"tables",
"as",
"input",
"and",
"creates",
"a",
"table",
"with",
"multiple",
"route",
"options",
".",
"It",
"returns",
"a",
"list",
"of",
"vindex",
"maps",
"one",
"for",
"each",
"input",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L90-L148 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | Merge | func (st *symtab) Merge(newsyms *symtab) error {
if st.tableNames == nil || newsyms.tableNames == nil {
// If any side of symtab has anonymous tables,
// we treat the merged symtab as having anonymous tables.
return nil
}
for _, t := range newsyms.tables {
if err := st.AddTable(t); err != nil {
return err
}
}
return nil
} | go | func (st *symtab) Merge(newsyms *symtab) error {
if st.tableNames == nil || newsyms.tableNames == nil {
// If any side of symtab has anonymous tables,
// we treat the merged symtab as having anonymous tables.
return nil
}
for _, t := range newsyms.tables {
if err := st.AddTable(t); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"Merge",
"(",
"newsyms",
"*",
"symtab",
")",
"error",
"{",
"if",
"st",
".",
"tableNames",
"==",
"nil",
"||",
"newsyms",
".",
"tableNames",
"==",
"nil",
"{",
"// If any side of symtab has anonymous tables,",
"// we treat the merged symtab as having anonymous tables.",
"return",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"newsyms",
".",
"tables",
"{",
"if",
"err",
":=",
"st",
".",
"AddTable",
"(",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Merge merges the new symtab into the current one.
// Duplicate table aliases return an error.
// uniqueColumns is updated, but duplicates are removed.
// Merges are only performed during the FROM clause analysis.
// At this point, only tables and uniqueColumns are set.
// All other fields are ignored. | [
"Merge",
"merges",
"the",
"new",
"symtab",
"into",
"the",
"current",
"one",
".",
"Duplicate",
"table",
"aliases",
"return",
"an",
"error",
".",
"uniqueColumns",
"is",
"updated",
"but",
"duplicates",
"are",
"removed",
".",
"Merges",
"are",
"only",
"performed",
"during",
"the",
"FROM",
"clause",
"analysis",
".",
"At",
"this",
"point",
"only",
"tables",
"and",
"uniqueColumns",
"are",
"set",
".",
"All",
"other",
"fields",
"are",
"ignored",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L156-L168 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | AddTable | func (st *symtab) AddTable(t *table) error {
if rb, ok := t.origin.(*route); !ok || rb.Resolve() != st.singleRoute {
st.singleRoute = nil
}
if _, ok := st.tables[t.alias]; ok {
return fmt.Errorf("duplicate symbol: %s", sqlparser.String(t.alias))
}
st.tables[t.alias] = t
st.tableNames = append(st.tableNames, t.alias)
// update the uniqueColumns list, and eliminate
// duplicate symbols if found.
for colname, c := range t.columns {
c.st = st
if _, ok := st.uniqueColumns[colname]; ok {
// Keep the entry, but make it nil. This will
// ensure that yet another column of the same name
// doesn't get added back in.
st.uniqueColumns[colname] = nil
continue
}
st.uniqueColumns[colname] = c
}
return nil
} | go | func (st *symtab) AddTable(t *table) error {
if rb, ok := t.origin.(*route); !ok || rb.Resolve() != st.singleRoute {
st.singleRoute = nil
}
if _, ok := st.tables[t.alias]; ok {
return fmt.Errorf("duplicate symbol: %s", sqlparser.String(t.alias))
}
st.tables[t.alias] = t
st.tableNames = append(st.tableNames, t.alias)
// update the uniqueColumns list, and eliminate
// duplicate symbols if found.
for colname, c := range t.columns {
c.st = st
if _, ok := st.uniqueColumns[colname]; ok {
// Keep the entry, but make it nil. This will
// ensure that yet another column of the same name
// doesn't get added back in.
st.uniqueColumns[colname] = nil
continue
}
st.uniqueColumns[colname] = c
}
return nil
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"AddTable",
"(",
"t",
"*",
"table",
")",
"error",
"{",
"if",
"rb",
",",
"ok",
":=",
"t",
".",
"origin",
".",
"(",
"*",
"route",
")",
";",
"!",
"ok",
"||",
"rb",
".",
"Resolve",
"(",
")",
"!=",
"st",
".",
"singleRoute",
"{",
"st",
".",
"singleRoute",
"=",
"nil",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"st",
".",
"tables",
"[",
"t",
".",
"alias",
"]",
";",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sqlparser",
".",
"String",
"(",
"t",
".",
"alias",
")",
")",
"\n",
"}",
"\n",
"st",
".",
"tables",
"[",
"t",
".",
"alias",
"]",
"=",
"t",
"\n",
"st",
".",
"tableNames",
"=",
"append",
"(",
"st",
".",
"tableNames",
",",
"t",
".",
"alias",
")",
"\n\n",
"// update the uniqueColumns list, and eliminate",
"// duplicate symbols if found.",
"for",
"colname",
",",
"c",
":=",
"range",
"t",
".",
"columns",
"{",
"c",
".",
"st",
"=",
"st",
"\n",
"if",
"_",
",",
"ok",
":=",
"st",
".",
"uniqueColumns",
"[",
"colname",
"]",
";",
"ok",
"{",
"// Keep the entry, but make it nil. This will",
"// ensure that yet another column of the same name",
"// doesn't get added back in.",
"st",
".",
"uniqueColumns",
"[",
"colname",
"]",
"=",
"nil",
"\n",
"continue",
"\n",
"}",
"\n",
"st",
".",
"uniqueColumns",
"[",
"colname",
"]",
"=",
"c",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // AddTable adds a table to symtab. | [
"AddTable",
"adds",
"a",
"table",
"to",
"symtab",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L171-L195 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | AllTables | func (st *symtab) AllTables() []*table {
if len(st.tableNames) == 0 {
return nil
}
tables := make([]*table, 0, len(st.tableNames))
for _, tname := range st.tableNames {
tables = append(tables, st.tables[tname])
}
return tables
} | go | func (st *symtab) AllTables() []*table {
if len(st.tableNames) == 0 {
return nil
}
tables := make([]*table, 0, len(st.tableNames))
for _, tname := range st.tableNames {
tables = append(tables, st.tables[tname])
}
return tables
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"AllTables",
"(",
")",
"[",
"]",
"*",
"table",
"{",
"if",
"len",
"(",
"st",
".",
"tableNames",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"tables",
":=",
"make",
"(",
"[",
"]",
"*",
"table",
",",
"0",
",",
"len",
"(",
"st",
".",
"tableNames",
")",
")",
"\n",
"for",
"_",
",",
"tname",
":=",
"range",
"st",
".",
"tableNames",
"{",
"tables",
"=",
"append",
"(",
"tables",
",",
"st",
".",
"tables",
"[",
"tname",
"]",
")",
"\n",
"}",
"\n",
"return",
"tables",
"\n",
"}"
] | // AllTables returns an ordered list of all current tables. | [
"AllTables",
"returns",
"an",
"ordered",
"list",
"of",
"all",
"current",
"tables",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L198-L207 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | SetResultColumns | func (st *symtab) SetResultColumns(rcs []*resultColumn) {
for _, rc := range rcs {
rc.column.st = st
}
st.ResultColumns = rcs
} | go | func (st *symtab) SetResultColumns(rcs []*resultColumn) {
for _, rc := range rcs {
rc.column.st = st
}
st.ResultColumns = rcs
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"SetResultColumns",
"(",
"rcs",
"[",
"]",
"*",
"resultColumn",
")",
"{",
"for",
"_",
",",
"rc",
":=",
"range",
"rcs",
"{",
"rc",
".",
"column",
".",
"st",
"=",
"st",
"\n",
"}",
"\n",
"st",
".",
"ResultColumns",
"=",
"rcs",
"\n",
"}"
] | // SetResultColumns sets the result columns. | [
"SetResultColumns",
"sets",
"the",
"result",
"columns",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L229-L234 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | searchResultColumn | func (st *symtab) searchResultColumn(col *sqlparser.ColName) (c *column, err error) {
var cursym *resultColumn
for _, rc := range st.ResultColumns {
if rc.alias.Equal(col.Name) {
if cursym != nil {
return nil, fmt.Errorf("ambiguous symbol reference: %v", sqlparser.String(col))
}
cursym = rc
}
}
if cursym != nil {
return cursym.column, nil
}
return nil, nil
} | go | func (st *symtab) searchResultColumn(col *sqlparser.ColName) (c *column, err error) {
var cursym *resultColumn
for _, rc := range st.ResultColumns {
if rc.alias.Equal(col.Name) {
if cursym != nil {
return nil, fmt.Errorf("ambiguous symbol reference: %v", sqlparser.String(col))
}
cursym = rc
}
}
if cursym != nil {
return cursym.column, nil
}
return nil, nil
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"searchResultColumn",
"(",
"col",
"*",
"sqlparser",
".",
"ColName",
")",
"(",
"c",
"*",
"column",
",",
"err",
"error",
")",
"{",
"var",
"cursym",
"*",
"resultColumn",
"\n",
"for",
"_",
",",
"rc",
":=",
"range",
"st",
".",
"ResultColumns",
"{",
"if",
"rc",
".",
"alias",
".",
"Equal",
"(",
"col",
".",
"Name",
")",
"{",
"if",
"cursym",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sqlparser",
".",
"String",
"(",
"col",
")",
")",
"\n",
"}",
"\n",
"cursym",
"=",
"rc",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"cursym",
"!=",
"nil",
"{",
"return",
"cursym",
".",
"column",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // searchResultColumn looks for col in the results columns. | [
"searchResultColumn",
"looks",
"for",
"col",
"in",
"the",
"results",
"columns",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L312-L326 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | searchTables | func (st *symtab) searchTables(col *sqlparser.ColName) (*column, error) {
var t *table
// @@ syntax is only allowed for dual tables, in which case there should be
// only one in the symtab. So, such expressions will be implicitly matched.
if col.Qualifier.IsEmpty() || strings.HasPrefix(col.Qualifier.Name.String(), "@@") {
// Search uniqueColumns first. If found, our job is done.
// Check for nil because there can be nil entries if there
// are duplicate columns across multiple tables.
if c := st.uniqueColumns[col.Name.Lowered()]; c != nil {
return c, nil
}
switch {
case len(st.tables) == 1:
// If there's only one table match against it.
// Loop executes once to match the only table.
for _, v := range st.tables {
t = v
}
// No return: break out.
case st.singleRoute != nil:
// If there's only one route, create an anonymous symbol.
return &column{origin: st.singleRoute, st: st}, nil
default:
// If none of the above, the symbol is unresolvable.
return nil, fmt.Errorf("symbol %s not found", sqlparser.String(col))
}
} else {
var ok bool
t, ok = st.tables[col.Qualifier]
if !ok {
return nil, nil
}
}
// At this point, t should be set.
c, ok := t.columns[col.Name.Lowered()]
if !ok {
// We know all the column names of a subquery. Might as well return an error if it's not found.
if t.isAuthoritative {
return nil, fmt.Errorf("symbol %s not found in table or subquery", sqlparser.String(col))
}
c = &column{
origin: t.Origin(),
st: st,
}
t.addColumn(col.Name, c)
}
return c, nil
} | go | func (st *symtab) searchTables(col *sqlparser.ColName) (*column, error) {
var t *table
// @@ syntax is only allowed for dual tables, in which case there should be
// only one in the symtab. So, such expressions will be implicitly matched.
if col.Qualifier.IsEmpty() || strings.HasPrefix(col.Qualifier.Name.String(), "@@") {
// Search uniqueColumns first. If found, our job is done.
// Check for nil because there can be nil entries if there
// are duplicate columns across multiple tables.
if c := st.uniqueColumns[col.Name.Lowered()]; c != nil {
return c, nil
}
switch {
case len(st.tables) == 1:
// If there's only one table match against it.
// Loop executes once to match the only table.
for _, v := range st.tables {
t = v
}
// No return: break out.
case st.singleRoute != nil:
// If there's only one route, create an anonymous symbol.
return &column{origin: st.singleRoute, st: st}, nil
default:
// If none of the above, the symbol is unresolvable.
return nil, fmt.Errorf("symbol %s not found", sqlparser.String(col))
}
} else {
var ok bool
t, ok = st.tables[col.Qualifier]
if !ok {
return nil, nil
}
}
// At this point, t should be set.
c, ok := t.columns[col.Name.Lowered()]
if !ok {
// We know all the column names of a subquery. Might as well return an error if it's not found.
if t.isAuthoritative {
return nil, fmt.Errorf("symbol %s not found in table or subquery", sqlparser.String(col))
}
c = &column{
origin: t.Origin(),
st: st,
}
t.addColumn(col.Name, c)
}
return c, nil
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"searchTables",
"(",
"col",
"*",
"sqlparser",
".",
"ColName",
")",
"(",
"*",
"column",
",",
"error",
")",
"{",
"var",
"t",
"*",
"table",
"\n",
"// @@ syntax is only allowed for dual tables, in which case there should be",
"// only one in the symtab. So, such expressions will be implicitly matched.",
"if",
"col",
".",
"Qualifier",
".",
"IsEmpty",
"(",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"col",
".",
"Qualifier",
".",
"Name",
".",
"String",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"// Search uniqueColumns first. If found, our job is done.",
"// Check for nil because there can be nil entries if there",
"// are duplicate columns across multiple tables.",
"if",
"c",
":=",
"st",
".",
"uniqueColumns",
"[",
"col",
".",
"Name",
".",
"Lowered",
"(",
")",
"]",
";",
"c",
"!=",
"nil",
"{",
"return",
"c",
",",
"nil",
"\n",
"}",
"\n\n",
"switch",
"{",
"case",
"len",
"(",
"st",
".",
"tables",
")",
"==",
"1",
":",
"// If there's only one table match against it.",
"// Loop executes once to match the only table.",
"for",
"_",
",",
"v",
":=",
"range",
"st",
".",
"tables",
"{",
"t",
"=",
"v",
"\n",
"}",
"\n",
"// No return: break out.",
"case",
"st",
".",
"singleRoute",
"!=",
"nil",
":",
"// If there's only one route, create an anonymous symbol.",
"return",
"&",
"column",
"{",
"origin",
":",
"st",
".",
"singleRoute",
",",
"st",
":",
"st",
"}",
",",
"nil",
"\n",
"default",
":",
"// If none of the above, the symbol is unresolvable.",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sqlparser",
".",
"String",
"(",
"col",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"var",
"ok",
"bool",
"\n",
"t",
",",
"ok",
"=",
"st",
".",
"tables",
"[",
"col",
".",
"Qualifier",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// At this point, t should be set.",
"c",
",",
"ok",
":=",
"t",
".",
"columns",
"[",
"col",
".",
"Name",
".",
"Lowered",
"(",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// We know all the column names of a subquery. Might as well return an error if it's not found.",
"if",
"t",
".",
"isAuthoritative",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sqlparser",
".",
"String",
"(",
"col",
")",
")",
"\n",
"}",
"\n",
"c",
"=",
"&",
"column",
"{",
"origin",
":",
"t",
".",
"Origin",
"(",
")",
",",
"st",
":",
"st",
",",
"}",
"\n",
"t",
".",
"addColumn",
"(",
"col",
".",
"Name",
",",
"c",
")",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // searchTables looks for the column in the tables. The search order
// is as described in Find. | [
"searchTables",
"looks",
"for",
"the",
"column",
"in",
"the",
"tables",
".",
"The",
"search",
"order",
"is",
"as",
"described",
"in",
"Find",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L330-L379 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | ResultFromNumber | func ResultFromNumber(rcs []*resultColumn, val *sqlparser.SQLVal) (int, error) {
if val.Type != sqlparser.IntVal {
return 0, errors.New("column number is not an int")
}
num, err := strconv.ParseInt(string(val.Val), 0, 64)
if err != nil {
return 0, fmt.Errorf("error parsing column number: %s", sqlparser.String(val))
}
if num < 1 || num > int64(len(rcs)) {
return 0, fmt.Errorf("column number out of range: %d", num)
}
return int(num - 1), nil
} | go | func ResultFromNumber(rcs []*resultColumn, val *sqlparser.SQLVal) (int, error) {
if val.Type != sqlparser.IntVal {
return 0, errors.New("column number is not an int")
}
num, err := strconv.ParseInt(string(val.Val), 0, 64)
if err != nil {
return 0, fmt.Errorf("error parsing column number: %s", sqlparser.String(val))
}
if num < 1 || num > int64(len(rcs)) {
return 0, fmt.Errorf("column number out of range: %d", num)
}
return int(num - 1), nil
} | [
"func",
"ResultFromNumber",
"(",
"rcs",
"[",
"]",
"*",
"resultColumn",
",",
"val",
"*",
"sqlparser",
".",
"SQLVal",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"val",
".",
"Type",
"!=",
"sqlparser",
".",
"IntVal",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"num",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"string",
"(",
"val",
".",
"Val",
")",
",",
"0",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sqlparser",
".",
"String",
"(",
"val",
")",
")",
"\n",
"}",
"\n",
"if",
"num",
"<",
"1",
"||",
"num",
">",
"int64",
"(",
"len",
"(",
"rcs",
")",
")",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"num",
")",
"\n",
"}",
"\n",
"return",
"int",
"(",
"num",
"-",
"1",
")",
",",
"nil",
"\n",
"}"
] | // ResultFromNumber returns the result column index based on the column
// order expression. | [
"ResultFromNumber",
"returns",
"the",
"result",
"column",
"index",
"based",
"on",
"the",
"column",
"order",
"expression",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L383-L395 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | ResolveSymbols | func (st *symtab) ResolveSymbols(node sqlparser.SQLNode) error {
return sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch node := node.(type) {
case *sqlparser.ColName:
if _, _, err := st.Find(node); err != nil {
return false, err
}
case *sqlparser.Subquery:
return false, errors.New("subqueries disallowed")
}
return true, nil
}, node)
} | go | func (st *symtab) ResolveSymbols(node sqlparser.SQLNode) error {
return sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) {
switch node := node.(type) {
case *sqlparser.ColName:
if _, _, err := st.Find(node); err != nil {
return false, err
}
case *sqlparser.Subquery:
return false, errors.New("subqueries disallowed")
}
return true, nil
}, node)
} | [
"func",
"(",
"st",
"*",
"symtab",
")",
"ResolveSymbols",
"(",
"node",
"sqlparser",
".",
"SQLNode",
")",
"error",
"{",
"return",
"sqlparser",
".",
"Walk",
"(",
"func",
"(",
"node",
"sqlparser",
".",
"SQLNode",
")",
"(",
"kontinue",
"bool",
",",
"err",
"error",
")",
"{",
"switch",
"node",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"sqlparser",
".",
"ColName",
":",
"if",
"_",
",",
"_",
",",
"err",
":=",
"st",
".",
"Find",
"(",
"node",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"case",
"*",
"sqlparser",
".",
"Subquery",
":",
"return",
"false",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}",
",",
"node",
")",
"\n",
"}"
] | // ResolveSymbols resolves all column references against symtab.
// This makes sure that they all have their Metadata initialized.
// If a symbol cannot be resolved or if the expression contains
// a subquery, an error is returned. | [
"ResolveSymbols",
"resolves",
"all",
"column",
"references",
"against",
"symtab",
".",
"This",
"makes",
"sure",
"that",
"they",
"all",
"have",
"their",
"Metadata",
"initialized",
".",
"If",
"a",
"symbol",
"cannot",
"be",
"resolved",
"or",
"if",
"the",
"expression",
"contains",
"a",
"subquery",
"an",
"error",
"is",
"returned",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L401-L413 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | Origin | func (t *table) Origin() builder {
// If it's a route, we have to resolve it.
if rb, ok := t.origin.(*route); ok {
return rb.Resolve()
}
return t.origin
} | go | func (t *table) Origin() builder {
// If it's a route, we have to resolve it.
if rb, ok := t.origin.(*route); ok {
return rb.Resolve()
}
return t.origin
} | [
"func",
"(",
"t",
"*",
"table",
")",
"Origin",
"(",
")",
"builder",
"{",
"// If it's a route, we have to resolve it.",
"if",
"rb",
",",
"ok",
":=",
"t",
".",
"origin",
".",
"(",
"*",
"route",
")",
";",
"ok",
"{",
"return",
"rb",
".",
"Resolve",
"(",
")",
"\n",
"}",
"\n",
"return",
"t",
".",
"origin",
"\n",
"}"
] | // Origin returns the route that originates the table. | [
"Origin",
"returns",
"the",
"route",
"that",
"originates",
"the",
"table",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L440-L446 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | Origin | func (c *column) Origin() builder {
// If it's a route, we have to resolve it.
if rb, ok := c.origin.(*route); ok {
return rb.Resolve()
}
return c.origin
} | go | func (c *column) Origin() builder {
// If it's a route, we have to resolve it.
if rb, ok := c.origin.(*route); ok {
return rb.Resolve()
}
return c.origin
} | [
"func",
"(",
"c",
"*",
"column",
")",
"Origin",
"(",
")",
"builder",
"{",
"// If it's a route, we have to resolve it.",
"if",
"rb",
",",
"ok",
":=",
"c",
".",
"origin",
".",
"(",
"*",
"route",
")",
";",
"ok",
"{",
"return",
"rb",
".",
"Resolve",
"(",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"origin",
"\n",
"}"
] | // Origin returns the route that originates the column. | [
"Origin",
"returns",
"the",
"route",
"that",
"originates",
"the",
"column",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L464-L470 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/symtab.go | newResultColumn | func newResultColumn(expr *sqlparser.AliasedExpr, origin builder) *resultColumn {
rc := &resultColumn{
alias: expr.As,
}
if col, ok := expr.Expr.(*sqlparser.ColName); ok {
// If no alias was specified, then the base name
// of the column becomes the alias.
if rc.alias.IsEmpty() {
rc.alias = col.Name
}
// If it's a col it should already have metadata.
rc.column = col.Metadata.(*column)
} else {
// We don't generate an alias if the expression is non-trivial.
// Just to be safe, generate an anonymous column for the expression.
rc.column = &column{
origin: origin,
}
}
return rc
} | go | func newResultColumn(expr *sqlparser.AliasedExpr, origin builder) *resultColumn {
rc := &resultColumn{
alias: expr.As,
}
if col, ok := expr.Expr.(*sqlparser.ColName); ok {
// If no alias was specified, then the base name
// of the column becomes the alias.
if rc.alias.IsEmpty() {
rc.alias = col.Name
}
// If it's a col it should already have metadata.
rc.column = col.Metadata.(*column)
} else {
// We don't generate an alias if the expression is non-trivial.
// Just to be safe, generate an anonymous column for the expression.
rc.column = &column{
origin: origin,
}
}
return rc
} | [
"func",
"newResultColumn",
"(",
"expr",
"*",
"sqlparser",
".",
"AliasedExpr",
",",
"origin",
"builder",
")",
"*",
"resultColumn",
"{",
"rc",
":=",
"&",
"resultColumn",
"{",
"alias",
":",
"expr",
".",
"As",
",",
"}",
"\n",
"if",
"col",
",",
"ok",
":=",
"expr",
".",
"Expr",
".",
"(",
"*",
"sqlparser",
".",
"ColName",
")",
";",
"ok",
"{",
"// If no alias was specified, then the base name",
"// of the column becomes the alias.",
"if",
"rc",
".",
"alias",
".",
"IsEmpty",
"(",
")",
"{",
"rc",
".",
"alias",
"=",
"col",
".",
"Name",
"\n",
"}",
"\n",
"// If it's a col it should already have metadata.",
"rc",
".",
"column",
"=",
"col",
".",
"Metadata",
".",
"(",
"*",
"column",
")",
"\n",
"}",
"else",
"{",
"// We don't generate an alias if the expression is non-trivial.",
"// Just to be safe, generate an anonymous column for the expression.",
"rc",
".",
"column",
"=",
"&",
"column",
"{",
"origin",
":",
"origin",
",",
"}",
"\n",
"}",
"\n",
"return",
"rc",
"\n",
"}"
] | // NewResultColumn creates a new resultColumn based on the supplied expression.
// The created symbol is not remembered until it is later set as ResultColumns
// after all select expressions are analyzed. | [
"NewResultColumn",
"creates",
"a",
"new",
"resultColumn",
"based",
"on",
"the",
"supplied",
"expression",
".",
"The",
"created",
"symbol",
"is",
"not",
"remembered",
"until",
"it",
"is",
"later",
"set",
"as",
"ResultColumns",
"after",
"all",
"select",
"expressions",
"are",
"analyzed",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/symtab.go#L489-L509 | train |
vitessio/vitess | go/trace/trace.go | NewSpan | func NewSpan(inCtx context.Context, label string) (Span, context.Context) {
parent, _ := spanFactory.FromContext(inCtx)
span := spanFactory.New(parent, label)
outCtx := spanFactory.NewContext(inCtx, span)
return span, outCtx
} | go | func NewSpan(inCtx context.Context, label string) (Span, context.Context) {
parent, _ := spanFactory.FromContext(inCtx)
span := spanFactory.New(parent, label)
outCtx := spanFactory.NewContext(inCtx, span)
return span, outCtx
} | [
"func",
"NewSpan",
"(",
"inCtx",
"context",
".",
"Context",
",",
"label",
"string",
")",
"(",
"Span",
",",
"context",
".",
"Context",
")",
"{",
"parent",
",",
"_",
":=",
"spanFactory",
".",
"FromContext",
"(",
"inCtx",
")",
"\n",
"span",
":=",
"spanFactory",
".",
"New",
"(",
"parent",
",",
"label",
")",
"\n",
"outCtx",
":=",
"spanFactory",
".",
"NewContext",
"(",
"inCtx",
",",
"span",
")",
"\n\n",
"return",
"span",
",",
"outCtx",
"\n",
"}"
] | // NewSpan creates a new Span with the currently installed tracing plugin.
// If no tracing plugin is installed, it returns a fake Span that does nothing. | [
"NewSpan",
"creates",
"a",
"new",
"Span",
"with",
"the",
"currently",
"installed",
"tracing",
"plugin",
".",
"If",
"no",
"tracing",
"plugin",
"is",
"installed",
"it",
"returns",
"a",
"fake",
"Span",
"that",
"does",
"nothing",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/trace.go#L47-L53 | train |
vitessio/vitess | go/trace/trace.go | NewContext | func NewContext(parent context.Context, span Span) context.Context {
return spanFactory.NewContext(parent, span)
} | go | func NewContext(parent context.Context, span Span) context.Context {
return spanFactory.NewContext(parent, span)
} | [
"func",
"NewContext",
"(",
"parent",
"context",
".",
"Context",
",",
"span",
"Span",
")",
"context",
".",
"Context",
"{",
"return",
"spanFactory",
".",
"NewContext",
"(",
"parent",
",",
"span",
")",
"\n",
"}"
] | // NewContext returns a context based on parent with a new Span value. | [
"NewContext",
"returns",
"a",
"context",
"based",
"on",
"parent",
"with",
"a",
"new",
"Span",
"value",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/trace.go#L68-L70 | train |
vitessio/vitess | go/trace/trace.go | CopySpan | func CopySpan(parentCtx, spanCtx context.Context) context.Context {
if span, ok := FromContext(spanCtx); ok {
return NewContext(parentCtx, span)
}
return parentCtx
} | go | func CopySpan(parentCtx, spanCtx context.Context) context.Context {
if span, ok := FromContext(spanCtx); ok {
return NewContext(parentCtx, span)
}
return parentCtx
} | [
"func",
"CopySpan",
"(",
"parentCtx",
",",
"spanCtx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"if",
"span",
",",
"ok",
":=",
"FromContext",
"(",
"spanCtx",
")",
";",
"ok",
"{",
"return",
"NewContext",
"(",
"parentCtx",
",",
"span",
")",
"\n",
"}",
"\n",
"return",
"parentCtx",
"\n",
"}"
] | // CopySpan creates a new context from parentCtx, with only the trace span
// copied over from spanCtx, if it has any. If not, parentCtx is returned. | [
"CopySpan",
"creates",
"a",
"new",
"context",
"from",
"parentCtx",
"with",
"only",
"the",
"trace",
"span",
"copied",
"over",
"from",
"spanCtx",
"if",
"it",
"has",
"any",
".",
"If",
"not",
"parentCtx",
"is",
"returned",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/trace.go#L74-L79 | train |
vitessio/vitess | go/trace/trace.go | StartTracing | func StartTracing(serviceName string) io.Closer {
factory, ok := tracingBackendFactories[*tracingServer]
if !ok {
return fail(serviceName)
}
tracer, closer, err := factory(serviceName)
if err != nil {
log.Error(vterrors.Wrapf(err, "failed to create a %s tracer", *tracingServer))
return &nilCloser{}
}
spanFactory = tracer
log.Infof("successfully started tracing with [%s]", *tracingServer)
return closer
} | go | func StartTracing(serviceName string) io.Closer {
factory, ok := tracingBackendFactories[*tracingServer]
if !ok {
return fail(serviceName)
}
tracer, closer, err := factory(serviceName)
if err != nil {
log.Error(vterrors.Wrapf(err, "failed to create a %s tracer", *tracingServer))
return &nilCloser{}
}
spanFactory = tracer
log.Infof("successfully started tracing with [%s]", *tracingServer)
return closer
} | [
"func",
"StartTracing",
"(",
"serviceName",
"string",
")",
"io",
".",
"Closer",
"{",
"factory",
",",
"ok",
":=",
"tracingBackendFactories",
"[",
"*",
"tracingServer",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fail",
"(",
"serviceName",
")",
"\n",
"}",
"\n\n",
"tracer",
",",
"closer",
",",
"err",
":=",
"factory",
"(",
"serviceName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Error",
"(",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"*",
"tracingServer",
")",
")",
"\n",
"return",
"&",
"nilCloser",
"{",
"}",
"\n",
"}",
"\n\n",
"spanFactory",
"=",
"tracer",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"*",
"tracingServer",
")",
"\n\n",
"return",
"closer",
"\n",
"}"
] | // StartTracing enables tracing for a named service | [
"StartTracing",
"enables",
"tracing",
"for",
"a",
"named",
"service"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/trace.go#L119-L136 | train |
vitessio/vitess | go/vt/worker/clone_utils.go | makeValueString | func makeValueString(fields []*querypb.Field, rows [][]sqltypes.Value) string {
buf := bytes.Buffer{}
for i, row := range rows {
if i > 0 {
buf.Write([]byte(",("))
} else {
buf.WriteByte('(')
}
for j, value := range row {
if j > 0 {
buf.WriteByte(',')
}
value.EncodeSQL(&buf)
}
buf.WriteByte(')')
}
return buf.String()
} | go | func makeValueString(fields []*querypb.Field, rows [][]sqltypes.Value) string {
buf := bytes.Buffer{}
for i, row := range rows {
if i > 0 {
buf.Write([]byte(",("))
} else {
buf.WriteByte('(')
}
for j, value := range row {
if j > 0 {
buf.WriteByte(',')
}
value.EncodeSQL(&buf)
}
buf.WriteByte(')')
}
return buf.String()
} | [
"func",
"makeValueString",
"(",
"fields",
"[",
"]",
"*",
"querypb",
".",
"Field",
",",
"rows",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
")",
"string",
"{",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"for",
"i",
",",
"row",
":=",
"range",
"rows",
"{",
"if",
"i",
">",
"0",
"{",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteByte",
"(",
"'('",
")",
"\n",
"}",
"\n",
"for",
"j",
",",
"value",
":=",
"range",
"row",
"{",
"if",
"j",
">",
"0",
"{",
"buf",
".",
"WriteByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"value",
".",
"EncodeSQL",
"(",
"&",
"buf",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteByte",
"(",
"')'",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // makeValueString returns a string that contains all the passed-in rows
// as an insert SQL command's parameters. | [
"makeValueString",
"returns",
"a",
"string",
"that",
"contains",
"all",
"the",
"passed",
"-",
"in",
"rows",
"as",
"an",
"insert",
"SQL",
"command",
"s",
"parameters",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/clone_utils.go#L37-L54 | train |
vitessio/vitess | go/vt/vttablet/grpctmclient/client.go | dial | func (client *Client) dial(tablet *topodatapb.Tablet) (*grpc.ClientConn, tabletmanagerservicepb.TabletManagerClient, error) {
addr := netutil.JoinHostPort(tablet.Hostname, int32(tablet.PortMap["grpc"]))
opt, err := grpcclient.SecureDialOption(*cert, *key, *ca, *name)
if err != nil {
return nil, nil, err
}
cc, err := grpcclient.Dial(addr, grpcclient.FailFast(false), opt)
if err != nil {
return nil, nil, err
}
return cc, tabletmanagerservicepb.NewTabletManagerClient(cc), nil
} | go | func (client *Client) dial(tablet *topodatapb.Tablet) (*grpc.ClientConn, tabletmanagerservicepb.TabletManagerClient, error) {
addr := netutil.JoinHostPort(tablet.Hostname, int32(tablet.PortMap["grpc"]))
opt, err := grpcclient.SecureDialOption(*cert, *key, *ca, *name)
if err != nil {
return nil, nil, err
}
cc, err := grpcclient.Dial(addr, grpcclient.FailFast(false), opt)
if err != nil {
return nil, nil, err
}
return cc, tabletmanagerservicepb.NewTabletManagerClient(cc), nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"dial",
"(",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
")",
"(",
"*",
"grpc",
".",
"ClientConn",
",",
"tabletmanagerservicepb",
".",
"TabletManagerClient",
",",
"error",
")",
"{",
"addr",
":=",
"netutil",
".",
"JoinHostPort",
"(",
"tablet",
".",
"Hostname",
",",
"int32",
"(",
"tablet",
".",
"PortMap",
"[",
"\"",
"\"",
"]",
")",
")",
"\n",
"opt",
",",
"err",
":=",
"grpcclient",
".",
"SecureDialOption",
"(",
"*",
"cert",
",",
"*",
"key",
",",
"*",
"ca",
",",
"*",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cc",
",",
"err",
":=",
"grpcclient",
".",
"Dial",
"(",
"addr",
",",
"grpcclient",
".",
"FailFast",
"(",
"false",
")",
",",
"opt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"cc",
",",
"tabletmanagerservicepb",
".",
"NewTabletManagerClient",
"(",
"cc",
")",
",",
"nil",
"\n",
"}"
] | // dial returns a client to use | [
"dial",
"returns",
"a",
"client",
"to",
"use"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/grpctmclient/client.go#L80-L91 | train |
vitessio/vitess | go/vt/vttablet/grpctmclient/client.go | Ping | func (client *Client) Ping(ctx context.Context, tablet *topodatapb.Tablet) error {
cc, c, err := client.dial(tablet)
if err != nil {
return err
}
defer cc.Close()
result, err := c.Ping(ctx, &tabletmanagerdatapb.PingRequest{
Payload: "payload",
})
if err != nil {
return err
}
if result.Payload != "payload" {
return fmt.Errorf("bad ping result: %v", result.Payload)
}
return nil
} | go | func (client *Client) Ping(ctx context.Context, tablet *topodatapb.Tablet) error {
cc, c, err := client.dial(tablet)
if err != nil {
return err
}
defer cc.Close()
result, err := c.Ping(ctx, &tabletmanagerdatapb.PingRequest{
Payload: "payload",
})
if err != nil {
return err
}
if result.Payload != "payload" {
return fmt.Errorf("bad ping result: %v", result.Payload)
}
return nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"Ping",
"(",
"ctx",
"context",
".",
"Context",
",",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
")",
"error",
"{",
"cc",
",",
"c",
",",
"err",
":=",
"client",
".",
"dial",
"(",
"tablet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"cc",
".",
"Close",
"(",
")",
"\n",
"result",
",",
"err",
":=",
"c",
".",
"Ping",
"(",
"ctx",
",",
"&",
"tabletmanagerdatapb",
".",
"PingRequest",
"{",
"Payload",
":",
"\"",
"\"",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"result",
".",
"Payload",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"result",
".",
"Payload",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | //
// Various read-only methods
//
// Ping is part of the tmclient.TabletManagerClient interface. | [
"Various",
"read",
"-",
"only",
"methods",
"Ping",
"is",
"part",
"of",
"the",
"tmclient",
".",
"TabletManagerClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/grpctmclient/client.go#L134-L150 | train |
vitessio/vitess | go/vt/vttablet/grpctmclient/client.go | ExecuteFetchAsDba | func (client *Client) ExecuteFetchAsDba(ctx context.Context, tablet *topodatapb.Tablet, usePool bool, query []byte, maxRows int, disableBinlogs, reloadSchema bool) (*querypb.QueryResult, error) {
var c tabletmanagerservicepb.TabletManagerClient
var err error
if usePool {
c, err = client.dialPool(tablet)
if err != nil {
return nil, err
}
} else {
var cc *grpc.ClientConn
cc, c, err = client.dial(tablet)
if err != nil {
return nil, err
}
defer cc.Close()
}
response, err := c.ExecuteFetchAsDba(ctx, &tabletmanagerdatapb.ExecuteFetchAsDbaRequest{
Query: query,
DbName: topoproto.TabletDbName(tablet),
MaxRows: uint64(maxRows),
DisableBinlogs: disableBinlogs,
ReloadSchema: reloadSchema,
})
if err != nil {
return nil, err
}
return response.Result, nil
} | go | func (client *Client) ExecuteFetchAsDba(ctx context.Context, tablet *topodatapb.Tablet, usePool bool, query []byte, maxRows int, disableBinlogs, reloadSchema bool) (*querypb.QueryResult, error) {
var c tabletmanagerservicepb.TabletManagerClient
var err error
if usePool {
c, err = client.dialPool(tablet)
if err != nil {
return nil, err
}
} else {
var cc *grpc.ClientConn
cc, c, err = client.dial(tablet)
if err != nil {
return nil, err
}
defer cc.Close()
}
response, err := c.ExecuteFetchAsDba(ctx, &tabletmanagerdatapb.ExecuteFetchAsDbaRequest{
Query: query,
DbName: topoproto.TabletDbName(tablet),
MaxRows: uint64(maxRows),
DisableBinlogs: disableBinlogs,
ReloadSchema: reloadSchema,
})
if err != nil {
return nil, err
}
return response.Result, nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"ExecuteFetchAsDba",
"(",
"ctx",
"context",
".",
"Context",
",",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
",",
"usePool",
"bool",
",",
"query",
"[",
"]",
"byte",
",",
"maxRows",
"int",
",",
"disableBinlogs",
",",
"reloadSchema",
"bool",
")",
"(",
"*",
"querypb",
".",
"QueryResult",
",",
"error",
")",
"{",
"var",
"c",
"tabletmanagerservicepb",
".",
"TabletManagerClient",
"\n",
"var",
"err",
"error",
"\n",
"if",
"usePool",
"{",
"c",
",",
"err",
"=",
"client",
".",
"dialPool",
"(",
"tablet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"var",
"cc",
"*",
"grpc",
".",
"ClientConn",
"\n",
"cc",
",",
"c",
",",
"err",
"=",
"client",
".",
"dial",
"(",
"tablet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"cc",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"response",
",",
"err",
":=",
"c",
".",
"ExecuteFetchAsDba",
"(",
"ctx",
",",
"&",
"tabletmanagerdatapb",
".",
"ExecuteFetchAsDbaRequest",
"{",
"Query",
":",
"query",
",",
"DbName",
":",
"topoproto",
".",
"TabletDbName",
"(",
"tablet",
")",
",",
"MaxRows",
":",
"uint64",
"(",
"maxRows",
")",
",",
"DisableBinlogs",
":",
"disableBinlogs",
",",
"ReloadSchema",
":",
"reloadSchema",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"response",
".",
"Result",
",",
"nil",
"\n",
"}"
] | // ExecuteFetchAsDba is part of the tmclient.TabletManagerClient interface. | [
"ExecuteFetchAsDba",
"is",
"part",
"of",
"the",
"tmclient",
".",
"TabletManagerClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/grpctmclient/client.go#L372-L400 | train |
vitessio/vitess | go/vt/vttablet/grpctmclient/client.go | MasterPosition | func (client *Client) MasterPosition(ctx context.Context, tablet *topodatapb.Tablet) (string, error) {
cc, c, err := client.dial(tablet)
if err != nil {
return "", err
}
defer cc.Close()
response, err := c.MasterPosition(ctx, &tabletmanagerdatapb.MasterPositionRequest{})
if err != nil {
return "", err
}
return response.Position, nil
} | go | func (client *Client) MasterPosition(ctx context.Context, tablet *topodatapb.Tablet) (string, error) {
cc, c, err := client.dial(tablet)
if err != nil {
return "", err
}
defer cc.Close()
response, err := c.MasterPosition(ctx, &tabletmanagerdatapb.MasterPositionRequest{})
if err != nil {
return "", err
}
return response.Position, nil
} | [
"func",
"(",
"client",
"*",
"Client",
")",
"MasterPosition",
"(",
"ctx",
"context",
".",
"Context",
",",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
")",
"(",
"string",
",",
"error",
")",
"{",
"cc",
",",
"c",
",",
"err",
":=",
"client",
".",
"dial",
"(",
"tablet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"cc",
".",
"Close",
"(",
")",
"\n",
"response",
",",
"err",
":=",
"c",
".",
"MasterPosition",
"(",
"ctx",
",",
"&",
"tabletmanagerdatapb",
".",
"MasterPositionRequest",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"response",
".",
"Position",
",",
"nil",
"\n",
"}"
] | // MasterPosition is part of the tmclient.TabletManagerClient interface. | [
"MasterPosition",
"is",
"part",
"of",
"the",
"tmclient",
".",
"TabletManagerClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/grpctmclient/client.go#L472-L483 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.