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/planbuilder/insert.go | swapBindVariables | func swapBindVariables(rows sqlparser.Values, colNum int, baseName string) (sqltypes.PlanValue, error) {
pv := sqltypes.PlanValue{}
for rowNum, row := range rows {
innerpv, err := sqlparser.NewPlanValue(row[colNum])
if err != nil {
return pv, fmt.Errorf("could not compute value for vindex or auto-inc column: %v", err)
}
pv.Values = append(pv.Values, innerpv)
row[colNum] = sqlparser.NewValArg([]byte(baseName + strconv.Itoa(rowNum)))
}
return pv, nil
} | go | func swapBindVariables(rows sqlparser.Values, colNum int, baseName string) (sqltypes.PlanValue, error) {
pv := sqltypes.PlanValue{}
for rowNum, row := range rows {
innerpv, err := sqlparser.NewPlanValue(row[colNum])
if err != nil {
return pv, fmt.Errorf("could not compute value for vindex or auto-inc column: %v", err)
}
pv.Values = append(pv.Values, innerpv)
row[colNum] = sqlparser.NewValArg([]byte(baseName + strconv.Itoa(rowNum)))
}
return pv, nil
} | [
"func",
"swapBindVariables",
"(",
"rows",
"sqlparser",
".",
"Values",
",",
"colNum",
"int",
",",
"baseName",
"string",
")",
"(",
"sqltypes",
".",
"PlanValue",
",",
"error",
")",
"{",
"pv",
":=",
"sqltypes",
".",
"PlanValue",
"{",
"}",
"\n",
"for",
"rowNum",
",",
"row",
":=",
"range",
"rows",
"{",
"innerpv",
",",
"err",
":=",
"sqlparser",
".",
"NewPlanValue",
"(",
"row",
"[",
"colNum",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"pv",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"pv",
".",
"Values",
"=",
"append",
"(",
"pv",
".",
"Values",
",",
"innerpv",
")",
"\n",
"row",
"[",
"colNum",
"]",
"=",
"sqlparser",
".",
"NewValArg",
"(",
"[",
"]",
"byte",
"(",
"baseName",
"+",
"strconv",
".",
"Itoa",
"(",
"rowNum",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"pv",
",",
"nil",
"\n",
"}"
] | // swapBindVariables swaps in bind variable names at the specified
// column position in the AST values and returns the converted values back.
// Bind variable names are generated using baseName. | [
"swapBindVariables",
"swaps",
"in",
"bind",
"variable",
"names",
"at",
"the",
"specified",
"column",
"position",
"in",
"the",
"AST",
"values",
"and",
"returns",
"the",
"converted",
"values",
"back",
".",
"Bind",
"variable",
"names",
"are",
"generated",
"using",
"baseName",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/insert.go#L209-L220 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/insert.go | findOrAddColumn | func findOrAddColumn(ins *sqlparser.Insert, col sqlparser.ColIdent) int {
for i, column := range ins.Columns {
if col.Equal(column) {
return i
}
}
ins.Columns = append(ins.Columns, col)
rows := ins.Rows.(sqlparser.Values)
for i := range rows {
rows[i] = append(rows[i], &sqlparser.NullVal{})
}
return len(ins.Columns) - 1
} | go | func findOrAddColumn(ins *sqlparser.Insert, col sqlparser.ColIdent) int {
for i, column := range ins.Columns {
if col.Equal(column) {
return i
}
}
ins.Columns = append(ins.Columns, col)
rows := ins.Rows.(sqlparser.Values)
for i := range rows {
rows[i] = append(rows[i], &sqlparser.NullVal{})
}
return len(ins.Columns) - 1
} | [
"func",
"findOrAddColumn",
"(",
"ins",
"*",
"sqlparser",
".",
"Insert",
",",
"col",
"sqlparser",
".",
"ColIdent",
")",
"int",
"{",
"for",
"i",
",",
"column",
":=",
"range",
"ins",
".",
"Columns",
"{",
"if",
"col",
".",
"Equal",
"(",
"column",
")",
"{",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"ins",
".",
"Columns",
"=",
"append",
"(",
"ins",
".",
"Columns",
",",
"col",
")",
"\n",
"rows",
":=",
"ins",
".",
"Rows",
".",
"(",
"sqlparser",
".",
"Values",
")",
"\n",
"for",
"i",
":=",
"range",
"rows",
"{",
"rows",
"[",
"i",
"]",
"=",
"append",
"(",
"rows",
"[",
"i",
"]",
",",
"&",
"sqlparser",
".",
"NullVal",
"{",
"}",
")",
"\n",
"}",
"\n",
"return",
"len",
"(",
"ins",
".",
"Columns",
")",
"-",
"1",
"\n",
"}"
] | // findOrAddColumn finds the position of a column in the insert. If it's
// absent it appends it to the with NULL values and returns that position. | [
"findOrAddColumn",
"finds",
"the",
"position",
"of",
"a",
"column",
"in",
"the",
"insert",
".",
"If",
"it",
"s",
"absent",
"it",
"appends",
"it",
"to",
"the",
"with",
"NULL",
"values",
"and",
"returns",
"that",
"position",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/insert.go#L224-L236 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/insert.go | isVindexChanging | func isVindexChanging(setClauses sqlparser.UpdateExprs, colVindexes []*vindexes.ColumnVindex) bool {
for _, assignment := range setClauses {
for _, vcol := range colVindexes {
for _, col := range vcol.Columns {
if col.Equal(assignment.Name.Name) {
valueExpr, isValuesFuncExpr := assignment.Expr.(*sqlparser.ValuesFuncExpr)
if !isValuesFuncExpr {
return true
}
// update on duplicate key is changing the vindex column, not supported.
if !valueExpr.Name.Name.Equal(assignment.Name.Name) {
return true
}
}
}
}
}
return false
} | go | func isVindexChanging(setClauses sqlparser.UpdateExprs, colVindexes []*vindexes.ColumnVindex) bool {
for _, assignment := range setClauses {
for _, vcol := range colVindexes {
for _, col := range vcol.Columns {
if col.Equal(assignment.Name.Name) {
valueExpr, isValuesFuncExpr := assignment.Expr.(*sqlparser.ValuesFuncExpr)
if !isValuesFuncExpr {
return true
}
// update on duplicate key is changing the vindex column, not supported.
if !valueExpr.Name.Name.Equal(assignment.Name.Name) {
return true
}
}
}
}
}
return false
} | [
"func",
"isVindexChanging",
"(",
"setClauses",
"sqlparser",
".",
"UpdateExprs",
",",
"colVindexes",
"[",
"]",
"*",
"vindexes",
".",
"ColumnVindex",
")",
"bool",
"{",
"for",
"_",
",",
"assignment",
":=",
"range",
"setClauses",
"{",
"for",
"_",
",",
"vcol",
":=",
"range",
"colVindexes",
"{",
"for",
"_",
",",
"col",
":=",
"range",
"vcol",
".",
"Columns",
"{",
"if",
"col",
".",
"Equal",
"(",
"assignment",
".",
"Name",
".",
"Name",
")",
"{",
"valueExpr",
",",
"isValuesFuncExpr",
":=",
"assignment",
".",
"Expr",
".",
"(",
"*",
"sqlparser",
".",
"ValuesFuncExpr",
")",
"\n",
"if",
"!",
"isValuesFuncExpr",
"{",
"return",
"true",
"\n",
"}",
"\n",
"// update on duplicate key is changing the vindex column, not supported.",
"if",
"!",
"valueExpr",
".",
"Name",
".",
"Name",
".",
"Equal",
"(",
"assignment",
".",
"Name",
".",
"Name",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isVindexChanging returns true if any of the update
// expressions modify a vindex column. | [
"isVindexChanging",
"returns",
"true",
"if",
"any",
"of",
"the",
"update",
"expressions",
"modify",
"a",
"vindex",
"column",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/insert.go#L240-L258 | train |
vitessio/vitess | go/vt/hook/hook.go | NewHook | func NewHook(name string, params []string) *Hook {
return &Hook{Name: name, Parameters: params}
} | go | func NewHook(name string, params []string) *Hook {
return &Hook{Name: name, Parameters: params}
} | [
"func",
"NewHook",
"(",
"name",
"string",
",",
"params",
"[",
"]",
"string",
")",
"*",
"Hook",
"{",
"return",
"&",
"Hook",
"{",
"Name",
":",
"name",
",",
"Parameters",
":",
"params",
"}",
"\n",
"}"
] | // NewHook returns a Hook object with the provided name and params. | [
"NewHook",
"returns",
"a",
"Hook",
"object",
"with",
"the",
"provided",
"name",
"and",
"params",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/hook/hook.go#L79-L81 | train |
vitessio/vitess | go/vt/hook/hook.go | NewHookWithEnv | func NewHookWithEnv(name string, params []string, env map[string]string) *Hook {
return &Hook{Name: name, Parameters: params, ExtraEnv: env}
} | go | func NewHookWithEnv(name string, params []string, env map[string]string) *Hook {
return &Hook{Name: name, Parameters: params, ExtraEnv: env}
} | [
"func",
"NewHookWithEnv",
"(",
"name",
"string",
",",
"params",
"[",
"]",
"string",
",",
"env",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"Hook",
"{",
"return",
"&",
"Hook",
"{",
"Name",
":",
"name",
",",
"Parameters",
":",
"params",
",",
"ExtraEnv",
":",
"env",
"}",
"\n",
"}"
] | // NewHookWithEnv returns a Hook object with the provided name, params and ExtraEnv. | [
"NewHookWithEnv",
"returns",
"a",
"Hook",
"object",
"with",
"the",
"provided",
"name",
"params",
"and",
"ExtraEnv",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/hook/hook.go#L89-L91 | train |
vitessio/vitess | go/vt/hook/hook.go | findHook | func (hook *Hook) findHook() (*exec.Cmd, int, error) {
// Check the hook path.
if strings.Contains(hook.Name, "/") {
return nil, HOOK_INVALID_NAME, fmt.Errorf("hook cannot contain '/'")
}
// Find our root.
root, err := vtenv.VtRoot()
if err != nil {
return nil, HOOK_VTROOT_ERROR, fmt.Errorf("cannot get VTROOT: %v", err)
}
// See if the hook exists.
vthook := path.Join(root, "vthook", hook.Name)
_, err = os.Stat(vthook)
if err != nil {
if os.IsNotExist(err) {
return nil, HOOK_DOES_NOT_EXIST, fmt.Errorf("missing hook %v", vthook)
}
return nil, HOOK_STAT_FAILED, fmt.Errorf("cannot stat hook %v: %v", vthook, err)
}
// Configure the command.
log.Infof("hook: executing hook: %v %v", vthook, strings.Join(hook.Parameters, " "))
cmd := exec.Command(vthook, hook.Parameters...)
if len(hook.ExtraEnv) > 0 {
cmd.Env = os.Environ()
for key, value := range hook.ExtraEnv {
cmd.Env = append(cmd.Env, key+"="+value)
}
}
return cmd, HOOK_SUCCESS, nil
} | go | func (hook *Hook) findHook() (*exec.Cmd, int, error) {
// Check the hook path.
if strings.Contains(hook.Name, "/") {
return nil, HOOK_INVALID_NAME, fmt.Errorf("hook cannot contain '/'")
}
// Find our root.
root, err := vtenv.VtRoot()
if err != nil {
return nil, HOOK_VTROOT_ERROR, fmt.Errorf("cannot get VTROOT: %v", err)
}
// See if the hook exists.
vthook := path.Join(root, "vthook", hook.Name)
_, err = os.Stat(vthook)
if err != nil {
if os.IsNotExist(err) {
return nil, HOOK_DOES_NOT_EXIST, fmt.Errorf("missing hook %v", vthook)
}
return nil, HOOK_STAT_FAILED, fmt.Errorf("cannot stat hook %v: %v", vthook, err)
}
// Configure the command.
log.Infof("hook: executing hook: %v %v", vthook, strings.Join(hook.Parameters, " "))
cmd := exec.Command(vthook, hook.Parameters...)
if len(hook.ExtraEnv) > 0 {
cmd.Env = os.Environ()
for key, value := range hook.ExtraEnv {
cmd.Env = append(cmd.Env, key+"="+value)
}
}
return cmd, HOOK_SUCCESS, nil
} | [
"func",
"(",
"hook",
"*",
"Hook",
")",
"findHook",
"(",
")",
"(",
"*",
"exec",
".",
"Cmd",
",",
"int",
",",
"error",
")",
"{",
"// Check the hook path.",
"if",
"strings",
".",
"Contains",
"(",
"hook",
".",
"Name",
",",
"\"",
"\"",
")",
"{",
"return",
"nil",
",",
"HOOK_INVALID_NAME",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Find our root.",
"root",
",",
"err",
":=",
"vtenv",
".",
"VtRoot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"HOOK_VTROOT_ERROR",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// See if the hook exists.",
"vthook",
":=",
"path",
".",
"Join",
"(",
"root",
",",
"\"",
"\"",
",",
"hook",
".",
"Name",
")",
"\n",
"_",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"vthook",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"HOOK_DOES_NOT_EXIST",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"vthook",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"HOOK_STAT_FAILED",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"vthook",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Configure the command.",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"vthook",
",",
"strings",
".",
"Join",
"(",
"hook",
".",
"Parameters",
",",
"\"",
"\"",
")",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"vthook",
",",
"hook",
".",
"Parameters",
"...",
")",
"\n",
"if",
"len",
"(",
"hook",
".",
"ExtraEnv",
")",
">",
"0",
"{",
"cmd",
".",
"Env",
"=",
"os",
".",
"Environ",
"(",
")",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"hook",
".",
"ExtraEnv",
"{",
"cmd",
".",
"Env",
"=",
"append",
"(",
"cmd",
".",
"Env",
",",
"key",
"+",
"\"",
"\"",
"+",
"value",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"cmd",
",",
"HOOK_SUCCESS",
",",
"nil",
"\n",
"}"
] | // findHook trie to locate the hook, and returns the exec.Cmd for it. | [
"findHook",
"trie",
"to",
"locate",
"the",
"hook",
"and",
"returns",
"the",
"exec",
".",
"Cmd",
"for",
"it",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/hook/hook.go#L94-L128 | train |
vitessio/vitess | go/vt/hook/hook.go | Execute | func (hook *Hook) Execute() (result *HookResult) {
result = &HookResult{}
// Find the hook.
cmd, status, err := hook.findHook()
if err != nil {
result.ExitStatus = status
result.Stderr = err.Error() + "\n"
return result
}
// Run it.
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
result.Stdout = stdout.String()
result.Stderr = stderr.String()
if err == nil {
result.ExitStatus = HOOK_SUCCESS
} else {
if cmd.ProcessState != nil && cmd.ProcessState.Sys() != nil {
result.ExitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
} else {
result.ExitStatus = HOOK_CANNOT_GET_EXIT_STATUS
}
result.Stderr += "ERROR: " + err.Error() + "\n"
}
log.Infof("hook: result is %v", result.String())
return result
} | go | func (hook *Hook) Execute() (result *HookResult) {
result = &HookResult{}
// Find the hook.
cmd, status, err := hook.findHook()
if err != nil {
result.ExitStatus = status
result.Stderr = err.Error() + "\n"
return result
}
// Run it.
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
result.Stdout = stdout.String()
result.Stderr = stderr.String()
if err == nil {
result.ExitStatus = HOOK_SUCCESS
} else {
if cmd.ProcessState != nil && cmd.ProcessState.Sys() != nil {
result.ExitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
} else {
result.ExitStatus = HOOK_CANNOT_GET_EXIT_STATUS
}
result.Stderr += "ERROR: " + err.Error() + "\n"
}
log.Infof("hook: result is %v", result.String())
return result
} | [
"func",
"(",
"hook",
"*",
"Hook",
")",
"Execute",
"(",
")",
"(",
"result",
"*",
"HookResult",
")",
"{",
"result",
"=",
"&",
"HookResult",
"{",
"}",
"\n\n",
"// Find the hook.",
"cmd",
",",
"status",
",",
"err",
":=",
"hook",
".",
"findHook",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"result",
".",
"ExitStatus",
"=",
"status",
"\n",
"result",
".",
"Stderr",
"=",
"err",
".",
"Error",
"(",
")",
"+",
"\"",
"\\n",
"\"",
"\n",
"return",
"result",
"\n",
"}",
"\n\n",
"// Run it.",
"var",
"stdout",
",",
"stderr",
"bytes",
".",
"Buffer",
"\n",
"cmd",
".",
"Stdout",
"=",
"&",
"stdout",
"\n",
"cmd",
".",
"Stderr",
"=",
"&",
"stderr",
"\n",
"err",
"=",
"cmd",
".",
"Run",
"(",
")",
"\n",
"result",
".",
"Stdout",
"=",
"stdout",
".",
"String",
"(",
")",
"\n",
"result",
".",
"Stderr",
"=",
"stderr",
".",
"String",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"result",
".",
"ExitStatus",
"=",
"HOOK_SUCCESS",
"\n",
"}",
"else",
"{",
"if",
"cmd",
".",
"ProcessState",
"!=",
"nil",
"&&",
"cmd",
".",
"ProcessState",
".",
"Sys",
"(",
")",
"!=",
"nil",
"{",
"result",
".",
"ExitStatus",
"=",
"cmd",
".",
"ProcessState",
".",
"Sys",
"(",
")",
".",
"(",
"syscall",
".",
"WaitStatus",
")",
".",
"ExitStatus",
"(",
")",
"\n",
"}",
"else",
"{",
"result",
".",
"ExitStatus",
"=",
"HOOK_CANNOT_GET_EXIT_STATUS",
"\n",
"}",
"\n",
"result",
".",
"Stderr",
"+=",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"result",
".",
"String",
"(",
")",
")",
"\n\n",
"return",
"result",
"\n",
"}"
] | // Execute tries to execute the Hook and returns a HookResult. | [
"Execute",
"tries",
"to",
"execute",
"the",
"Hook",
"and",
"returns",
"a",
"HookResult",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/hook/hook.go#L131-L163 | train |
vitessio/vitess | go/vt/hook/hook.go | ExecuteOptional | func (hook *Hook) ExecuteOptional() error {
hr := hook.Execute()
switch hr.ExitStatus {
case HOOK_DOES_NOT_EXIST:
log.Infof("%v hook doesn't exist", hook.Name)
case HOOK_VTROOT_ERROR:
log.Infof("VTROOT not set, so %v hook doesn't exist", hook.Name)
case HOOK_SUCCESS:
// nothing to do here
default:
return fmt.Errorf("%v hook failed(%v): %v", hook.Name, hr.ExitStatus, hr.Stderr)
}
return nil
} | go | func (hook *Hook) ExecuteOptional() error {
hr := hook.Execute()
switch hr.ExitStatus {
case HOOK_DOES_NOT_EXIST:
log.Infof("%v hook doesn't exist", hook.Name)
case HOOK_VTROOT_ERROR:
log.Infof("VTROOT not set, so %v hook doesn't exist", hook.Name)
case HOOK_SUCCESS:
// nothing to do here
default:
return fmt.Errorf("%v hook failed(%v): %v", hook.Name, hr.ExitStatus, hr.Stderr)
}
return nil
} | [
"func",
"(",
"hook",
"*",
"Hook",
")",
"ExecuteOptional",
"(",
")",
"error",
"{",
"hr",
":=",
"hook",
".",
"Execute",
"(",
")",
"\n",
"switch",
"hr",
".",
"ExitStatus",
"{",
"case",
"HOOK_DOES_NOT_EXIST",
":",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"hook",
".",
"Name",
")",
"\n",
"case",
"HOOK_VTROOT_ERROR",
":",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"hook",
".",
"Name",
")",
"\n",
"case",
"HOOK_SUCCESS",
":",
"// nothing to do here",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hook",
".",
"Name",
",",
"hr",
".",
"ExitStatus",
",",
"hr",
".",
"Stderr",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ExecuteOptional executes an optional hook, logs if it doesn't
// exist, and returns a printable error. | [
"ExecuteOptional",
"executes",
"an",
"optional",
"hook",
"logs",
"if",
"it",
"doesn",
"t",
"exist",
"and",
"returns",
"a",
"printable",
"error",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/hook/hook.go#L167-L180 | train |
vitessio/vitess | go/vt/hook/hook.go | String | func (hr *HookResult) String() string {
result := "result: "
switch hr.ExitStatus {
case HOOK_SUCCESS:
result += "HOOK_SUCCESS"
case HOOK_DOES_NOT_EXIST:
result += "HOOK_DOES_NOT_EXIST"
case HOOK_STAT_FAILED:
result += "HOOK_STAT_FAILED"
case HOOK_CANNOT_GET_EXIT_STATUS:
result += "HOOK_CANNOT_GET_EXIT_STATUS"
case HOOK_INVALID_NAME:
result += "HOOK_INVALID_NAME"
case HOOK_VTROOT_ERROR:
result += "HOOK_VTROOT_ERROR"
default:
result += fmt.Sprintf("exit(%v)", hr.ExitStatus)
}
if hr.Stdout != "" {
result += "\nstdout:\n" + hr.Stdout
}
if hr.Stderr != "" {
result += "\nstderr:\n" + hr.Stderr
}
return result
} | go | func (hr *HookResult) String() string {
result := "result: "
switch hr.ExitStatus {
case HOOK_SUCCESS:
result += "HOOK_SUCCESS"
case HOOK_DOES_NOT_EXIST:
result += "HOOK_DOES_NOT_EXIST"
case HOOK_STAT_FAILED:
result += "HOOK_STAT_FAILED"
case HOOK_CANNOT_GET_EXIT_STATUS:
result += "HOOK_CANNOT_GET_EXIT_STATUS"
case HOOK_INVALID_NAME:
result += "HOOK_INVALID_NAME"
case HOOK_VTROOT_ERROR:
result += "HOOK_VTROOT_ERROR"
default:
result += fmt.Sprintf("exit(%v)", hr.ExitStatus)
}
if hr.Stdout != "" {
result += "\nstdout:\n" + hr.Stdout
}
if hr.Stderr != "" {
result += "\nstderr:\n" + hr.Stderr
}
return result
} | [
"func",
"(",
"hr",
"*",
"HookResult",
")",
"String",
"(",
")",
"string",
"{",
"result",
":=",
"\"",
"\"",
"\n",
"switch",
"hr",
".",
"ExitStatus",
"{",
"case",
"HOOK_SUCCESS",
":",
"result",
"+=",
"\"",
"\"",
"\n",
"case",
"HOOK_DOES_NOT_EXIST",
":",
"result",
"+=",
"\"",
"\"",
"\n",
"case",
"HOOK_STAT_FAILED",
":",
"result",
"+=",
"\"",
"\"",
"\n",
"case",
"HOOK_CANNOT_GET_EXIT_STATUS",
":",
"result",
"+=",
"\"",
"\"",
"\n",
"case",
"HOOK_INVALID_NAME",
":",
"result",
"+=",
"\"",
"\"",
"\n",
"case",
"HOOK_VTROOT_ERROR",
":",
"result",
"+=",
"\"",
"\"",
"\n",
"default",
":",
"result",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"hr",
".",
"ExitStatus",
")",
"\n",
"}",
"\n",
"if",
"hr",
".",
"Stdout",
"!=",
"\"",
"\"",
"{",
"result",
"+=",
"\"",
"\\n",
"\\n",
"\"",
"+",
"hr",
".",
"Stdout",
"\n",
"}",
"\n",
"if",
"hr",
".",
"Stderr",
"!=",
"\"",
"\"",
"{",
"result",
"+=",
"\"",
"\\n",
"\\n",
"\"",
"+",
"hr",
".",
"Stderr",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // String returns a printable version of the HookResult | [
"String",
"returns",
"a",
"printable",
"version",
"of",
"the",
"HookResult"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/hook/hook.go#L261-L286 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/state_change.go | loadBlacklistRules | func (agent *ActionAgent) loadBlacklistRules(tablet *topodatapb.Tablet, blacklistedTables []string) (err error) {
blacklistRules := rules.New()
if len(blacklistedTables) > 0 {
// tables, first resolve wildcards
tables, err := mysqlctl.ResolveTables(agent.MysqlDaemon, topoproto.TabletDbName(tablet), blacklistedTables)
if err != nil {
return err
}
// Verify that at least one table matches the wildcards, so
// that we don't add a rule to blacklist all tables
if len(tables) > 0 {
log.Infof("Blacklisting tables %v", strings.Join(tables, ", "))
qr := rules.NewQueryRule("enforce blacklisted tables", "blacklisted_table", rules.QRFailRetry)
for _, t := range tables {
qr.AddTableCond(t)
}
blacklistRules.Add(qr)
}
}
loadRuleErr := agent.QueryServiceControl.SetQueryRules(blacklistQueryRules, blacklistRules)
if loadRuleErr != nil {
log.Warningf("Fail to load query rule set %s: %s", blacklistQueryRules, loadRuleErr)
}
return nil
} | go | func (agent *ActionAgent) loadBlacklistRules(tablet *topodatapb.Tablet, blacklistedTables []string) (err error) {
blacklistRules := rules.New()
if len(blacklistedTables) > 0 {
// tables, first resolve wildcards
tables, err := mysqlctl.ResolveTables(agent.MysqlDaemon, topoproto.TabletDbName(tablet), blacklistedTables)
if err != nil {
return err
}
// Verify that at least one table matches the wildcards, so
// that we don't add a rule to blacklist all tables
if len(tables) > 0 {
log.Infof("Blacklisting tables %v", strings.Join(tables, ", "))
qr := rules.NewQueryRule("enforce blacklisted tables", "blacklisted_table", rules.QRFailRetry)
for _, t := range tables {
qr.AddTableCond(t)
}
blacklistRules.Add(qr)
}
}
loadRuleErr := agent.QueryServiceControl.SetQueryRules(blacklistQueryRules, blacklistRules)
if loadRuleErr != nil {
log.Warningf("Fail to load query rule set %s: %s", blacklistQueryRules, loadRuleErr)
}
return nil
} | [
"func",
"(",
"agent",
"*",
"ActionAgent",
")",
"loadBlacklistRules",
"(",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
",",
"blacklistedTables",
"[",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"blacklistRules",
":=",
"rules",
".",
"New",
"(",
")",
"\n",
"if",
"len",
"(",
"blacklistedTables",
")",
">",
"0",
"{",
"// tables, first resolve wildcards",
"tables",
",",
"err",
":=",
"mysqlctl",
".",
"ResolveTables",
"(",
"agent",
".",
"MysqlDaemon",
",",
"topoproto",
".",
"TabletDbName",
"(",
"tablet",
")",
",",
"blacklistedTables",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Verify that at least one table matches the wildcards, so",
"// that we don't add a rule to blacklist all tables",
"if",
"len",
"(",
"tables",
")",
">",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"tables",
",",
"\"",
"\"",
")",
")",
"\n",
"qr",
":=",
"rules",
".",
"NewQueryRule",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"rules",
".",
"QRFailRetry",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tables",
"{",
"qr",
".",
"AddTableCond",
"(",
"t",
")",
"\n",
"}",
"\n",
"blacklistRules",
".",
"Add",
"(",
"qr",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"loadRuleErr",
":=",
"agent",
".",
"QueryServiceControl",
".",
"SetQueryRules",
"(",
"blacklistQueryRules",
",",
"blacklistRules",
")",
"\n",
"if",
"loadRuleErr",
"!=",
"nil",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"blacklistQueryRules",
",",
"loadRuleErr",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // loadBlacklistRules loads and builds the blacklist query rules | [
"loadBlacklistRules",
"loads",
"and",
"builds",
"the",
"blacklist",
"query",
"rules"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/state_change.go#L60-L86 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/state_change.go | lameduck | func (agent *ActionAgent) lameduck(reason string) {
log.Infof("Agent is entering lameduck, reason: %v", reason)
agent.QueryServiceControl.EnterLameduck()
agent.broadcastHealth()
time.Sleep(*gracePeriod)
log.Infof("Agent is leaving lameduck")
} | go | func (agent *ActionAgent) lameduck(reason string) {
log.Infof("Agent is entering lameduck, reason: %v", reason)
agent.QueryServiceControl.EnterLameduck()
agent.broadcastHealth()
time.Sleep(*gracePeriod)
log.Infof("Agent is leaving lameduck")
} | [
"func",
"(",
"agent",
"*",
"ActionAgent",
")",
"lameduck",
"(",
"reason",
"string",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"reason",
")",
"\n",
"agent",
".",
"QueryServiceControl",
".",
"EnterLameduck",
"(",
")",
"\n",
"agent",
".",
"broadcastHealth",
"(",
")",
"\n",
"time",
".",
"Sleep",
"(",
"*",
"gracePeriod",
")",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // lameduck changes the QueryServiceControl state to lameduck,
// brodcasts the new health, then sleep for grace period, to give time
// to clients to get the new status. | [
"lameduck",
"changes",
"the",
"QueryServiceControl",
"state",
"to",
"lameduck",
"brodcasts",
"the",
"new",
"health",
"then",
"sleep",
"for",
"grace",
"period",
"to",
"give",
"time",
"to",
"clients",
"to",
"get",
"the",
"new",
"status",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/state_change.go#L91-L97 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/state_change.go | refreshTablet | func (agent *ActionAgent) refreshTablet(ctx context.Context, reason string) error {
agent.checkLock()
log.Infof("Executing post-action state refresh: %v", reason)
span, ctx := trace.NewSpan(ctx, "ActionAgent.refreshTablet")
span.Annotate("reason", reason)
defer span.Finish()
// Actions should have side effects on the tablet, so reload the data.
ti, err := agent.TopoServer.GetTablet(ctx, agent.TabletAlias)
if err != nil {
log.Warningf("Failed rereading tablet after %v - services may be inconsistent: %v", reason, err)
return vterrors.Wrapf(err, "refreshTablet failed rereading tablet after %v", reason)
}
tablet := ti.Tablet
// Also refresh the MySQL port, to be sure it's correct.
// Note if this run doesn't succeed, the healthcheck go routine
// will try again.
agent.gotMysqlPort = false
agent.waitingForMysql = false
if updatedTablet := agent.checkTabletMysqlPort(ctx, tablet); updatedTablet != nil {
tablet = updatedTablet
}
agent.updateState(ctx, tablet, reason)
log.Infof("Done with post-action state refresh")
return nil
} | go | func (agent *ActionAgent) refreshTablet(ctx context.Context, reason string) error {
agent.checkLock()
log.Infof("Executing post-action state refresh: %v", reason)
span, ctx := trace.NewSpan(ctx, "ActionAgent.refreshTablet")
span.Annotate("reason", reason)
defer span.Finish()
// Actions should have side effects on the tablet, so reload the data.
ti, err := agent.TopoServer.GetTablet(ctx, agent.TabletAlias)
if err != nil {
log.Warningf("Failed rereading tablet after %v - services may be inconsistent: %v", reason, err)
return vterrors.Wrapf(err, "refreshTablet failed rereading tablet after %v", reason)
}
tablet := ti.Tablet
// Also refresh the MySQL port, to be sure it's correct.
// Note if this run doesn't succeed, the healthcheck go routine
// will try again.
agent.gotMysqlPort = false
agent.waitingForMysql = false
if updatedTablet := agent.checkTabletMysqlPort(ctx, tablet); updatedTablet != nil {
tablet = updatedTablet
}
agent.updateState(ctx, tablet, reason)
log.Infof("Done with post-action state refresh")
return nil
} | [
"func",
"(",
"agent",
"*",
"ActionAgent",
")",
"refreshTablet",
"(",
"ctx",
"context",
".",
"Context",
",",
"reason",
"string",
")",
"error",
"{",
"agent",
".",
"checkLock",
"(",
")",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"reason",
")",
"\n\n",
"span",
",",
"ctx",
":=",
"trace",
".",
"NewSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"span",
".",
"Annotate",
"(",
"\"",
"\"",
",",
"reason",
")",
"\n",
"defer",
"span",
".",
"Finish",
"(",
")",
"\n\n",
"// Actions should have side effects on the tablet, so reload the data.",
"ti",
",",
"err",
":=",
"agent",
".",
"TopoServer",
".",
"GetTablet",
"(",
"ctx",
",",
"agent",
".",
"TabletAlias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"reason",
",",
"err",
")",
"\n",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"reason",
")",
"\n",
"}",
"\n",
"tablet",
":=",
"ti",
".",
"Tablet",
"\n\n",
"// Also refresh the MySQL port, to be sure it's correct.",
"// Note if this run doesn't succeed, the healthcheck go routine",
"// will try again.",
"agent",
".",
"gotMysqlPort",
"=",
"false",
"\n",
"agent",
".",
"waitingForMysql",
"=",
"false",
"\n",
"if",
"updatedTablet",
":=",
"agent",
".",
"checkTabletMysqlPort",
"(",
"ctx",
",",
"tablet",
")",
";",
"updatedTablet",
"!=",
"nil",
"{",
"tablet",
"=",
"updatedTablet",
"\n",
"}",
"\n\n",
"agent",
".",
"updateState",
"(",
"ctx",
",",
"tablet",
",",
"reason",
")",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // refreshTablet needs to be run after an action may have changed the current
// state of the tablet. | [
"refreshTablet",
"needs",
"to",
"be",
"run",
"after",
"an",
"action",
"may",
"have",
"changed",
"the",
"current",
"state",
"of",
"the",
"tablet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/state_change.go#L132-L160 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/state_change.go | updateState | func (agent *ActionAgent) updateState(ctx context.Context, newTablet *topodatapb.Tablet, reason string) {
oldTablet := agent.Tablet()
if oldTablet == nil {
oldTablet = &topodatapb.Tablet{}
}
log.Infof("Running tablet callback because: %v", reason)
agent.changeCallback(ctx, oldTablet, newTablet)
agent.setTablet(newTablet)
event.Dispatch(&events.StateChange{
OldTablet: *oldTablet,
NewTablet: *newTablet,
Reason: reason,
})
} | go | func (agent *ActionAgent) updateState(ctx context.Context, newTablet *topodatapb.Tablet, reason string) {
oldTablet := agent.Tablet()
if oldTablet == nil {
oldTablet = &topodatapb.Tablet{}
}
log.Infof("Running tablet callback because: %v", reason)
agent.changeCallback(ctx, oldTablet, newTablet)
agent.setTablet(newTablet)
event.Dispatch(&events.StateChange{
OldTablet: *oldTablet,
NewTablet: *newTablet,
Reason: reason,
})
} | [
"func",
"(",
"agent",
"*",
"ActionAgent",
")",
"updateState",
"(",
"ctx",
"context",
".",
"Context",
",",
"newTablet",
"*",
"topodatapb",
".",
"Tablet",
",",
"reason",
"string",
")",
"{",
"oldTablet",
":=",
"agent",
".",
"Tablet",
"(",
")",
"\n",
"if",
"oldTablet",
"==",
"nil",
"{",
"oldTablet",
"=",
"&",
"topodatapb",
".",
"Tablet",
"{",
"}",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"reason",
")",
"\n",
"agent",
".",
"changeCallback",
"(",
"ctx",
",",
"oldTablet",
",",
"newTablet",
")",
"\n",
"agent",
".",
"setTablet",
"(",
"newTablet",
")",
"\n",
"event",
".",
"Dispatch",
"(",
"&",
"events",
".",
"StateChange",
"{",
"OldTablet",
":",
"*",
"oldTablet",
",",
"NewTablet",
":",
"*",
"newTablet",
",",
"Reason",
":",
"reason",
",",
"}",
")",
"\n",
"}"
] | // updateState will use the provided tablet record as the new tablet state,
// the current tablet as a base, run changeCallback, and dispatch the event. | [
"updateState",
"will",
"use",
"the",
"provided",
"tablet",
"record",
"as",
"the",
"new",
"tablet",
"state",
"the",
"current",
"tablet",
"as",
"a",
"base",
"run",
"changeCallback",
"and",
"dispatch",
"the",
"event",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/state_change.go#L164-L177 | train |
vitessio/vitess | go/sqltypes/result.go | Repair | func (result *Result) Repair(fields []*querypb.Field) {
// Usage of j is intentional.
for j, f := range fields {
for _, r := range result.Rows {
if r[j].typ != Null {
r[j].typ = f.Type
}
}
}
} | go | func (result *Result) Repair(fields []*querypb.Field) {
// Usage of j is intentional.
for j, f := range fields {
for _, r := range result.Rows {
if r[j].typ != Null {
r[j].typ = f.Type
}
}
}
} | [
"func",
"(",
"result",
"*",
"Result",
")",
"Repair",
"(",
"fields",
"[",
"]",
"*",
"querypb",
".",
"Field",
")",
"{",
"// Usage of j is intentional.",
"for",
"j",
",",
"f",
":=",
"range",
"fields",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"result",
".",
"Rows",
"{",
"if",
"r",
"[",
"j",
"]",
".",
"typ",
"!=",
"Null",
"{",
"r",
"[",
"j",
"]",
".",
"typ",
"=",
"f",
".",
"Type",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Repair fixes the type info in the rows
// to conform to the supplied field types. | [
"Repair",
"fixes",
"the",
"type",
"info",
"in",
"the",
"rows",
"to",
"conform",
"to",
"the",
"supplied",
"field",
"types",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L45-L54 | train |
vitessio/vitess | go/sqltypes/result.go | Copy | func (result *Result) Copy() *Result {
out := &Result{
InsertID: result.InsertID,
RowsAffected: result.RowsAffected,
}
if result.Fields != nil {
fieldsp := make([]*querypb.Field, len(result.Fields))
fields := make([]querypb.Field, len(result.Fields))
for i, f := range result.Fields {
fields[i] = *f
fieldsp[i] = &fields[i]
}
out.Fields = fieldsp
}
if result.Rows != nil {
out.Rows = make([][]Value, 0, len(result.Rows))
for _, r := range result.Rows {
out.Rows = append(out.Rows, CopyRow(r))
}
}
if result.Extras != nil {
out.Extras = &querypb.ResultExtras{
Fresher: result.Extras.Fresher,
}
if result.Extras.EventToken != nil {
out.Extras.EventToken = &querypb.EventToken{
Timestamp: result.Extras.EventToken.Timestamp,
Shard: result.Extras.EventToken.Shard,
Position: result.Extras.EventToken.Position,
}
}
}
return out
} | go | func (result *Result) Copy() *Result {
out := &Result{
InsertID: result.InsertID,
RowsAffected: result.RowsAffected,
}
if result.Fields != nil {
fieldsp := make([]*querypb.Field, len(result.Fields))
fields := make([]querypb.Field, len(result.Fields))
for i, f := range result.Fields {
fields[i] = *f
fieldsp[i] = &fields[i]
}
out.Fields = fieldsp
}
if result.Rows != nil {
out.Rows = make([][]Value, 0, len(result.Rows))
for _, r := range result.Rows {
out.Rows = append(out.Rows, CopyRow(r))
}
}
if result.Extras != nil {
out.Extras = &querypb.ResultExtras{
Fresher: result.Extras.Fresher,
}
if result.Extras.EventToken != nil {
out.Extras.EventToken = &querypb.EventToken{
Timestamp: result.Extras.EventToken.Timestamp,
Shard: result.Extras.EventToken.Shard,
Position: result.Extras.EventToken.Position,
}
}
}
return out
} | [
"func",
"(",
"result",
"*",
"Result",
")",
"Copy",
"(",
")",
"*",
"Result",
"{",
"out",
":=",
"&",
"Result",
"{",
"InsertID",
":",
"result",
".",
"InsertID",
",",
"RowsAffected",
":",
"result",
".",
"RowsAffected",
",",
"}",
"\n",
"if",
"result",
".",
"Fields",
"!=",
"nil",
"{",
"fieldsp",
":=",
"make",
"(",
"[",
"]",
"*",
"querypb",
".",
"Field",
",",
"len",
"(",
"result",
".",
"Fields",
")",
")",
"\n",
"fields",
":=",
"make",
"(",
"[",
"]",
"querypb",
".",
"Field",
",",
"len",
"(",
"result",
".",
"Fields",
")",
")",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"result",
".",
"Fields",
"{",
"fields",
"[",
"i",
"]",
"=",
"*",
"f",
"\n",
"fieldsp",
"[",
"i",
"]",
"=",
"&",
"fields",
"[",
"i",
"]",
"\n",
"}",
"\n",
"out",
".",
"Fields",
"=",
"fieldsp",
"\n",
"}",
"\n",
"if",
"result",
".",
"Rows",
"!=",
"nil",
"{",
"out",
".",
"Rows",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"Value",
",",
"0",
",",
"len",
"(",
"result",
".",
"Rows",
")",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"result",
".",
"Rows",
"{",
"out",
".",
"Rows",
"=",
"append",
"(",
"out",
".",
"Rows",
",",
"CopyRow",
"(",
"r",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"result",
".",
"Extras",
"!=",
"nil",
"{",
"out",
".",
"Extras",
"=",
"&",
"querypb",
".",
"ResultExtras",
"{",
"Fresher",
":",
"result",
".",
"Extras",
".",
"Fresher",
",",
"}",
"\n",
"if",
"result",
".",
"Extras",
".",
"EventToken",
"!=",
"nil",
"{",
"out",
".",
"Extras",
".",
"EventToken",
"=",
"&",
"querypb",
".",
"EventToken",
"{",
"Timestamp",
":",
"result",
".",
"Extras",
".",
"EventToken",
".",
"Timestamp",
",",
"Shard",
":",
"result",
".",
"Extras",
".",
"EventToken",
".",
"Shard",
",",
"Position",
":",
"result",
".",
"Extras",
".",
"EventToken",
".",
"Position",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // Copy creates a deep copy of Result. | [
"Copy",
"creates",
"a",
"deep",
"copy",
"of",
"Result",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L57-L90 | train |
vitessio/vitess | go/sqltypes/result.go | CopyRow | func CopyRow(r []Value) []Value {
// The raw bytes of the values are supposed to be treated as read-only.
// So, there's no need to copy them.
out := make([]Value, len(r))
copy(out, r)
return out
} | go | func CopyRow(r []Value) []Value {
// The raw bytes of the values are supposed to be treated as read-only.
// So, there's no need to copy them.
out := make([]Value, len(r))
copy(out, r)
return out
} | [
"func",
"CopyRow",
"(",
"r",
"[",
"]",
"Value",
")",
"[",
"]",
"Value",
"{",
"// The raw bytes of the values are supposed to be treated as read-only.",
"// So, there's no need to copy them.",
"out",
":=",
"make",
"(",
"[",
"]",
"Value",
",",
"len",
"(",
"r",
")",
")",
"\n",
"copy",
"(",
"out",
",",
"r",
")",
"\n",
"return",
"out",
"\n",
"}"
] | // CopyRow makes a copy of the row. | [
"CopyRow",
"makes",
"a",
"copy",
"of",
"the",
"row",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L93-L99 | train |
vitessio/vitess | go/sqltypes/result.go | Truncate | func (result *Result) Truncate(l int) *Result {
if l == 0 {
return result
}
out := &Result{
InsertID: result.InsertID,
RowsAffected: result.RowsAffected,
}
if result.Fields != nil {
out.Fields = result.Fields[:l]
}
if result.Rows != nil {
out.Rows = make([][]Value, 0, len(result.Rows))
for _, r := range result.Rows {
out.Rows = append(out.Rows, r[:l])
}
}
if result.Extras != nil {
out.Extras = &querypb.ResultExtras{
Fresher: result.Extras.Fresher,
}
if result.Extras.EventToken != nil {
out.Extras.EventToken = &querypb.EventToken{
Timestamp: result.Extras.EventToken.Timestamp,
Shard: result.Extras.EventToken.Shard,
Position: result.Extras.EventToken.Position,
}
}
}
return out
} | go | func (result *Result) Truncate(l int) *Result {
if l == 0 {
return result
}
out := &Result{
InsertID: result.InsertID,
RowsAffected: result.RowsAffected,
}
if result.Fields != nil {
out.Fields = result.Fields[:l]
}
if result.Rows != nil {
out.Rows = make([][]Value, 0, len(result.Rows))
for _, r := range result.Rows {
out.Rows = append(out.Rows, r[:l])
}
}
if result.Extras != nil {
out.Extras = &querypb.ResultExtras{
Fresher: result.Extras.Fresher,
}
if result.Extras.EventToken != nil {
out.Extras.EventToken = &querypb.EventToken{
Timestamp: result.Extras.EventToken.Timestamp,
Shard: result.Extras.EventToken.Shard,
Position: result.Extras.EventToken.Position,
}
}
}
return out
} | [
"func",
"(",
"result",
"*",
"Result",
")",
"Truncate",
"(",
"l",
"int",
")",
"*",
"Result",
"{",
"if",
"l",
"==",
"0",
"{",
"return",
"result",
"\n",
"}",
"\n\n",
"out",
":=",
"&",
"Result",
"{",
"InsertID",
":",
"result",
".",
"InsertID",
",",
"RowsAffected",
":",
"result",
".",
"RowsAffected",
",",
"}",
"\n",
"if",
"result",
".",
"Fields",
"!=",
"nil",
"{",
"out",
".",
"Fields",
"=",
"result",
".",
"Fields",
"[",
":",
"l",
"]",
"\n",
"}",
"\n",
"if",
"result",
".",
"Rows",
"!=",
"nil",
"{",
"out",
".",
"Rows",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"Value",
",",
"0",
",",
"len",
"(",
"result",
".",
"Rows",
")",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"result",
".",
"Rows",
"{",
"out",
".",
"Rows",
"=",
"append",
"(",
"out",
".",
"Rows",
",",
"r",
"[",
":",
"l",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"result",
".",
"Extras",
"!=",
"nil",
"{",
"out",
".",
"Extras",
"=",
"&",
"querypb",
".",
"ResultExtras",
"{",
"Fresher",
":",
"result",
".",
"Extras",
".",
"Fresher",
",",
"}",
"\n",
"if",
"result",
".",
"Extras",
".",
"EventToken",
"!=",
"nil",
"{",
"out",
".",
"Extras",
".",
"EventToken",
"=",
"&",
"querypb",
".",
"EventToken",
"{",
"Timestamp",
":",
"result",
".",
"Extras",
".",
"EventToken",
".",
"Timestamp",
",",
"Shard",
":",
"result",
".",
"Extras",
".",
"EventToken",
".",
"Shard",
",",
"Position",
":",
"result",
".",
"Extras",
".",
"EventToken",
".",
"Position",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // Truncate returns a new Result with all the rows truncated
// to the specified number of columns. | [
"Truncate",
"returns",
"a",
"new",
"Result",
"with",
"all",
"the",
"rows",
"truncated",
"to",
"the",
"specified",
"number",
"of",
"columns",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L103-L134 | train |
vitessio/vitess | go/sqltypes/result.go | FieldsEqual | func FieldsEqual(f1, f2 []*querypb.Field) bool {
if len(f1) != len(f2) {
return false
}
for i, f := range f1 {
if !proto.Equal(f, f2[i]) {
return false
}
}
return true
} | go | func FieldsEqual(f1, f2 []*querypb.Field) bool {
if len(f1) != len(f2) {
return false
}
for i, f := range f1 {
if !proto.Equal(f, f2[i]) {
return false
}
}
return true
} | [
"func",
"FieldsEqual",
"(",
"f1",
",",
"f2",
"[",
"]",
"*",
"querypb",
".",
"Field",
")",
"bool",
"{",
"if",
"len",
"(",
"f1",
")",
"!=",
"len",
"(",
"f2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"f1",
"{",
"if",
"!",
"proto",
".",
"Equal",
"(",
"f",
",",
"f2",
"[",
"i",
"]",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // FieldsEqual compares two arrays of fields.
// reflect.DeepEqual shouldn't be used because of the protos. | [
"FieldsEqual",
"compares",
"two",
"arrays",
"of",
"fields",
".",
"reflect",
".",
"DeepEqual",
"shouldn",
"t",
"be",
"used",
"because",
"of",
"the",
"protos",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L138-L148 | train |
vitessio/vitess | go/sqltypes/result.go | Equal | func (result *Result) Equal(other *Result) bool {
// Check for nil cases
if result == nil {
return other == nil
}
if other == nil {
return false
}
// Compare Fields, RowsAffected, InsertID, Rows, Extras.
return FieldsEqual(result.Fields, other.Fields) &&
result.RowsAffected == other.RowsAffected &&
result.InsertID == other.InsertID &&
reflect.DeepEqual(result.Rows, other.Rows) &&
proto.Equal(result.Extras, other.Extras)
} | go | func (result *Result) Equal(other *Result) bool {
// Check for nil cases
if result == nil {
return other == nil
}
if other == nil {
return false
}
// Compare Fields, RowsAffected, InsertID, Rows, Extras.
return FieldsEqual(result.Fields, other.Fields) &&
result.RowsAffected == other.RowsAffected &&
result.InsertID == other.InsertID &&
reflect.DeepEqual(result.Rows, other.Rows) &&
proto.Equal(result.Extras, other.Extras)
} | [
"func",
"(",
"result",
"*",
"Result",
")",
"Equal",
"(",
"other",
"*",
"Result",
")",
"bool",
"{",
"// Check for nil cases",
"if",
"result",
"==",
"nil",
"{",
"return",
"other",
"==",
"nil",
"\n",
"}",
"\n",
"if",
"other",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Compare Fields, RowsAffected, InsertID, Rows, Extras.",
"return",
"FieldsEqual",
"(",
"result",
".",
"Fields",
",",
"other",
".",
"Fields",
")",
"&&",
"result",
".",
"RowsAffected",
"==",
"other",
".",
"RowsAffected",
"&&",
"result",
".",
"InsertID",
"==",
"other",
".",
"InsertID",
"&&",
"reflect",
".",
"DeepEqual",
"(",
"result",
".",
"Rows",
",",
"other",
".",
"Rows",
")",
"&&",
"proto",
".",
"Equal",
"(",
"result",
".",
"Extras",
",",
"other",
".",
"Extras",
")",
"\n",
"}"
] | // Equal compares the Result with another one.
// reflect.DeepEqual shouldn't be used because of the protos. | [
"Equal",
"compares",
"the",
"Result",
"with",
"another",
"one",
".",
"reflect",
".",
"DeepEqual",
"shouldn",
"t",
"be",
"used",
"because",
"of",
"the",
"protos",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L152-L167 | train |
vitessio/vitess | go/sqltypes/result.go | ResultsEqual | func ResultsEqual(r1, r2 []Result) bool {
if len(r1) != len(r2) {
return false
}
for i, r := range r1 {
if !r.Equal(&r2[i]) {
return false
}
}
return true
} | go | func ResultsEqual(r1, r2 []Result) bool {
if len(r1) != len(r2) {
return false
}
for i, r := range r1 {
if !r.Equal(&r2[i]) {
return false
}
}
return true
} | [
"func",
"ResultsEqual",
"(",
"r1",
",",
"r2",
"[",
"]",
"Result",
")",
"bool",
"{",
"if",
"len",
"(",
"r1",
")",
"!=",
"len",
"(",
"r2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"r",
":=",
"range",
"r1",
"{",
"if",
"!",
"r",
".",
"Equal",
"(",
"&",
"r2",
"[",
"i",
"]",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // ResultsEqual compares two arrays of Result.
// reflect.DeepEqual shouldn't be used because of the protos. | [
"ResultsEqual",
"compares",
"two",
"arrays",
"of",
"Result",
".",
"reflect",
".",
"DeepEqual",
"shouldn",
"t",
"be",
"used",
"because",
"of",
"the",
"protos",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L171-L181 | train |
vitessio/vitess | go/sqltypes/result.go | IncludeFieldsOrDefault | func IncludeFieldsOrDefault(options *querypb.ExecuteOptions) querypb.ExecuteOptions_IncludedFields {
if options == nil {
return querypb.ExecuteOptions_TYPE_AND_NAME
}
return options.IncludedFields
} | go | func IncludeFieldsOrDefault(options *querypb.ExecuteOptions) querypb.ExecuteOptions_IncludedFields {
if options == nil {
return querypb.ExecuteOptions_TYPE_AND_NAME
}
return options.IncludedFields
} | [
"func",
"IncludeFieldsOrDefault",
"(",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
")",
"querypb",
".",
"ExecuteOptions_IncludedFields",
"{",
"if",
"options",
"==",
"nil",
"{",
"return",
"querypb",
".",
"ExecuteOptions_TYPE_AND_NAME",
"\n",
"}",
"\n\n",
"return",
"options",
".",
"IncludedFields",
"\n",
"}"
] | // IncludeFieldsOrDefault normalizes the passed Execution Options.
// It returns the default value if options is nil. | [
"IncludeFieldsOrDefault",
"normalizes",
"the",
"passed",
"Execution",
"Options",
".",
"It",
"returns",
"the",
"default",
"value",
"if",
"options",
"is",
"nil",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L202-L208 | train |
vitessio/vitess | go/sqltypes/result.go | StripMetadata | func (result *Result) StripMetadata(incl querypb.ExecuteOptions_IncludedFields) *Result {
if incl == querypb.ExecuteOptions_ALL || len(result.Fields) == 0 {
return result
}
r := *result
r.Fields = make([]*querypb.Field, len(result.Fields))
newFieldsArray := make([]querypb.Field, len(result.Fields))
for i, f := range result.Fields {
r.Fields[i] = &newFieldsArray[i]
newFieldsArray[i].Type = f.Type
if incl == querypb.ExecuteOptions_TYPE_AND_NAME {
newFieldsArray[i].Name = f.Name
}
}
return &r
} | go | func (result *Result) StripMetadata(incl querypb.ExecuteOptions_IncludedFields) *Result {
if incl == querypb.ExecuteOptions_ALL || len(result.Fields) == 0 {
return result
}
r := *result
r.Fields = make([]*querypb.Field, len(result.Fields))
newFieldsArray := make([]querypb.Field, len(result.Fields))
for i, f := range result.Fields {
r.Fields[i] = &newFieldsArray[i]
newFieldsArray[i].Type = f.Type
if incl == querypb.ExecuteOptions_TYPE_AND_NAME {
newFieldsArray[i].Name = f.Name
}
}
return &r
} | [
"func",
"(",
"result",
"*",
"Result",
")",
"StripMetadata",
"(",
"incl",
"querypb",
".",
"ExecuteOptions_IncludedFields",
")",
"*",
"Result",
"{",
"if",
"incl",
"==",
"querypb",
".",
"ExecuteOptions_ALL",
"||",
"len",
"(",
"result",
".",
"Fields",
")",
"==",
"0",
"{",
"return",
"result",
"\n",
"}",
"\n",
"r",
":=",
"*",
"result",
"\n",
"r",
".",
"Fields",
"=",
"make",
"(",
"[",
"]",
"*",
"querypb",
".",
"Field",
",",
"len",
"(",
"result",
".",
"Fields",
")",
")",
"\n",
"newFieldsArray",
":=",
"make",
"(",
"[",
"]",
"querypb",
".",
"Field",
",",
"len",
"(",
"result",
".",
"Fields",
")",
")",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"result",
".",
"Fields",
"{",
"r",
".",
"Fields",
"[",
"i",
"]",
"=",
"&",
"newFieldsArray",
"[",
"i",
"]",
"\n",
"newFieldsArray",
"[",
"i",
"]",
".",
"Type",
"=",
"f",
".",
"Type",
"\n",
"if",
"incl",
"==",
"querypb",
".",
"ExecuteOptions_TYPE_AND_NAME",
"{",
"newFieldsArray",
"[",
"i",
"]",
".",
"Name",
"=",
"f",
".",
"Name",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"r",
"\n",
"}"
] | // StripMetadata will return a new Result that has the same Rows,
// but the Field objects will have their non-critical metadata emptied. Note we don't
// proto.Copy each Field for performance reasons, but we only copy the
// individual fields. | [
"StripMetadata",
"will",
"return",
"a",
"new",
"Result",
"that",
"has",
"the",
"same",
"Rows",
"but",
"the",
"Field",
"objects",
"will",
"have",
"their",
"non",
"-",
"critical",
"metadata",
"emptied",
".",
"Note",
"we",
"don",
"t",
"proto",
".",
"Copy",
"each",
"Field",
"for",
"performance",
"reasons",
"but",
"we",
"only",
"copy",
"the",
"individual",
"fields",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L214-L229 | train |
vitessio/vitess | go/sqltypes/result.go | AppendResult | func (result *Result) AppendResult(src *Result) {
if src.RowsAffected == 0 && len(src.Fields) == 0 {
return
}
if result.Fields == nil {
result.Fields = src.Fields
}
result.RowsAffected += src.RowsAffected
if src.InsertID != 0 {
result.InsertID = src.InsertID
}
if len(result.Rows) == 0 {
// we haven't gotten any result yet, just save the new extras.
result.Extras = src.Extras
} else {
// Merge the EventTokens / Fresher flags within Extras.
if src.Extras == nil {
// We didn't get any from innerq. Have to clear any
// we'd have gotten already.
if result.Extras != nil {
result.Extras.EventToken = nil
result.Extras.Fresher = false
}
} else {
// We may have gotten an EventToken from
// innerqr. If we also got one earlier, merge
// it. If we didn't get one earlier, we
// discard the new one.
if result.Extras != nil {
// Note if any of the two is nil, we get nil.
result.Extras.EventToken = EventTokenMinimum(result.Extras.EventToken, src.Extras.EventToken)
result.Extras.Fresher = result.Extras.Fresher && src.Extras.Fresher
}
}
}
result.Rows = append(result.Rows, src.Rows...)
} | go | func (result *Result) AppendResult(src *Result) {
if src.RowsAffected == 0 && len(src.Fields) == 0 {
return
}
if result.Fields == nil {
result.Fields = src.Fields
}
result.RowsAffected += src.RowsAffected
if src.InsertID != 0 {
result.InsertID = src.InsertID
}
if len(result.Rows) == 0 {
// we haven't gotten any result yet, just save the new extras.
result.Extras = src.Extras
} else {
// Merge the EventTokens / Fresher flags within Extras.
if src.Extras == nil {
// We didn't get any from innerq. Have to clear any
// we'd have gotten already.
if result.Extras != nil {
result.Extras.EventToken = nil
result.Extras.Fresher = false
}
} else {
// We may have gotten an EventToken from
// innerqr. If we also got one earlier, merge
// it. If we didn't get one earlier, we
// discard the new one.
if result.Extras != nil {
// Note if any of the two is nil, we get nil.
result.Extras.EventToken = EventTokenMinimum(result.Extras.EventToken, src.Extras.EventToken)
result.Extras.Fresher = result.Extras.Fresher && src.Extras.Fresher
}
}
}
result.Rows = append(result.Rows, src.Rows...)
} | [
"func",
"(",
"result",
"*",
"Result",
")",
"AppendResult",
"(",
"src",
"*",
"Result",
")",
"{",
"if",
"src",
".",
"RowsAffected",
"==",
"0",
"&&",
"len",
"(",
"src",
".",
"Fields",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"result",
".",
"Fields",
"==",
"nil",
"{",
"result",
".",
"Fields",
"=",
"src",
".",
"Fields",
"\n",
"}",
"\n",
"result",
".",
"RowsAffected",
"+=",
"src",
".",
"RowsAffected",
"\n",
"if",
"src",
".",
"InsertID",
"!=",
"0",
"{",
"result",
".",
"InsertID",
"=",
"src",
".",
"InsertID",
"\n",
"}",
"\n",
"if",
"len",
"(",
"result",
".",
"Rows",
")",
"==",
"0",
"{",
"// we haven't gotten any result yet, just save the new extras.",
"result",
".",
"Extras",
"=",
"src",
".",
"Extras",
"\n",
"}",
"else",
"{",
"// Merge the EventTokens / Fresher flags within Extras.",
"if",
"src",
".",
"Extras",
"==",
"nil",
"{",
"// We didn't get any from innerq. Have to clear any",
"// we'd have gotten already.",
"if",
"result",
".",
"Extras",
"!=",
"nil",
"{",
"result",
".",
"Extras",
".",
"EventToken",
"=",
"nil",
"\n",
"result",
".",
"Extras",
".",
"Fresher",
"=",
"false",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// We may have gotten an EventToken from",
"// innerqr. If we also got one earlier, merge",
"// it. If we didn't get one earlier, we",
"// discard the new one.",
"if",
"result",
".",
"Extras",
"!=",
"nil",
"{",
"// Note if any of the two is nil, we get nil.",
"result",
".",
"Extras",
".",
"EventToken",
"=",
"EventTokenMinimum",
"(",
"result",
".",
"Extras",
".",
"EventToken",
",",
"src",
".",
"Extras",
".",
"EventToken",
")",
"\n\n",
"result",
".",
"Extras",
".",
"Fresher",
"=",
"result",
".",
"Extras",
".",
"Fresher",
"&&",
"src",
".",
"Extras",
".",
"Fresher",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"result",
".",
"Rows",
"=",
"append",
"(",
"result",
".",
"Rows",
",",
"src",
".",
"Rows",
"...",
")",
"\n",
"}"
] | // AppendResult will combine the Results Objects of one result
// to another result.Note currently it doesn't handle cases like
// if two results have different fields.We will enhance this function. | [
"AppendResult",
"will",
"combine",
"the",
"Results",
"Objects",
"of",
"one",
"result",
"to",
"another",
"result",
".",
"Note",
"currently",
"it",
"doesn",
"t",
"handle",
"cases",
"like",
"if",
"two",
"results",
"have",
"different",
"fields",
".",
"We",
"will",
"enhance",
"this",
"function",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/result.go#L234-L271 | train |
vitessio/vitess | go/vt/topo/replication.go | NewShardReplicationInfo | func NewShardReplicationInfo(sr *topodatapb.ShardReplication, cell, keyspace, shard string) *ShardReplicationInfo {
return &ShardReplicationInfo{
ShardReplication: sr,
cell: cell,
keyspace: keyspace,
shard: shard,
}
} | go | func NewShardReplicationInfo(sr *topodatapb.ShardReplication, cell, keyspace, shard string) *ShardReplicationInfo {
return &ShardReplicationInfo{
ShardReplication: sr,
cell: cell,
keyspace: keyspace,
shard: shard,
}
} | [
"func",
"NewShardReplicationInfo",
"(",
"sr",
"*",
"topodatapb",
".",
"ShardReplication",
",",
"cell",
",",
"keyspace",
",",
"shard",
"string",
")",
"*",
"ShardReplicationInfo",
"{",
"return",
"&",
"ShardReplicationInfo",
"{",
"ShardReplication",
":",
"sr",
",",
"cell",
":",
"cell",
",",
"keyspace",
":",
"keyspace",
",",
"shard",
":",
"shard",
",",
"}",
"\n",
"}"
] | // NewShardReplicationInfo is for topo.Server implementations to
// create the structure | [
"NewShardReplicationInfo",
"is",
"for",
"topo",
".",
"Server",
"implementations",
"to",
"create",
"the",
"structure"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/replication.go#L44-L51 | train |
vitessio/vitess | go/vt/topo/replication.go | GetShardReplicationNode | func (sri *ShardReplicationInfo) GetShardReplicationNode(tabletAlias *topodatapb.TabletAlias) (*topodatapb.ShardReplication_Node, error) {
for _, rl := range sri.Nodes {
if proto.Equal(rl.TabletAlias, tabletAlias) {
return rl, nil
}
}
return nil, NewError(NoNode, tabletAlias.String())
} | go | func (sri *ShardReplicationInfo) GetShardReplicationNode(tabletAlias *topodatapb.TabletAlias) (*topodatapb.ShardReplication_Node, error) {
for _, rl := range sri.Nodes {
if proto.Equal(rl.TabletAlias, tabletAlias) {
return rl, nil
}
}
return nil, NewError(NoNode, tabletAlias.String())
} | [
"func",
"(",
"sri",
"*",
"ShardReplicationInfo",
")",
"GetShardReplicationNode",
"(",
"tabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
")",
"(",
"*",
"topodatapb",
".",
"ShardReplication_Node",
",",
"error",
")",
"{",
"for",
"_",
",",
"rl",
":=",
"range",
"sri",
".",
"Nodes",
"{",
"if",
"proto",
".",
"Equal",
"(",
"rl",
".",
"TabletAlias",
",",
"tabletAlias",
")",
"{",
"return",
"rl",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"NewError",
"(",
"NoNode",
",",
"tabletAlias",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // GetShardReplicationNode finds a node for a given tablet. | [
"GetShardReplicationNode",
"finds",
"a",
"node",
"for",
"a",
"given",
"tablet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/replication.go#L69-L76 | train |
vitessio/vitess | go/vt/topo/replication.go | RemoveShardReplicationRecord | func RemoveShardReplicationRecord(ctx context.Context, ts *Server, cell, keyspace, shard string, tabletAlias *topodatapb.TabletAlias) error {
err := ts.UpdateShardReplicationFields(ctx, cell, keyspace, shard, func(sr *topodatapb.ShardReplication) error {
nodes := make([]*topodatapb.ShardReplication_Node, 0, len(sr.Nodes))
for _, node := range sr.Nodes {
if !proto.Equal(node.TabletAlias, tabletAlias) {
nodes = append(nodes, node)
}
}
sr.Nodes = nodes
return nil
})
return err
} | go | func RemoveShardReplicationRecord(ctx context.Context, ts *Server, cell, keyspace, shard string, tabletAlias *topodatapb.TabletAlias) error {
err := ts.UpdateShardReplicationFields(ctx, cell, keyspace, shard, func(sr *topodatapb.ShardReplication) error {
nodes := make([]*topodatapb.ShardReplication_Node, 0, len(sr.Nodes))
for _, node := range sr.Nodes {
if !proto.Equal(node.TabletAlias, tabletAlias) {
nodes = append(nodes, node)
}
}
sr.Nodes = nodes
return nil
})
return err
} | [
"func",
"RemoveShardReplicationRecord",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"Server",
",",
"cell",
",",
"keyspace",
",",
"shard",
"string",
",",
"tabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
")",
"error",
"{",
"err",
":=",
"ts",
".",
"UpdateShardReplicationFields",
"(",
"ctx",
",",
"cell",
",",
"keyspace",
",",
"shard",
",",
"func",
"(",
"sr",
"*",
"topodatapb",
".",
"ShardReplication",
")",
"error",
"{",
"nodes",
":=",
"make",
"(",
"[",
"]",
"*",
"topodatapb",
".",
"ShardReplication_Node",
",",
"0",
",",
"len",
"(",
"sr",
".",
"Nodes",
")",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"sr",
".",
"Nodes",
"{",
"if",
"!",
"proto",
".",
"Equal",
"(",
"node",
".",
"TabletAlias",
",",
"tabletAlias",
")",
"{",
"nodes",
"=",
"append",
"(",
"nodes",
",",
"node",
")",
"\n",
"}",
"\n",
"}",
"\n",
"sr",
".",
"Nodes",
"=",
"nodes",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // RemoveShardReplicationRecord is a low level function to remove an
// entry from the ShardReplication object. | [
"RemoveShardReplicationRecord",
"is",
"a",
"low",
"level",
"function",
"to",
"remove",
"an",
"entry",
"from",
"the",
"ShardReplication",
"object",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/replication.go#L118-L130 | train |
vitessio/vitess | go/vt/topo/replication.go | FixShardReplication | func FixShardReplication(ctx context.Context, ts *Server, logger logutil.Logger, cell, keyspace, shard string) error {
sri, err := ts.GetShardReplication(ctx, cell, keyspace, shard)
if err != nil {
return err
}
for _, node := range sri.Nodes {
ti, err := ts.GetTablet(ctx, node.TabletAlias)
if IsErrType(err, NoNode) {
logger.Warningf("Tablet %v is in the replication graph, but does not exist, removing it", node.TabletAlias)
return RemoveShardReplicationRecord(ctx, ts, cell, keyspace, shard, node.TabletAlias)
}
if err != nil {
// unknown error, we probably don't want to continue
return err
}
if ti.Keyspace != keyspace || ti.Shard != shard || ti.Alias.Cell != cell {
logger.Warningf("Tablet '%v' is in the replication graph, but has wrong keyspace/shard/cell, removing it", ti.Tablet)
return RemoveShardReplicationRecord(ctx, ts, cell, keyspace, shard, node.TabletAlias)
}
logger.Infof("Keeping tablet %v in the replication graph", node.TabletAlias)
}
logger.Infof("All entries in replication graph are valid")
return nil
} | go | func FixShardReplication(ctx context.Context, ts *Server, logger logutil.Logger, cell, keyspace, shard string) error {
sri, err := ts.GetShardReplication(ctx, cell, keyspace, shard)
if err != nil {
return err
}
for _, node := range sri.Nodes {
ti, err := ts.GetTablet(ctx, node.TabletAlias)
if IsErrType(err, NoNode) {
logger.Warningf("Tablet %v is in the replication graph, but does not exist, removing it", node.TabletAlias)
return RemoveShardReplicationRecord(ctx, ts, cell, keyspace, shard, node.TabletAlias)
}
if err != nil {
// unknown error, we probably don't want to continue
return err
}
if ti.Keyspace != keyspace || ti.Shard != shard || ti.Alias.Cell != cell {
logger.Warningf("Tablet '%v' is in the replication graph, but has wrong keyspace/shard/cell, removing it", ti.Tablet)
return RemoveShardReplicationRecord(ctx, ts, cell, keyspace, shard, node.TabletAlias)
}
logger.Infof("Keeping tablet %v in the replication graph", node.TabletAlias)
}
logger.Infof("All entries in replication graph are valid")
return nil
} | [
"func",
"FixShardReplication",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"Server",
",",
"logger",
"logutil",
".",
"Logger",
",",
"cell",
",",
"keyspace",
",",
"shard",
"string",
")",
"error",
"{",
"sri",
",",
"err",
":=",
"ts",
".",
"GetShardReplication",
"(",
"ctx",
",",
"cell",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"node",
":=",
"range",
"sri",
".",
"Nodes",
"{",
"ti",
",",
"err",
":=",
"ts",
".",
"GetTablet",
"(",
"ctx",
",",
"node",
".",
"TabletAlias",
")",
"\n",
"if",
"IsErrType",
"(",
"err",
",",
"NoNode",
")",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"node",
".",
"TabletAlias",
")",
"\n",
"return",
"RemoveShardReplicationRecord",
"(",
"ctx",
",",
"ts",
",",
"cell",
",",
"keyspace",
",",
"shard",
",",
"node",
".",
"TabletAlias",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// unknown error, we probably don't want to continue",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"ti",
".",
"Keyspace",
"!=",
"keyspace",
"||",
"ti",
".",
"Shard",
"!=",
"shard",
"||",
"ti",
".",
"Alias",
".",
"Cell",
"!=",
"cell",
"{",
"logger",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"ti",
".",
"Tablet",
")",
"\n",
"return",
"RemoveShardReplicationRecord",
"(",
"ctx",
",",
"ts",
",",
"cell",
",",
"keyspace",
",",
"shard",
",",
"node",
".",
"TabletAlias",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"node",
".",
"TabletAlias",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // FixShardReplication will fix the first problem it encounters within
// a ShardReplication object. | [
"FixShardReplication",
"will",
"fix",
"the",
"first",
"problem",
"it",
"encounters",
"within",
"a",
"ShardReplication",
"object",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/replication.go#L134-L161 | train |
vitessio/vitess | go/vt/topo/replication.go | UpdateShardReplicationFields | func (ts *Server) UpdateShardReplicationFields(ctx context.Context, cell, keyspace, shard string, update func(*topodatapb.ShardReplication) error) error {
nodePath := path.Join(KeyspacesPath, keyspace, ShardsPath, shard, ShardReplicationFile)
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return err
}
for {
data, version, err := conn.Get(ctx, nodePath)
sr := &topodatapb.ShardReplication{}
switch {
case IsErrType(err, NoNode):
// Empty node, version is nil
case err == nil:
// Use any data we got.
if err = proto.Unmarshal(data, sr); err != nil {
return vterrors.Wrap(err, "bad ShardReplication data")
}
default:
return err
}
err = update(sr)
switch {
case IsErrType(err, NoUpdateNeeded):
return nil
case err == nil:
// keep going
default:
return err
}
// marshall and save
data, err = proto.Marshal(sr)
if err != nil {
return err
}
if version == nil {
// We have to create, and we catch NodeExists.
_, err = conn.Create(ctx, nodePath, data)
if IsErrType(err, NodeExists) {
// Node was created by another process, try
// again.
continue
}
return err
}
// We have to update, and we catch ErrBadVersion.
_, err = conn.Update(ctx, nodePath, data, version)
if IsErrType(err, BadVersion) {
// Node was updated by another process, try again.
continue
}
return err
}
} | go | func (ts *Server) UpdateShardReplicationFields(ctx context.Context, cell, keyspace, shard string, update func(*topodatapb.ShardReplication) error) error {
nodePath := path.Join(KeyspacesPath, keyspace, ShardsPath, shard, ShardReplicationFile)
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return err
}
for {
data, version, err := conn.Get(ctx, nodePath)
sr := &topodatapb.ShardReplication{}
switch {
case IsErrType(err, NoNode):
// Empty node, version is nil
case err == nil:
// Use any data we got.
if err = proto.Unmarshal(data, sr); err != nil {
return vterrors.Wrap(err, "bad ShardReplication data")
}
default:
return err
}
err = update(sr)
switch {
case IsErrType(err, NoUpdateNeeded):
return nil
case err == nil:
// keep going
default:
return err
}
// marshall and save
data, err = proto.Marshal(sr)
if err != nil {
return err
}
if version == nil {
// We have to create, and we catch NodeExists.
_, err = conn.Create(ctx, nodePath, data)
if IsErrType(err, NodeExists) {
// Node was created by another process, try
// again.
continue
}
return err
}
// We have to update, and we catch ErrBadVersion.
_, err = conn.Update(ctx, nodePath, data, version)
if IsErrType(err, BadVersion) {
// Node was updated by another process, try again.
continue
}
return err
}
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"UpdateShardReplicationFields",
"(",
"ctx",
"context",
".",
"Context",
",",
"cell",
",",
"keyspace",
",",
"shard",
"string",
",",
"update",
"func",
"(",
"*",
"topodatapb",
".",
"ShardReplication",
")",
"error",
")",
"error",
"{",
"nodePath",
":=",
"path",
".",
"Join",
"(",
"KeyspacesPath",
",",
"keyspace",
",",
"ShardsPath",
",",
"shard",
",",
"ShardReplicationFile",
")",
"\n\n",
"conn",
",",
"err",
":=",
"ts",
".",
"ConnForCell",
"(",
"ctx",
",",
"cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"{",
"data",
",",
"version",
",",
"err",
":=",
"conn",
".",
"Get",
"(",
"ctx",
",",
"nodePath",
")",
"\n",
"sr",
":=",
"&",
"topodatapb",
".",
"ShardReplication",
"{",
"}",
"\n",
"switch",
"{",
"case",
"IsErrType",
"(",
"err",
",",
"NoNode",
")",
":",
"// Empty node, version is nil",
"case",
"err",
"==",
"nil",
":",
"// Use any data we got.",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"sr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"update",
"(",
"sr",
")",
"\n",
"switch",
"{",
"case",
"IsErrType",
"(",
"err",
",",
"NoUpdateNeeded",
")",
":",
"return",
"nil",
"\n",
"case",
"err",
"==",
"nil",
":",
"// keep going",
"default",
":",
"return",
"err",
"\n",
"}",
"\n\n",
"// marshall and save",
"data",
",",
"err",
"=",
"proto",
".",
"Marshal",
"(",
"sr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"version",
"==",
"nil",
"{",
"// We have to create, and we catch NodeExists.",
"_",
",",
"err",
"=",
"conn",
".",
"Create",
"(",
"ctx",
",",
"nodePath",
",",
"data",
")",
"\n",
"if",
"IsErrType",
"(",
"err",
",",
"NodeExists",
")",
"{",
"// Node was created by another process, try",
"// again.",
"continue",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// We have to update, and we catch ErrBadVersion.",
"_",
",",
"err",
"=",
"conn",
".",
"Update",
"(",
"ctx",
",",
"nodePath",
",",
"data",
",",
"version",
")",
"\n",
"if",
"IsErrType",
"(",
"err",
",",
"BadVersion",
")",
"{",
"// Node was updated by another process, try again.",
"continue",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}"
] | // UpdateShardReplicationFields updates the fields inside a topo.ShardReplication object. | [
"UpdateShardReplicationFields",
"updates",
"the",
"fields",
"inside",
"a",
"topo",
".",
"ShardReplication",
"object",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/replication.go#L164-L221 | train |
vitessio/vitess | go/vt/topo/replication.go | GetShardReplication | func (ts *Server) GetShardReplication(ctx context.Context, cell, keyspace, shard string) (*ShardReplicationInfo, error) {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return nil, err
}
nodePath := path.Join(KeyspacesPath, keyspace, ShardsPath, shard, ShardReplicationFile)
data, _, err := conn.Get(ctx, nodePath)
if err != nil {
return nil, err
}
sr := &topodatapb.ShardReplication{}
if err = proto.Unmarshal(data, sr); err != nil {
return nil, vterrors.Wrap(err, "bad ShardReplication data")
}
return NewShardReplicationInfo(sr, cell, keyspace, shard), nil
} | go | func (ts *Server) GetShardReplication(ctx context.Context, cell, keyspace, shard string) (*ShardReplicationInfo, error) {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return nil, err
}
nodePath := path.Join(KeyspacesPath, keyspace, ShardsPath, shard, ShardReplicationFile)
data, _, err := conn.Get(ctx, nodePath)
if err != nil {
return nil, err
}
sr := &topodatapb.ShardReplication{}
if err = proto.Unmarshal(data, sr); err != nil {
return nil, vterrors.Wrap(err, "bad ShardReplication data")
}
return NewShardReplicationInfo(sr, cell, keyspace, shard), nil
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"GetShardReplication",
"(",
"ctx",
"context",
".",
"Context",
",",
"cell",
",",
"keyspace",
",",
"shard",
"string",
")",
"(",
"*",
"ShardReplicationInfo",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"ts",
".",
"ConnForCell",
"(",
"ctx",
",",
"cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"nodePath",
":=",
"path",
".",
"Join",
"(",
"KeyspacesPath",
",",
"keyspace",
",",
"ShardsPath",
",",
"shard",
",",
"ShardReplicationFile",
")",
"\n",
"data",
",",
"_",
",",
"err",
":=",
"conn",
".",
"Get",
"(",
"ctx",
",",
"nodePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"sr",
":=",
"&",
"topodatapb",
".",
"ShardReplication",
"{",
"}",
"\n",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"sr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"NewShardReplicationInfo",
"(",
"sr",
",",
"cell",
",",
"keyspace",
",",
"shard",
")",
",",
"nil",
"\n",
"}"
] | // GetShardReplication returns the ShardReplicationInfo object. | [
"GetShardReplication",
"returns",
"the",
"ShardReplicationInfo",
"object",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/replication.go#L224-L242 | train |
vitessio/vitess | go/vt/topo/replication.go | DeleteShardReplication | func (ts *Server) DeleteShardReplication(ctx context.Context, cell, keyspace, shard string) error {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return err
}
nodePath := path.Join(KeyspacesPath, keyspace, ShardsPath, shard, ShardReplicationFile)
return conn.Delete(ctx, nodePath, nil)
} | go | func (ts *Server) DeleteShardReplication(ctx context.Context, cell, keyspace, shard string) error {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return err
}
nodePath := path.Join(KeyspacesPath, keyspace, ShardsPath, shard, ShardReplicationFile)
return conn.Delete(ctx, nodePath, nil)
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"DeleteShardReplication",
"(",
"ctx",
"context",
".",
"Context",
",",
"cell",
",",
"keyspace",
",",
"shard",
"string",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"ts",
".",
"ConnForCell",
"(",
"ctx",
",",
"cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"nodePath",
":=",
"path",
".",
"Join",
"(",
"KeyspacesPath",
",",
"keyspace",
",",
"ShardsPath",
",",
"shard",
",",
"ShardReplicationFile",
")",
"\n",
"return",
"conn",
".",
"Delete",
"(",
"ctx",
",",
"nodePath",
",",
"nil",
")",
"\n",
"}"
] | // DeleteShardReplication deletes a ShardReplication object. | [
"DeleteShardReplication",
"deletes",
"a",
"ShardReplication",
"object",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/replication.go#L245-L253 | train |
vitessio/vitess | go/vt/topo/workflow.go | CreateWorkflow | func (ts *Server) CreateWorkflow(ctx context.Context, w *workflowpb.Workflow) (*WorkflowInfo, error) {
// Pack the content.
contents, err := proto.Marshal(w)
if err != nil {
return nil, err
}
// Save it.
filePath := pathForWorkflow(w.Uuid)
version, err := ts.globalCell.Create(ctx, filePath, contents)
if err != nil {
return nil, err
}
return &WorkflowInfo{
version: version,
Workflow: w,
}, nil
} | go | func (ts *Server) CreateWorkflow(ctx context.Context, w *workflowpb.Workflow) (*WorkflowInfo, error) {
// Pack the content.
contents, err := proto.Marshal(w)
if err != nil {
return nil, err
}
// Save it.
filePath := pathForWorkflow(w.Uuid)
version, err := ts.globalCell.Create(ctx, filePath, contents)
if err != nil {
return nil, err
}
return &WorkflowInfo{
version: version,
Workflow: w,
}, nil
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"CreateWorkflow",
"(",
"ctx",
"context",
".",
"Context",
",",
"w",
"*",
"workflowpb",
".",
"Workflow",
")",
"(",
"*",
"WorkflowInfo",
",",
"error",
")",
"{",
"// Pack the content.",
"contents",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"w",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Save it.",
"filePath",
":=",
"pathForWorkflow",
"(",
"w",
".",
"Uuid",
")",
"\n",
"version",
",",
"err",
":=",
"ts",
".",
"globalCell",
".",
"Create",
"(",
"ctx",
",",
"filePath",
",",
"contents",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"WorkflowInfo",
"{",
"version",
":",
"version",
",",
"Workflow",
":",
"w",
",",
"}",
",",
"nil",
"\n",
"}"
] | // CreateWorkflow creates the given workflow, and returns the initial
// WorkflowInfo. | [
"CreateWorkflow",
"creates",
"the",
"given",
"workflow",
"and",
"returns",
"the",
"initial",
"WorkflowInfo",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/workflow.go#L62-L79 | train |
vitessio/vitess | go/vt/topo/workflow.go | GetWorkflow | func (ts *Server) GetWorkflow(ctx context.Context, uuid string) (*WorkflowInfo, error) {
// Read the file.
filePath := pathForWorkflow(uuid)
contents, version, err := ts.globalCell.Get(ctx, filePath)
if err != nil {
return nil, err
}
// Unpack the contents.
w := &workflowpb.Workflow{}
if err := proto.Unmarshal(contents, w); err != nil {
return nil, err
}
return &WorkflowInfo{
version: version,
Workflow: w,
}, nil
} | go | func (ts *Server) GetWorkflow(ctx context.Context, uuid string) (*WorkflowInfo, error) {
// Read the file.
filePath := pathForWorkflow(uuid)
contents, version, err := ts.globalCell.Get(ctx, filePath)
if err != nil {
return nil, err
}
// Unpack the contents.
w := &workflowpb.Workflow{}
if err := proto.Unmarshal(contents, w); err != nil {
return nil, err
}
return &WorkflowInfo{
version: version,
Workflow: w,
}, nil
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"GetWorkflow",
"(",
"ctx",
"context",
".",
"Context",
",",
"uuid",
"string",
")",
"(",
"*",
"WorkflowInfo",
",",
"error",
")",
"{",
"// Read the file.",
"filePath",
":=",
"pathForWorkflow",
"(",
"uuid",
")",
"\n",
"contents",
",",
"version",
",",
"err",
":=",
"ts",
".",
"globalCell",
".",
"Get",
"(",
"ctx",
",",
"filePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Unpack the contents.",
"w",
":=",
"&",
"workflowpb",
".",
"Workflow",
"{",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"contents",
",",
"w",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"WorkflowInfo",
"{",
"version",
":",
"version",
",",
"Workflow",
":",
"w",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GetWorkflow reads a workflow from the global cell. | [
"GetWorkflow",
"reads",
"a",
"workflow",
"from",
"the",
"global",
"cell",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/workflow.go#L82-L100 | train |
vitessio/vitess | go/vt/topo/workflow.go | SaveWorkflow | func (ts *Server) SaveWorkflow(ctx context.Context, wi *WorkflowInfo) error {
// Pack the content.
contents, err := proto.Marshal(wi.Workflow)
if err != nil {
return err
}
// Save it.
filePath := pathForWorkflow(wi.Uuid)
version, err := ts.globalCell.Update(ctx, filePath, contents, wi.version)
if err != nil {
return err
}
// Remember the new version.
wi.version = version
return nil
} | go | func (ts *Server) SaveWorkflow(ctx context.Context, wi *WorkflowInfo) error {
// Pack the content.
contents, err := proto.Marshal(wi.Workflow)
if err != nil {
return err
}
// Save it.
filePath := pathForWorkflow(wi.Uuid)
version, err := ts.globalCell.Update(ctx, filePath, contents, wi.version)
if err != nil {
return err
}
// Remember the new version.
wi.version = version
return nil
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"SaveWorkflow",
"(",
"ctx",
"context",
".",
"Context",
",",
"wi",
"*",
"WorkflowInfo",
")",
"error",
"{",
"// Pack the content.",
"contents",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"wi",
".",
"Workflow",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Save it.",
"filePath",
":=",
"pathForWorkflow",
"(",
"wi",
".",
"Uuid",
")",
"\n",
"version",
",",
"err",
":=",
"ts",
".",
"globalCell",
".",
"Update",
"(",
"ctx",
",",
"filePath",
",",
"contents",
",",
"wi",
".",
"version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Remember the new version.",
"wi",
".",
"version",
"=",
"version",
"\n",
"return",
"nil",
"\n",
"}"
] | // SaveWorkflow saves the WorkflowInfo object. If the version is not
// good any more, ErrBadVersion is returned. | [
"SaveWorkflow",
"saves",
"the",
"WorkflowInfo",
"object",
".",
"If",
"the",
"version",
"is",
"not",
"good",
"any",
"more",
"ErrBadVersion",
"is",
"returned",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/workflow.go#L104-L121 | train |
vitessio/vitess | go/vt/topo/workflow.go | DeleteWorkflow | func (ts *Server) DeleteWorkflow(ctx context.Context, wi *WorkflowInfo) error {
filePath := pathForWorkflow(wi.Uuid)
return ts.globalCell.Delete(ctx, filePath, wi.version)
} | go | func (ts *Server) DeleteWorkflow(ctx context.Context, wi *WorkflowInfo) error {
filePath := pathForWorkflow(wi.Uuid)
return ts.globalCell.Delete(ctx, filePath, wi.version)
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"DeleteWorkflow",
"(",
"ctx",
"context",
".",
"Context",
",",
"wi",
"*",
"WorkflowInfo",
")",
"error",
"{",
"filePath",
":=",
"pathForWorkflow",
"(",
"wi",
".",
"Uuid",
")",
"\n",
"return",
"ts",
".",
"globalCell",
".",
"Delete",
"(",
"ctx",
",",
"filePath",
",",
"wi",
".",
"version",
")",
"\n",
"}"
] | // DeleteWorkflow deletes the specified workflow. After this, the
// WorkflowInfo object should not be used any more. | [
"DeleteWorkflow",
"deletes",
"the",
"specified",
"workflow",
".",
"After",
"this",
"the",
"WorkflowInfo",
"object",
"should",
"not",
"be",
"used",
"any",
"more",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/workflow.go#L125-L128 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | CreateTablet | func CreateTablet(ctx context.Context, ts *topo.Server, cell string, uid uint32, keyspace, shard, dbname string, tabletType topodatapb.TabletType, mysqld mysqlctl.MysqlDaemon, dbcfgs *dbconfigs.DBConfigs) error {
alias := &topodatapb.TabletAlias{
Cell: cell,
Uid: uid,
}
log.Infof("Creating %v tablet %v for %v/%v", tabletType, topoproto.TabletAliasString(alias), keyspace, shard)
flag.Set("debug-url-prefix", fmt.Sprintf("/debug-%d", uid))
controller := tabletserver.NewServer(ts, *alias)
initTabletType := tabletType
if tabletType == topodatapb.TabletType_MASTER {
initTabletType = topodatapb.TabletType_REPLICA
}
agent := tabletmanager.NewComboActionAgent(ctx, ts, alias, int32(8000+uid), int32(9000+uid), controller, dbcfgs, mysqld, keyspace, shard, dbname, strings.ToLower(initTabletType.String()))
if tabletType == topodatapb.TabletType_MASTER {
if err := agent.TabletExternallyReparented(ctx, ""); err != nil {
return fmt.Errorf("TabletExternallyReparented failed on master %v: %v", topoproto.TabletAliasString(alias), err)
}
}
tabletMap[uid] = &tablet{
keyspace: keyspace,
shard: shard,
tabletType: tabletType,
dbname: dbname,
qsc: controller,
agent: agent,
}
return nil
} | go | func CreateTablet(ctx context.Context, ts *topo.Server, cell string, uid uint32, keyspace, shard, dbname string, tabletType topodatapb.TabletType, mysqld mysqlctl.MysqlDaemon, dbcfgs *dbconfigs.DBConfigs) error {
alias := &topodatapb.TabletAlias{
Cell: cell,
Uid: uid,
}
log.Infof("Creating %v tablet %v for %v/%v", tabletType, topoproto.TabletAliasString(alias), keyspace, shard)
flag.Set("debug-url-prefix", fmt.Sprintf("/debug-%d", uid))
controller := tabletserver.NewServer(ts, *alias)
initTabletType := tabletType
if tabletType == topodatapb.TabletType_MASTER {
initTabletType = topodatapb.TabletType_REPLICA
}
agent := tabletmanager.NewComboActionAgent(ctx, ts, alias, int32(8000+uid), int32(9000+uid), controller, dbcfgs, mysqld, keyspace, shard, dbname, strings.ToLower(initTabletType.String()))
if tabletType == topodatapb.TabletType_MASTER {
if err := agent.TabletExternallyReparented(ctx, ""); err != nil {
return fmt.Errorf("TabletExternallyReparented failed on master %v: %v", topoproto.TabletAliasString(alias), err)
}
}
tabletMap[uid] = &tablet{
keyspace: keyspace,
shard: shard,
tabletType: tabletType,
dbname: dbname,
qsc: controller,
agent: agent,
}
return nil
} | [
"func",
"CreateTablet",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"topo",
".",
"Server",
",",
"cell",
"string",
",",
"uid",
"uint32",
",",
"keyspace",
",",
"shard",
",",
"dbname",
"string",
",",
"tabletType",
"topodatapb",
".",
"TabletType",
",",
"mysqld",
"mysqlctl",
".",
"MysqlDaemon",
",",
"dbcfgs",
"*",
"dbconfigs",
".",
"DBConfigs",
")",
"error",
"{",
"alias",
":=",
"&",
"topodatapb",
".",
"TabletAlias",
"{",
"Cell",
":",
"cell",
",",
"Uid",
":",
"uid",
",",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"tabletType",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
",",
"keyspace",
",",
"shard",
")",
"\n",
"flag",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"uid",
")",
")",
"\n\n",
"controller",
":=",
"tabletserver",
".",
"NewServer",
"(",
"ts",
",",
"*",
"alias",
")",
"\n",
"initTabletType",
":=",
"tabletType",
"\n",
"if",
"tabletType",
"==",
"topodatapb",
".",
"TabletType_MASTER",
"{",
"initTabletType",
"=",
"topodatapb",
".",
"TabletType_REPLICA",
"\n",
"}",
"\n",
"agent",
":=",
"tabletmanager",
".",
"NewComboActionAgent",
"(",
"ctx",
",",
"ts",
",",
"alias",
",",
"int32",
"(",
"8000",
"+",
"uid",
")",
",",
"int32",
"(",
"9000",
"+",
"uid",
")",
",",
"controller",
",",
"dbcfgs",
",",
"mysqld",
",",
"keyspace",
",",
"shard",
",",
"dbname",
",",
"strings",
".",
"ToLower",
"(",
"initTabletType",
".",
"String",
"(",
")",
")",
")",
"\n",
"if",
"tabletType",
"==",
"topodatapb",
".",
"TabletType_MASTER",
"{",
"if",
"err",
":=",
"agent",
".",
"TabletExternallyReparented",
"(",
"ctx",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"tabletMap",
"[",
"uid",
"]",
"=",
"&",
"tablet",
"{",
"keyspace",
":",
"keyspace",
",",
"shard",
":",
"shard",
",",
"tabletType",
":",
"tabletType",
",",
"dbname",
":",
"dbname",
",",
"qsc",
":",
"controller",
",",
"agent",
":",
"agent",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CreateTablet creates an individual tablet, with its agent, and adds
// it to the map. If it's a master tablet, it also issues a TER. | [
"CreateTablet",
"creates",
"an",
"individual",
"tablet",
"with",
"its",
"agent",
"and",
"adds",
"it",
"to",
"the",
"map",
".",
"If",
"it",
"s",
"a",
"master",
"tablet",
"it",
"also",
"issues",
"a",
"TER",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L77-L106 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | dialer | func dialer(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) {
t, ok := tabletMap[tablet.Alias.Uid]
if !ok {
return nil, vterrors.New(vtrpcpb.Code_UNAVAILABLE, "connection refused")
}
return &internalTabletConn{
tablet: t,
topoTablet: tablet,
}, nil
} | go | func dialer(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) {
t, ok := tabletMap[tablet.Alias.Uid]
if !ok {
return nil, vterrors.New(vtrpcpb.Code_UNAVAILABLE, "connection refused")
}
return &internalTabletConn{
tablet: t,
topoTablet: tablet,
}, nil
} | [
"func",
"dialer",
"(",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
",",
"failFast",
"grpcclient",
".",
"FailFast",
")",
"(",
"queryservice",
".",
"QueryService",
",",
"error",
")",
"{",
"t",
",",
"ok",
":=",
"tabletMap",
"[",
"tablet",
".",
"Alias",
".",
"Uid",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"vterrors",
".",
"New",
"(",
"vtrpcpb",
".",
"Code_UNAVAILABLE",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"internalTabletConn",
"{",
"tablet",
":",
"t",
",",
"topoTablet",
":",
"tablet",
",",
"}",
",",
"nil",
"\n",
"}"
] | //
// TabletConn implementation
//
// dialer is our tabletconn.Dialer | [
"TabletConn",
"implementation",
"dialer",
"is",
"our",
"tabletconn",
".",
"Dialer"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L274-L284 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | Execute | func (itc *internalTabletConn) Execute(ctx context.Context, target *querypb.Target, query string, bindVars map[string]*querypb.BindVariable, transactionID int64, options *querypb.ExecuteOptions) (*sqltypes.Result, error) {
bindVars = sqltypes.CopyBindVariables(bindVars)
reply, err := itc.tablet.qsc.QueryService().Execute(ctx, target, query, bindVars, transactionID, options)
if err != nil {
return nil, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return reply, nil
} | go | func (itc *internalTabletConn) Execute(ctx context.Context, target *querypb.Target, query string, bindVars map[string]*querypb.BindVariable, transactionID int64, options *querypb.ExecuteOptions) (*sqltypes.Result, error) {
bindVars = sqltypes.CopyBindVariables(bindVars)
reply, err := itc.tablet.qsc.QueryService().Execute(ctx, target, query, bindVars, transactionID, options)
if err != nil {
return nil, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return reply, nil
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"Execute",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"query",
"string",
",",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"transactionID",
"int64",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
")",
"(",
"*",
"sqltypes",
".",
"Result",
",",
"error",
")",
"{",
"bindVars",
"=",
"sqltypes",
".",
"CopyBindVariables",
"(",
"bindVars",
")",
"\n",
"reply",
",",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"Execute",
"(",
"ctx",
",",
"target",
",",
"query",
",",
"bindVars",
",",
"transactionID",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"reply",
",",
"nil",
"\n",
"}"
] | // Execute is part of queryservice.QueryService
// We need to copy the bind variables as tablet server will change them. | [
"Execute",
"is",
"part",
"of",
"queryservice",
".",
"QueryService",
"We",
"need",
"to",
"copy",
"the",
"bind",
"variables",
"as",
"tablet",
"server",
"will",
"change",
"them",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L295-L302 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | ExecuteBatch | func (itc *internalTabletConn) ExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) {
q := make([]*querypb.BoundQuery, len(queries))
for i, query := range queries {
q[i] = &querypb.BoundQuery{
Sql: query.Sql,
BindVariables: sqltypes.CopyBindVariables(query.BindVariables),
}
}
results, err := itc.tablet.qsc.QueryService().ExecuteBatch(ctx, target, q, asTransaction, transactionID, options)
if err != nil {
return nil, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return results, nil
} | go | func (itc *internalTabletConn) ExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) {
q := make([]*querypb.BoundQuery, len(queries))
for i, query := range queries {
q[i] = &querypb.BoundQuery{
Sql: query.Sql,
BindVariables: sqltypes.CopyBindVariables(query.BindVariables),
}
}
results, err := itc.tablet.qsc.QueryService().ExecuteBatch(ctx, target, q, asTransaction, transactionID, options)
if err != nil {
return nil, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return results, nil
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"ExecuteBatch",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"queries",
"[",
"]",
"*",
"querypb",
".",
"BoundQuery",
",",
"asTransaction",
"bool",
",",
"transactionID",
"int64",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
")",
"(",
"[",
"]",
"sqltypes",
".",
"Result",
",",
"error",
")",
"{",
"q",
":=",
"make",
"(",
"[",
"]",
"*",
"querypb",
".",
"BoundQuery",
",",
"len",
"(",
"queries",
")",
")",
"\n",
"for",
"i",
",",
"query",
":=",
"range",
"queries",
"{",
"q",
"[",
"i",
"]",
"=",
"&",
"querypb",
".",
"BoundQuery",
"{",
"Sql",
":",
"query",
".",
"Sql",
",",
"BindVariables",
":",
"sqltypes",
".",
"CopyBindVariables",
"(",
"query",
".",
"BindVariables",
")",
",",
"}",
"\n",
"}",
"\n",
"results",
",",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"ExecuteBatch",
"(",
"ctx",
",",
"target",
",",
"q",
",",
"asTransaction",
",",
"transactionID",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // ExecuteBatch is part of queryservice.QueryService
// We need to copy the bind variables as tablet server will change them. | [
"ExecuteBatch",
"is",
"part",
"of",
"queryservice",
".",
"QueryService",
"We",
"need",
"to",
"copy",
"the",
"bind",
"variables",
"as",
"tablet",
"server",
"will",
"change",
"them",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L306-L319 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | Begin | func (itc *internalTabletConn) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (int64, error) {
transactionID, err := itc.tablet.qsc.QueryService().Begin(ctx, target, options)
if err != nil {
return 0, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return transactionID, nil
} | go | func (itc *internalTabletConn) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (int64, error) {
transactionID, err := itc.tablet.qsc.QueryService().Begin(ctx, target, options)
if err != nil {
return 0, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return transactionID, nil
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"Begin",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
")",
"(",
"int64",
",",
"error",
")",
"{",
"transactionID",
",",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"Begin",
"(",
"ctx",
",",
"target",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"transactionID",
",",
"nil",
"\n",
"}"
] | // Begin is part of queryservice.QueryService | [
"Begin",
"is",
"part",
"of",
"queryservice",
".",
"QueryService"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L330-L336 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | Commit | func (itc *internalTabletConn) Commit(ctx context.Context, target *querypb.Target, transactionID int64) error {
err := itc.tablet.qsc.QueryService().Commit(ctx, target, transactionID)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | go | func (itc *internalTabletConn) Commit(ctx context.Context, target *querypb.Target, transactionID int64) error {
err := itc.tablet.qsc.QueryService().Commit(ctx, target, transactionID)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"Commit",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"transactionID",
"int64",
")",
"error",
"{",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"Commit",
"(",
"ctx",
",",
"target",
",",
"transactionID",
")",
"\n",
"return",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}"
] | // Commit is part of queryservice.QueryService | [
"Commit",
"is",
"part",
"of",
"queryservice",
".",
"QueryService"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L339-L342 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | BeginExecuteBatch | func (itc *internalTabletConn) BeginExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, options *querypb.ExecuteOptions) ([]sqltypes.Result, int64, error) {
transactionID, err := itc.Begin(ctx, target, options)
if err != nil {
return nil, 0, err
}
results, err := itc.ExecuteBatch(ctx, target, queries, asTransaction, transactionID, options)
return results, transactionID, err
} | go | func (itc *internalTabletConn) BeginExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, options *querypb.ExecuteOptions) ([]sqltypes.Result, int64, error) {
transactionID, err := itc.Begin(ctx, target, options)
if err != nil {
return nil, 0, err
}
results, err := itc.ExecuteBatch(ctx, target, queries, asTransaction, transactionID, options)
return results, transactionID, err
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"BeginExecuteBatch",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"queries",
"[",
"]",
"*",
"querypb",
".",
"BoundQuery",
",",
"asTransaction",
"bool",
",",
"options",
"*",
"querypb",
".",
"ExecuteOptions",
")",
"(",
"[",
"]",
"sqltypes",
".",
"Result",
",",
"int64",
",",
"error",
")",
"{",
"transactionID",
",",
"err",
":=",
"itc",
".",
"Begin",
"(",
"ctx",
",",
"target",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"results",
",",
"err",
":=",
"itc",
".",
"ExecuteBatch",
"(",
"ctx",
",",
"target",
",",
"queries",
",",
"asTransaction",
",",
"transactionID",
",",
"options",
")",
"\n",
"return",
"results",
",",
"transactionID",
",",
"err",
"\n",
"}"
] | // BeginExecuteBatch is part of queryservice.QueryService | [
"BeginExecuteBatch",
"is",
"part",
"of",
"queryservice",
".",
"QueryService"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L409-L416 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | MessageStream | func (itc *internalTabletConn) MessageStream(ctx context.Context, target *querypb.Target, name string, callback func(*sqltypes.Result) error) error {
err := itc.tablet.qsc.QueryService().MessageStream(ctx, target, name, callback)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | go | func (itc *internalTabletConn) MessageStream(ctx context.Context, target *querypb.Target, name string, callback func(*sqltypes.Result) error) error {
err := itc.tablet.qsc.QueryService().MessageStream(ctx, target, name, callback)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"MessageStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"name",
"string",
",",
"callback",
"func",
"(",
"*",
"sqltypes",
".",
"Result",
")",
"error",
")",
"error",
"{",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"MessageStream",
"(",
"ctx",
",",
"target",
",",
"name",
",",
"callback",
")",
"\n",
"return",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}"
] | // MessageStream is part of queryservice.QueryService | [
"MessageStream",
"is",
"part",
"of",
"queryservice",
".",
"QueryService"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L419-L422 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | MessageAck | func (itc *internalTabletConn) MessageAck(ctx context.Context, target *querypb.Target, name string, ids []*querypb.Value) (int64, error) {
count, err := itc.tablet.qsc.QueryService().MessageAck(ctx, target, name, ids)
return count, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | go | func (itc *internalTabletConn) MessageAck(ctx context.Context, target *querypb.Target, name string, ids []*querypb.Value) (int64, error) {
count, err := itc.tablet.qsc.QueryService().MessageAck(ctx, target, name, ids)
return count, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"MessageAck",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"name",
"string",
",",
"ids",
"[",
"]",
"*",
"querypb",
".",
"Value",
")",
"(",
"int64",
",",
"error",
")",
"{",
"count",
",",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"MessageAck",
"(",
"ctx",
",",
"target",
",",
"name",
",",
"ids",
")",
"\n",
"return",
"count",
",",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}"
] | // MessageAck is part of queryservice.QueryService | [
"MessageAck",
"is",
"part",
"of",
"queryservice",
".",
"QueryService"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L425-L428 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | SplitQuery | func (itc *internalTabletConn) SplitQuery(
ctx context.Context,
target *querypb.Target,
query *querypb.BoundQuery,
splitColumns []string,
splitCount int64,
numRowsPerQueryPart int64,
algorithm querypb.SplitQueryRequest_Algorithm) ([]*querypb.QuerySplit, error) {
splits, err := itc.tablet.qsc.QueryService().SplitQuery(
ctx,
target,
query,
splitColumns,
splitCount,
numRowsPerQueryPart,
algorithm)
if err != nil {
return nil, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return splits, nil
} | go | func (itc *internalTabletConn) SplitQuery(
ctx context.Context,
target *querypb.Target,
query *querypb.BoundQuery,
splitColumns []string,
splitCount int64,
numRowsPerQueryPart int64,
algorithm querypb.SplitQueryRequest_Algorithm) ([]*querypb.QuerySplit, error) {
splits, err := itc.tablet.qsc.QueryService().SplitQuery(
ctx,
target,
query,
splitColumns,
splitCount,
numRowsPerQueryPart,
algorithm)
if err != nil {
return nil, tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
}
return splits, nil
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"SplitQuery",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"query",
"*",
"querypb",
".",
"BoundQuery",
",",
"splitColumns",
"[",
"]",
"string",
",",
"splitCount",
"int64",
",",
"numRowsPerQueryPart",
"int64",
",",
"algorithm",
"querypb",
".",
"SplitQueryRequest_Algorithm",
")",
"(",
"[",
"]",
"*",
"querypb",
".",
"QuerySplit",
",",
"error",
")",
"{",
"splits",
",",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"SplitQuery",
"(",
"ctx",
",",
"target",
",",
"query",
",",
"splitColumns",
",",
"splitCount",
",",
"numRowsPerQueryPart",
",",
"algorithm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"splits",
",",
"nil",
"\n",
"}"
] | // SplitQuery is part of queryservice.QueryService | [
"SplitQuery",
"is",
"part",
"of",
"queryservice",
".",
"QueryService"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L445-L466 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | StreamHealth | func (itc *internalTabletConn) StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error {
err := itc.tablet.qsc.QueryService().StreamHealth(ctx, callback)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | go | func (itc *internalTabletConn) StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error {
err := itc.tablet.qsc.QueryService().StreamHealth(ctx, callback)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"StreamHealth",
"(",
"ctx",
"context",
".",
"Context",
",",
"callback",
"func",
"(",
"*",
"querypb",
".",
"StreamHealthResponse",
")",
"error",
")",
"error",
"{",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"StreamHealth",
"(",
"ctx",
",",
"callback",
")",
"\n",
"return",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}"
] | // StreamHealth is part of queryservice.QueryService | [
"StreamHealth",
"is",
"part",
"of",
"queryservice",
".",
"QueryService"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L469-L472 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | UpdateStream | func (itc *internalTabletConn) UpdateStream(ctx context.Context, target *querypb.Target, position string, timestamp int64, callback func(*querypb.StreamEvent) error) error {
err := itc.tablet.qsc.QueryService().UpdateStream(ctx, target, position, timestamp, callback)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | go | func (itc *internalTabletConn) UpdateStream(ctx context.Context, target *querypb.Target, position string, timestamp int64, callback func(*querypb.StreamEvent) error) error {
err := itc.tablet.qsc.QueryService().UpdateStream(ctx, target, position, timestamp, callback)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"UpdateStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"position",
"string",
",",
"timestamp",
"int64",
",",
"callback",
"func",
"(",
"*",
"querypb",
".",
"StreamEvent",
")",
"error",
")",
"error",
"{",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"UpdateStream",
"(",
"ctx",
",",
"target",
",",
"position",
",",
"timestamp",
",",
"callback",
")",
"\n",
"return",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}"
] | // UpdateStream is part of queryservice.QueryService. | [
"UpdateStream",
"is",
"part",
"of",
"queryservice",
".",
"QueryService",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L475-L478 | train |
vitessio/vitess | go/vt/vtcombo/tablet_map.go | VStream | func (itc *internalTabletConn) VStream(ctx context.Context, target *querypb.Target, startPos string, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error {
err := itc.tablet.qsc.QueryService().VStream(ctx, target, startPos, filter, send)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | go | func (itc *internalTabletConn) VStream(ctx context.Context, target *querypb.Target, startPos string, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error {
err := itc.tablet.qsc.QueryService().VStream(ctx, target, startPos, filter, send)
return tabletconn.ErrorFromGRPC(vterrors.ToGRPC(err))
} | [
"func",
"(",
"itc",
"*",
"internalTabletConn",
")",
"VStream",
"(",
"ctx",
"context",
".",
"Context",
",",
"target",
"*",
"querypb",
".",
"Target",
",",
"startPos",
"string",
",",
"filter",
"*",
"binlogdatapb",
".",
"Filter",
",",
"send",
"func",
"(",
"[",
"]",
"*",
"binlogdatapb",
".",
"VEvent",
")",
"error",
")",
"error",
"{",
"err",
":=",
"itc",
".",
"tablet",
".",
"qsc",
".",
"QueryService",
"(",
")",
".",
"VStream",
"(",
"ctx",
",",
"target",
",",
"startPos",
",",
"filter",
",",
"send",
")",
"\n",
"return",
"tabletconn",
".",
"ErrorFromGRPC",
"(",
"vterrors",
".",
"ToGRPC",
"(",
"err",
")",
")",
"\n",
"}"
] | // VStream is part of queryservice.QueryService. | [
"VStream",
"is",
"part",
"of",
"queryservice",
".",
"QueryService",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtcombo/tablet_map.go#L481-L484 | train |
vitessio/vitess | go/vt/mysqlctl/schema.go | executeSchemaCommands | func (mysqld *Mysqld) executeSchemaCommands(sql string) error {
params, err := dbconfigs.WithCredentials(mysqld.dbcfgs.Dba())
if err != nil {
return err
}
return mysqld.executeMysqlScript(params, strings.NewReader(sql))
} | go | func (mysqld *Mysqld) executeSchemaCommands(sql string) error {
params, err := dbconfigs.WithCredentials(mysqld.dbcfgs.Dba())
if err != nil {
return err
}
return mysqld.executeMysqlScript(params, strings.NewReader(sql))
} | [
"func",
"(",
"mysqld",
"*",
"Mysqld",
")",
"executeSchemaCommands",
"(",
"sql",
"string",
")",
"error",
"{",
"params",
",",
"err",
":=",
"dbconfigs",
".",
"WithCredentials",
"(",
"mysqld",
".",
"dbcfgs",
".",
"Dba",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"mysqld",
".",
"executeMysqlScript",
"(",
"params",
",",
"strings",
".",
"NewReader",
"(",
"sql",
")",
")",
"\n",
"}"
] | // executeSchemaCommands executes some SQL commands, using the mysql
// command line tool. It uses the dba connection parameters, with credentials. | [
"executeSchemaCommands",
"executes",
"some",
"SQL",
"commands",
"using",
"the",
"mysql",
"command",
"line",
"tool",
".",
"It",
"uses",
"the",
"dba",
"connection",
"parameters",
"with",
"credentials",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/schema.go#L39-L46 | train |
vitessio/vitess | go/vt/mysqlctl/schema.go | ResolveTables | func ResolveTables(mysqld MysqlDaemon, dbName string, tables []string) ([]string, error) {
sd, err := mysqld.GetSchema(dbName, tables, nil, true)
if err != nil {
return nil, err
}
result := make([]string, len(sd.TableDefinitions))
for i, td := range sd.TableDefinitions {
result[i] = td.Name
}
return result, nil
} | go | func ResolveTables(mysqld MysqlDaemon, dbName string, tables []string) ([]string, error) {
sd, err := mysqld.GetSchema(dbName, tables, nil, true)
if err != nil {
return nil, err
}
result := make([]string, len(sd.TableDefinitions))
for i, td := range sd.TableDefinitions {
result[i] = td.Name
}
return result, nil
} | [
"func",
"ResolveTables",
"(",
"mysqld",
"MysqlDaemon",
",",
"dbName",
"string",
",",
"tables",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"sd",
",",
"err",
":=",
"mysqld",
".",
"GetSchema",
"(",
"dbName",
",",
"tables",
",",
"nil",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"sd",
".",
"TableDefinitions",
")",
")",
"\n",
"for",
"i",
",",
"td",
":=",
"range",
"sd",
".",
"TableDefinitions",
"{",
"result",
"[",
"i",
"]",
"=",
"td",
".",
"Name",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // ResolveTables returns a list of actual tables+views matching a list
// of regexps | [
"ResolveTables",
"returns",
"a",
"list",
"of",
"actual",
"tables",
"+",
"views",
"matching",
"a",
"list",
"of",
"regexps"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/schema.go#L149-L159 | train |
vitessio/vitess | go/vt/mysqlctl/schema.go | GetColumns | func (mysqld *Mysqld) GetColumns(dbName, table string) ([]string, error) {
conn, err := getPoolReconnect(context.TODO(), mysqld.dbaPool)
if err != nil {
return nil, err
}
defer conn.Recycle()
qr, err := conn.ExecuteFetch(fmt.Sprintf("SELECT * FROM %s.%s WHERE 1=0", sqlescape.EscapeID(dbName), sqlescape.EscapeID(table)), 0, true)
if err != nil {
return nil, err
}
columns := make([]string, len(qr.Fields))
for i, field := range qr.Fields {
columns[i] = field.Name
}
return columns, nil
} | go | func (mysqld *Mysqld) GetColumns(dbName, table string) ([]string, error) {
conn, err := getPoolReconnect(context.TODO(), mysqld.dbaPool)
if err != nil {
return nil, err
}
defer conn.Recycle()
qr, err := conn.ExecuteFetch(fmt.Sprintf("SELECT * FROM %s.%s WHERE 1=0", sqlescape.EscapeID(dbName), sqlescape.EscapeID(table)), 0, true)
if err != nil {
return nil, err
}
columns := make([]string, len(qr.Fields))
for i, field := range qr.Fields {
columns[i] = field.Name
}
return columns, nil
} | [
"func",
"(",
"mysqld",
"*",
"Mysqld",
")",
"GetColumns",
"(",
"dbName",
",",
"table",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"getPoolReconnect",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"mysqld",
".",
"dbaPool",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Recycle",
"(",
")",
"\n",
"qr",
",",
"err",
":=",
"conn",
".",
"ExecuteFetch",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sqlescape",
".",
"EscapeID",
"(",
"dbName",
")",
",",
"sqlescape",
".",
"EscapeID",
"(",
"table",
")",
")",
",",
"0",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"columns",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"qr",
".",
"Fields",
")",
")",
"\n",
"for",
"i",
",",
"field",
":=",
"range",
"qr",
".",
"Fields",
"{",
"columns",
"[",
"i",
"]",
"=",
"field",
".",
"Name",
"\n",
"}",
"\n",
"return",
"columns",
",",
"nil",
"\n\n",
"}"
] | // GetColumns returns the columns of table. | [
"GetColumns",
"returns",
"the",
"columns",
"of",
"table",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/schema.go#L162-L178 | train |
vitessio/vitess | go/vt/mysqlctl/schema.go | GetPrimaryKeyColumns | func (mysqld *Mysqld) GetPrimaryKeyColumns(dbName, table string) ([]string, error) {
conn, err := getPoolReconnect(context.TODO(), mysqld.dbaPool)
if err != nil {
return nil, err
}
defer conn.Recycle()
qr, err := conn.ExecuteFetch(fmt.Sprintf("SHOW INDEX FROM %s.%s", sqlescape.EscapeID(dbName), sqlescape.EscapeID(table)), 100, true)
if err != nil {
return nil, err
}
keyNameIndex := -1
seqInIndexIndex := -1
columnNameIndex := -1
for i, field := range qr.Fields {
switch field.Name {
case "Key_name":
keyNameIndex = i
case "Seq_in_index":
seqInIndexIndex = i
case "Column_name":
columnNameIndex = i
}
}
if keyNameIndex == -1 || seqInIndexIndex == -1 || columnNameIndex == -1 {
return nil, fmt.Errorf("unknown columns in 'show index' result: %v", qr.Fields)
}
columns := make([]string, 0, 5)
var expectedIndex int64 = 1
for _, row := range qr.Rows {
// skip non-primary keys
if row[keyNameIndex].ToString() != "PRIMARY" {
continue
}
// check the Seq_in_index is always increasing
seqInIndex, err := sqltypes.ToInt64(row[seqInIndexIndex])
if err != nil {
return nil, err
}
if seqInIndex != expectedIndex {
return nil, fmt.Errorf("unexpected index: %v != %v", seqInIndex, expectedIndex)
}
expectedIndex++
columns = append(columns, row[columnNameIndex].ToString())
}
return columns, err
} | go | func (mysqld *Mysqld) GetPrimaryKeyColumns(dbName, table string) ([]string, error) {
conn, err := getPoolReconnect(context.TODO(), mysqld.dbaPool)
if err != nil {
return nil, err
}
defer conn.Recycle()
qr, err := conn.ExecuteFetch(fmt.Sprintf("SHOW INDEX FROM %s.%s", sqlescape.EscapeID(dbName), sqlescape.EscapeID(table)), 100, true)
if err != nil {
return nil, err
}
keyNameIndex := -1
seqInIndexIndex := -1
columnNameIndex := -1
for i, field := range qr.Fields {
switch field.Name {
case "Key_name":
keyNameIndex = i
case "Seq_in_index":
seqInIndexIndex = i
case "Column_name":
columnNameIndex = i
}
}
if keyNameIndex == -1 || seqInIndexIndex == -1 || columnNameIndex == -1 {
return nil, fmt.Errorf("unknown columns in 'show index' result: %v", qr.Fields)
}
columns := make([]string, 0, 5)
var expectedIndex int64 = 1
for _, row := range qr.Rows {
// skip non-primary keys
if row[keyNameIndex].ToString() != "PRIMARY" {
continue
}
// check the Seq_in_index is always increasing
seqInIndex, err := sqltypes.ToInt64(row[seqInIndexIndex])
if err != nil {
return nil, err
}
if seqInIndex != expectedIndex {
return nil, fmt.Errorf("unexpected index: %v != %v", seqInIndex, expectedIndex)
}
expectedIndex++
columns = append(columns, row[columnNameIndex].ToString())
}
return columns, err
} | [
"func",
"(",
"mysqld",
"*",
"Mysqld",
")",
"GetPrimaryKeyColumns",
"(",
"dbName",
",",
"table",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"getPoolReconnect",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"mysqld",
".",
"dbaPool",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Recycle",
"(",
")",
"\n",
"qr",
",",
"err",
":=",
"conn",
".",
"ExecuteFetch",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sqlescape",
".",
"EscapeID",
"(",
"dbName",
")",
",",
"sqlescape",
".",
"EscapeID",
"(",
"table",
")",
")",
",",
"100",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"keyNameIndex",
":=",
"-",
"1",
"\n",
"seqInIndexIndex",
":=",
"-",
"1",
"\n",
"columnNameIndex",
":=",
"-",
"1",
"\n",
"for",
"i",
",",
"field",
":=",
"range",
"qr",
".",
"Fields",
"{",
"switch",
"field",
".",
"Name",
"{",
"case",
"\"",
"\"",
":",
"keyNameIndex",
"=",
"i",
"\n",
"case",
"\"",
"\"",
":",
"seqInIndexIndex",
"=",
"i",
"\n",
"case",
"\"",
"\"",
":",
"columnNameIndex",
"=",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"keyNameIndex",
"==",
"-",
"1",
"||",
"seqInIndexIndex",
"==",
"-",
"1",
"||",
"columnNameIndex",
"==",
"-",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"qr",
".",
"Fields",
")",
"\n",
"}",
"\n\n",
"columns",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"5",
")",
"\n",
"var",
"expectedIndex",
"int64",
"=",
"1",
"\n",
"for",
"_",
",",
"row",
":=",
"range",
"qr",
".",
"Rows",
"{",
"// skip non-primary keys",
"if",
"row",
"[",
"keyNameIndex",
"]",
".",
"ToString",
"(",
")",
"!=",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"// check the Seq_in_index is always increasing",
"seqInIndex",
",",
"err",
":=",
"sqltypes",
".",
"ToInt64",
"(",
"row",
"[",
"seqInIndexIndex",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"seqInIndex",
"!=",
"expectedIndex",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"seqInIndex",
",",
"expectedIndex",
")",
"\n",
"}",
"\n",
"expectedIndex",
"++",
"\n\n",
"columns",
"=",
"append",
"(",
"columns",
",",
"row",
"[",
"columnNameIndex",
"]",
".",
"ToString",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"columns",
",",
"err",
"\n",
"}"
] | // GetPrimaryKeyColumns returns the primary key columns of table. | [
"GetPrimaryKeyColumns",
"returns",
"the",
"primary",
"key",
"columns",
"of",
"table",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/schema.go#L181-L229 | train |
vitessio/vitess | go/vt/mysqlctl/schema.go | PreflightSchemaChange | func (mysqld *Mysqld) PreflightSchemaChange(dbName string, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error) {
results := make([]*tabletmanagerdatapb.SchemaChangeResult, len(changes))
// Get current schema from the real database.
originalSchema, err := mysqld.GetSchema(dbName, nil, nil, true)
if err != nil {
return nil, err
}
// Populate temporary database with it.
initialCopySQL := "SET sql_log_bin = 0;\n"
initialCopySQL += "DROP DATABASE IF EXISTS _vt_preflight;\n"
initialCopySQL += "CREATE DATABASE _vt_preflight;\n"
initialCopySQL += "USE _vt_preflight;\n"
for _, td := range originalSchema.TableDefinitions {
if td.Type == tmutils.TableBaseTable {
initialCopySQL += td.Schema + ";\n"
}
}
for _, td := range originalSchema.TableDefinitions {
if td.Type == tmutils.TableView {
// Views will have {{.DatabaseName}} in there, replace
// it with _vt_preflight
s := strings.Replace(td.Schema, "{{.DatabaseName}}", "`_vt_preflight`", -1)
initialCopySQL += s + ";\n"
}
}
if err = mysqld.executeSchemaCommands(initialCopySQL); err != nil {
return nil, err
}
// For each change, record the schema before and after.
for i, change := range changes {
beforeSchema, err := mysqld.GetSchema("_vt_preflight", nil, nil, true)
if err != nil {
return nil, err
}
// apply schema change to the temporary database
sql := "SET sql_log_bin = 0;\n"
sql += "USE _vt_preflight;\n"
sql += change
if err = mysqld.executeSchemaCommands(sql); err != nil {
return nil, err
}
// get the result
afterSchema, err := mysqld.GetSchema("_vt_preflight", nil, nil, true)
if err != nil {
return nil, err
}
results[i] = &tabletmanagerdatapb.SchemaChangeResult{BeforeSchema: beforeSchema, AfterSchema: afterSchema}
}
// and clean up the extra database
dropSQL := "SET sql_log_bin = 0;\n"
dropSQL += "DROP DATABASE _vt_preflight;\n"
if err = mysqld.executeSchemaCommands(dropSQL); err != nil {
return nil, err
}
return results, nil
} | go | func (mysqld *Mysqld) PreflightSchemaChange(dbName string, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error) {
results := make([]*tabletmanagerdatapb.SchemaChangeResult, len(changes))
// Get current schema from the real database.
originalSchema, err := mysqld.GetSchema(dbName, nil, nil, true)
if err != nil {
return nil, err
}
// Populate temporary database with it.
initialCopySQL := "SET sql_log_bin = 0;\n"
initialCopySQL += "DROP DATABASE IF EXISTS _vt_preflight;\n"
initialCopySQL += "CREATE DATABASE _vt_preflight;\n"
initialCopySQL += "USE _vt_preflight;\n"
for _, td := range originalSchema.TableDefinitions {
if td.Type == tmutils.TableBaseTable {
initialCopySQL += td.Schema + ";\n"
}
}
for _, td := range originalSchema.TableDefinitions {
if td.Type == tmutils.TableView {
// Views will have {{.DatabaseName}} in there, replace
// it with _vt_preflight
s := strings.Replace(td.Schema, "{{.DatabaseName}}", "`_vt_preflight`", -1)
initialCopySQL += s + ";\n"
}
}
if err = mysqld.executeSchemaCommands(initialCopySQL); err != nil {
return nil, err
}
// For each change, record the schema before and after.
for i, change := range changes {
beforeSchema, err := mysqld.GetSchema("_vt_preflight", nil, nil, true)
if err != nil {
return nil, err
}
// apply schema change to the temporary database
sql := "SET sql_log_bin = 0;\n"
sql += "USE _vt_preflight;\n"
sql += change
if err = mysqld.executeSchemaCommands(sql); err != nil {
return nil, err
}
// get the result
afterSchema, err := mysqld.GetSchema("_vt_preflight", nil, nil, true)
if err != nil {
return nil, err
}
results[i] = &tabletmanagerdatapb.SchemaChangeResult{BeforeSchema: beforeSchema, AfterSchema: afterSchema}
}
// and clean up the extra database
dropSQL := "SET sql_log_bin = 0;\n"
dropSQL += "DROP DATABASE _vt_preflight;\n"
if err = mysqld.executeSchemaCommands(dropSQL); err != nil {
return nil, err
}
return results, nil
} | [
"func",
"(",
"mysqld",
"*",
"Mysqld",
")",
"PreflightSchemaChange",
"(",
"dbName",
"string",
",",
"changes",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"*",
"tabletmanagerdatapb",
".",
"SchemaChangeResult",
",",
"error",
")",
"{",
"results",
":=",
"make",
"(",
"[",
"]",
"*",
"tabletmanagerdatapb",
".",
"SchemaChangeResult",
",",
"len",
"(",
"changes",
")",
")",
"\n\n",
"// Get current schema from the real database.",
"originalSchema",
",",
"err",
":=",
"mysqld",
".",
"GetSchema",
"(",
"dbName",
",",
"nil",
",",
"nil",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Populate temporary database with it.",
"initialCopySQL",
":=",
"\"",
"\\n",
"\"",
"\n",
"initialCopySQL",
"+=",
"\"",
"\\n",
"\"",
"\n",
"initialCopySQL",
"+=",
"\"",
"\\n",
"\"",
"\n",
"initialCopySQL",
"+=",
"\"",
"\\n",
"\"",
"\n",
"for",
"_",
",",
"td",
":=",
"range",
"originalSchema",
".",
"TableDefinitions",
"{",
"if",
"td",
".",
"Type",
"==",
"tmutils",
".",
"TableBaseTable",
"{",
"initialCopySQL",
"+=",
"td",
".",
"Schema",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"td",
":=",
"range",
"originalSchema",
".",
"TableDefinitions",
"{",
"if",
"td",
".",
"Type",
"==",
"tmutils",
".",
"TableView",
"{",
"// Views will have {{.DatabaseName}} in there, replace",
"// it with _vt_preflight",
"s",
":=",
"strings",
".",
"Replace",
"(",
"td",
".",
"Schema",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"initialCopySQL",
"+=",
"s",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"mysqld",
".",
"executeSchemaCommands",
"(",
"initialCopySQL",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// For each change, record the schema before and after.",
"for",
"i",
",",
"change",
":=",
"range",
"changes",
"{",
"beforeSchema",
",",
"err",
":=",
"mysqld",
".",
"GetSchema",
"(",
"\"",
"\"",
",",
"nil",
",",
"nil",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// apply schema change to the temporary database",
"sql",
":=",
"\"",
"\\n",
"\"",
"\n",
"sql",
"+=",
"\"",
"\\n",
"\"",
"\n",
"sql",
"+=",
"change",
"\n",
"if",
"err",
"=",
"mysqld",
".",
"executeSchemaCommands",
"(",
"sql",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// get the result",
"afterSchema",
",",
"err",
":=",
"mysqld",
".",
"GetSchema",
"(",
"\"",
"\"",
",",
"nil",
",",
"nil",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"results",
"[",
"i",
"]",
"=",
"&",
"tabletmanagerdatapb",
".",
"SchemaChangeResult",
"{",
"BeforeSchema",
":",
"beforeSchema",
",",
"AfterSchema",
":",
"afterSchema",
"}",
"\n",
"}",
"\n\n",
"// and clean up the extra database",
"dropSQL",
":=",
"\"",
"\\n",
"\"",
"\n",
"dropSQL",
"+=",
"\"",
"\\n",
"\"",
"\n",
"if",
"err",
"=",
"mysqld",
".",
"executeSchemaCommands",
"(",
"dropSQL",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // PreflightSchemaChange checks the schema changes in "changes" by applying them
// to an intermediate database that has the same schema as the target database. | [
"PreflightSchemaChange",
"checks",
"the",
"schema",
"changes",
"in",
"changes",
"by",
"applying",
"them",
"to",
"an",
"intermediate",
"database",
"that",
"has",
"the",
"same",
"schema",
"as",
"the",
"target",
"database",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/schema.go#L233-L296 | train |
vitessio/vitess | go/vt/mysqlctl/schema.go | ApplySchemaChange | func (mysqld *Mysqld) ApplySchemaChange(dbName string, change *tmutils.SchemaChange) (*tabletmanagerdatapb.SchemaChangeResult, error) {
// check current schema matches
beforeSchema, err := mysqld.GetSchema(dbName, nil, nil, true)
if err != nil {
return nil, err
}
if change.BeforeSchema != nil {
schemaDiffs := tmutils.DiffSchemaToArray("actual", beforeSchema, "expected", change.BeforeSchema)
if len(schemaDiffs) > 0 {
for _, msg := range schemaDiffs {
log.Warningf("BeforeSchema differs: %v", msg)
}
// let's see if the schema was already applied
if change.AfterSchema != nil {
schemaDiffs = tmutils.DiffSchemaToArray("actual", beforeSchema, "expected", change.AfterSchema)
if len(schemaDiffs) == 0 {
// no diff between the schema we expect
// after the change and the current
// schema, we already applied it
return &tabletmanagerdatapb.SchemaChangeResult{
BeforeSchema: beforeSchema,
AfterSchema: beforeSchema}, nil
}
}
if change.Force {
log.Warningf("BeforeSchema differs, applying anyway")
} else {
return nil, fmt.Errorf("BeforeSchema differs")
}
}
}
sql := change.SQL
if !change.AllowReplication {
sql = "SET sql_log_bin = 0;\n" + sql
}
// add a 'use XXX' in front of the SQL
sql = fmt.Sprintf("USE %s;\n%s", sqlescape.EscapeID(dbName), sql)
// execute the schema change using an external mysql process
// (to benefit from the extra commands in mysql cli)
if err = mysqld.executeSchemaCommands(sql); err != nil {
return nil, err
}
// get AfterSchema
afterSchema, err := mysqld.GetSchema(dbName, nil, nil, true)
if err != nil {
return nil, err
}
// compare to the provided AfterSchema
if change.AfterSchema != nil {
schemaDiffs := tmutils.DiffSchemaToArray("actual", afterSchema, "expected", change.AfterSchema)
if len(schemaDiffs) > 0 {
for _, msg := range schemaDiffs {
log.Warningf("AfterSchema differs: %v", msg)
}
if change.Force {
log.Warningf("AfterSchema differs, not reporting error")
} else {
return nil, fmt.Errorf("AfterSchema differs")
}
}
}
return &tabletmanagerdatapb.SchemaChangeResult{BeforeSchema: beforeSchema, AfterSchema: afterSchema}, nil
} | go | func (mysqld *Mysqld) ApplySchemaChange(dbName string, change *tmutils.SchemaChange) (*tabletmanagerdatapb.SchemaChangeResult, error) {
// check current schema matches
beforeSchema, err := mysqld.GetSchema(dbName, nil, nil, true)
if err != nil {
return nil, err
}
if change.BeforeSchema != nil {
schemaDiffs := tmutils.DiffSchemaToArray("actual", beforeSchema, "expected", change.BeforeSchema)
if len(schemaDiffs) > 0 {
for _, msg := range schemaDiffs {
log.Warningf("BeforeSchema differs: %v", msg)
}
// let's see if the schema was already applied
if change.AfterSchema != nil {
schemaDiffs = tmutils.DiffSchemaToArray("actual", beforeSchema, "expected", change.AfterSchema)
if len(schemaDiffs) == 0 {
// no diff between the schema we expect
// after the change and the current
// schema, we already applied it
return &tabletmanagerdatapb.SchemaChangeResult{
BeforeSchema: beforeSchema,
AfterSchema: beforeSchema}, nil
}
}
if change.Force {
log.Warningf("BeforeSchema differs, applying anyway")
} else {
return nil, fmt.Errorf("BeforeSchema differs")
}
}
}
sql := change.SQL
if !change.AllowReplication {
sql = "SET sql_log_bin = 0;\n" + sql
}
// add a 'use XXX' in front of the SQL
sql = fmt.Sprintf("USE %s;\n%s", sqlescape.EscapeID(dbName), sql)
// execute the schema change using an external mysql process
// (to benefit from the extra commands in mysql cli)
if err = mysqld.executeSchemaCommands(sql); err != nil {
return nil, err
}
// get AfterSchema
afterSchema, err := mysqld.GetSchema(dbName, nil, nil, true)
if err != nil {
return nil, err
}
// compare to the provided AfterSchema
if change.AfterSchema != nil {
schemaDiffs := tmutils.DiffSchemaToArray("actual", afterSchema, "expected", change.AfterSchema)
if len(schemaDiffs) > 0 {
for _, msg := range schemaDiffs {
log.Warningf("AfterSchema differs: %v", msg)
}
if change.Force {
log.Warningf("AfterSchema differs, not reporting error")
} else {
return nil, fmt.Errorf("AfterSchema differs")
}
}
}
return &tabletmanagerdatapb.SchemaChangeResult{BeforeSchema: beforeSchema, AfterSchema: afterSchema}, nil
} | [
"func",
"(",
"mysqld",
"*",
"Mysqld",
")",
"ApplySchemaChange",
"(",
"dbName",
"string",
",",
"change",
"*",
"tmutils",
".",
"SchemaChange",
")",
"(",
"*",
"tabletmanagerdatapb",
".",
"SchemaChangeResult",
",",
"error",
")",
"{",
"// check current schema matches",
"beforeSchema",
",",
"err",
":=",
"mysqld",
".",
"GetSchema",
"(",
"dbName",
",",
"nil",
",",
"nil",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"change",
".",
"BeforeSchema",
"!=",
"nil",
"{",
"schemaDiffs",
":=",
"tmutils",
".",
"DiffSchemaToArray",
"(",
"\"",
"\"",
",",
"beforeSchema",
",",
"\"",
"\"",
",",
"change",
".",
"BeforeSchema",
")",
"\n",
"if",
"len",
"(",
"schemaDiffs",
")",
">",
"0",
"{",
"for",
"_",
",",
"msg",
":=",
"range",
"schemaDiffs",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"msg",
")",
"\n",
"}",
"\n\n",
"// let's see if the schema was already applied",
"if",
"change",
".",
"AfterSchema",
"!=",
"nil",
"{",
"schemaDiffs",
"=",
"tmutils",
".",
"DiffSchemaToArray",
"(",
"\"",
"\"",
",",
"beforeSchema",
",",
"\"",
"\"",
",",
"change",
".",
"AfterSchema",
")",
"\n",
"if",
"len",
"(",
"schemaDiffs",
")",
"==",
"0",
"{",
"// no diff between the schema we expect",
"// after the change and the current",
"// schema, we already applied it",
"return",
"&",
"tabletmanagerdatapb",
".",
"SchemaChangeResult",
"{",
"BeforeSchema",
":",
"beforeSchema",
",",
"AfterSchema",
":",
"beforeSchema",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"change",
".",
"Force",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"sql",
":=",
"change",
".",
"SQL",
"\n",
"if",
"!",
"change",
".",
"AllowReplication",
"{",
"sql",
"=",
"\"",
"\\n",
"\"",
"+",
"sql",
"\n",
"}",
"\n\n",
"// add a 'use XXX' in front of the SQL",
"sql",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"sqlescape",
".",
"EscapeID",
"(",
"dbName",
")",
",",
"sql",
")",
"\n\n",
"// execute the schema change using an external mysql process",
"// (to benefit from the extra commands in mysql cli)",
"if",
"err",
"=",
"mysqld",
".",
"executeSchemaCommands",
"(",
"sql",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// get AfterSchema",
"afterSchema",
",",
"err",
":=",
"mysqld",
".",
"GetSchema",
"(",
"dbName",
",",
"nil",
",",
"nil",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// compare to the provided AfterSchema",
"if",
"change",
".",
"AfterSchema",
"!=",
"nil",
"{",
"schemaDiffs",
":=",
"tmutils",
".",
"DiffSchemaToArray",
"(",
"\"",
"\"",
",",
"afterSchema",
",",
"\"",
"\"",
",",
"change",
".",
"AfterSchema",
")",
"\n",
"if",
"len",
"(",
"schemaDiffs",
")",
">",
"0",
"{",
"for",
"_",
",",
"msg",
":=",
"range",
"schemaDiffs",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
",",
"msg",
")",
"\n",
"}",
"\n",
"if",
"change",
".",
"Force",
"{",
"log",
".",
"Warningf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"tabletmanagerdatapb",
".",
"SchemaChangeResult",
"{",
"BeforeSchema",
":",
"beforeSchema",
",",
"AfterSchema",
":",
"afterSchema",
"}",
",",
"nil",
"\n",
"}"
] | // ApplySchemaChange will apply the schema change to the given database. | [
"ApplySchemaChange",
"will",
"apply",
"the",
"schema",
"change",
"to",
"the",
"given",
"database",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/schema.go#L299-L369 | train |
vitessio/vitess | go/vt/logutil/proto3.go | ProtoToTime | func ProtoToTime(ts *logutilpb.Time) time.Time {
if ts == nil {
// treat nil like the empty Timestamp
return time.Unix(0, 0).UTC()
}
return time.Unix(ts.Seconds, int64(ts.Nanoseconds)).UTC()
} | go | func ProtoToTime(ts *logutilpb.Time) time.Time {
if ts == nil {
// treat nil like the empty Timestamp
return time.Unix(0, 0).UTC()
}
return time.Unix(ts.Seconds, int64(ts.Nanoseconds)).UTC()
} | [
"func",
"ProtoToTime",
"(",
"ts",
"*",
"logutilpb",
".",
"Time",
")",
"time",
".",
"Time",
"{",
"if",
"ts",
"==",
"nil",
"{",
"// treat nil like the empty Timestamp",
"return",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
".",
"UTC",
"(",
")",
"\n",
"}",
"\n",
"return",
"time",
".",
"Unix",
"(",
"ts",
".",
"Seconds",
",",
"int64",
"(",
"ts",
".",
"Nanoseconds",
")",
")",
".",
"UTC",
"(",
")",
"\n",
"}"
] | // This file contains a few functions to help with proto3.
// ProtoToTime converts a logutilpb.Time to a time.Time.
// proto3 will eventually support timestamps, at which point we'll retire
// this.
//
// A nil pointer is like the empty timestamp. | [
"This",
"file",
"contains",
"a",
"few",
"functions",
"to",
"help",
"with",
"proto3",
".",
"ProtoToTime",
"converts",
"a",
"logutilpb",
".",
"Time",
"to",
"a",
"time",
".",
"Time",
".",
"proto3",
"will",
"eventually",
"support",
"timestamps",
"at",
"which",
"point",
"we",
"ll",
"retire",
"this",
".",
"A",
"nil",
"pointer",
"is",
"like",
"the",
"empty",
"timestamp",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/logutil/proto3.go#L32-L38 | train |
vitessio/vitess | go/vt/logutil/proto3.go | TimeToProto | func TimeToProto(t time.Time) *logutilpb.Time {
seconds := t.Unix()
nanos := int64(t.Sub(time.Unix(seconds, 0)))
return &logutilpb.Time{
Seconds: seconds,
Nanoseconds: int32(nanos),
}
} | go | func TimeToProto(t time.Time) *logutilpb.Time {
seconds := t.Unix()
nanos := int64(t.Sub(time.Unix(seconds, 0)))
return &logutilpb.Time{
Seconds: seconds,
Nanoseconds: int32(nanos),
}
} | [
"func",
"TimeToProto",
"(",
"t",
"time",
".",
"Time",
")",
"*",
"logutilpb",
".",
"Time",
"{",
"seconds",
":=",
"t",
".",
"Unix",
"(",
")",
"\n",
"nanos",
":=",
"int64",
"(",
"t",
".",
"Sub",
"(",
"time",
".",
"Unix",
"(",
"seconds",
",",
"0",
")",
")",
")",
"\n",
"return",
"&",
"logutilpb",
".",
"Time",
"{",
"Seconds",
":",
"seconds",
",",
"Nanoseconds",
":",
"int32",
"(",
"nanos",
")",
",",
"}",
"\n",
"}"
] | // TimeToProto converts the time.Time to a logutilpb.Time. | [
"TimeToProto",
"converts",
"the",
"time",
".",
"Time",
"to",
"a",
"logutilpb",
".",
"Time",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/logutil/proto3.go#L41-L48 | train |
vitessio/vitess | go/vt/worker/split_diff_cmd.go | shardsWithSources | func shardsWithSources(ctx context.Context, wr *wrangler.Wrangler) ([]map[string]string, error) {
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
keyspaces, err := wr.TopoServer().GetKeyspaces(shortCtx)
cancel()
if err != nil {
return nil, vterrors.Wrap(err, "failed to get list of keyspaces")
}
wg := sync.WaitGroup{}
mu := sync.Mutex{} // protects result
result := make([]map[string]string, 0, len(keyspaces))
rec := concurrency.AllErrorRecorder{}
for _, keyspace := range keyspaces {
wg.Add(1)
go func(keyspace string) {
defer wg.Done()
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
shards, err := wr.TopoServer().GetShardNames(shortCtx, keyspace)
cancel()
if err != nil {
rec.RecordError(vterrors.Wrapf(err, "failed to get list of shards for keyspace '%v'", keyspace))
return
}
for _, shard := range shards {
wg.Add(1)
go func(keyspace, shard string) {
defer wg.Done()
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
si, err := wr.TopoServer().GetShard(shortCtx, keyspace, shard)
cancel()
if err != nil {
rec.RecordError(vterrors.Wrapf(err, "failed to get details for shard '%v'", topoproto.KeyspaceShardString(keyspace, shard)))
return
}
if len(si.SourceShards) > 0 && len(si.SourceShards[0].Tables) == 0 {
mu.Lock()
result = append(result, map[string]string{
"Keyspace": keyspace,
"Shard": shard,
})
mu.Unlock()
}
}(keyspace, shard)
}
}(keyspace)
}
wg.Wait()
if rec.HasErrors() {
return nil, rec.Error()
}
if len(result) == 0 {
return nil, vterrors.New(vtrpc.Code_FAILED_PRECONDITION, "there are no shards with SourceShards")
}
return result, nil
} | go | func shardsWithSources(ctx context.Context, wr *wrangler.Wrangler) ([]map[string]string, error) {
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
keyspaces, err := wr.TopoServer().GetKeyspaces(shortCtx)
cancel()
if err != nil {
return nil, vterrors.Wrap(err, "failed to get list of keyspaces")
}
wg := sync.WaitGroup{}
mu := sync.Mutex{} // protects result
result := make([]map[string]string, 0, len(keyspaces))
rec := concurrency.AllErrorRecorder{}
for _, keyspace := range keyspaces {
wg.Add(1)
go func(keyspace string) {
defer wg.Done()
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
shards, err := wr.TopoServer().GetShardNames(shortCtx, keyspace)
cancel()
if err != nil {
rec.RecordError(vterrors.Wrapf(err, "failed to get list of shards for keyspace '%v'", keyspace))
return
}
for _, shard := range shards {
wg.Add(1)
go func(keyspace, shard string) {
defer wg.Done()
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
si, err := wr.TopoServer().GetShard(shortCtx, keyspace, shard)
cancel()
if err != nil {
rec.RecordError(vterrors.Wrapf(err, "failed to get details for shard '%v'", topoproto.KeyspaceShardString(keyspace, shard)))
return
}
if len(si.SourceShards) > 0 && len(si.SourceShards[0].Tables) == 0 {
mu.Lock()
result = append(result, map[string]string{
"Keyspace": keyspace,
"Shard": shard,
})
mu.Unlock()
}
}(keyspace, shard)
}
}(keyspace)
}
wg.Wait()
if rec.HasErrors() {
return nil, rec.Error()
}
if len(result) == 0 {
return nil, vterrors.New(vtrpc.Code_FAILED_PRECONDITION, "there are no shards with SourceShards")
}
return result, nil
} | [
"func",
"shardsWithSources",
"(",
"ctx",
"context",
".",
"Context",
",",
"wr",
"*",
"wrangler",
".",
"Wrangler",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"shortCtx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"ctx",
",",
"*",
"remoteActionsTimeout",
")",
"\n",
"keyspaces",
",",
"err",
":=",
"wr",
".",
"TopoServer",
"(",
")",
".",
"GetKeyspaces",
"(",
"shortCtx",
")",
"\n",
"cancel",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"mu",
":=",
"sync",
".",
"Mutex",
"{",
"}",
"// protects result",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"string",
",",
"0",
",",
"len",
"(",
"keyspaces",
")",
")",
"\n",
"rec",
":=",
"concurrency",
".",
"AllErrorRecorder",
"{",
"}",
"\n",
"for",
"_",
",",
"keyspace",
":=",
"range",
"keyspaces",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"keyspace",
"string",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"shortCtx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"ctx",
",",
"*",
"remoteActionsTimeout",
")",
"\n",
"shards",
",",
"err",
":=",
"wr",
".",
"TopoServer",
"(",
")",
".",
"GetShardNames",
"(",
"shortCtx",
",",
"keyspace",
")",
"\n",
"cancel",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rec",
".",
"RecordError",
"(",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"shard",
":=",
"range",
"shards",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"keyspace",
",",
"shard",
"string",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"shortCtx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"ctx",
",",
"*",
"remoteActionsTimeout",
")",
"\n",
"si",
",",
"err",
":=",
"wr",
".",
"TopoServer",
"(",
")",
".",
"GetShard",
"(",
"shortCtx",
",",
"keyspace",
",",
"shard",
")",
"\n",
"cancel",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rec",
".",
"RecordError",
"(",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"topoproto",
".",
"KeyspaceShardString",
"(",
"keyspace",
",",
"shard",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"si",
".",
"SourceShards",
")",
">",
"0",
"&&",
"len",
"(",
"si",
".",
"SourceShards",
"[",
"0",
"]",
".",
"Tables",
")",
"==",
"0",
"{",
"mu",
".",
"Lock",
"(",
")",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"keyspace",
",",
"\"",
"\"",
":",
"shard",
",",
"}",
")",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"}",
"(",
"keyspace",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"if",
"rec",
".",
"HasErrors",
"(",
")",
"{",
"return",
"nil",
",",
"rec",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"result",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"vterrors",
".",
"New",
"(",
"vtrpc",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // shardsWithSources returns all the shards that have SourceShards set
// with no Tables list. | [
"shardsWithSources",
"returns",
"all",
"the",
"shards",
"that",
"have",
"SourceShards",
"set",
"with",
"no",
"Tables",
"list",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/split_diff_cmd.go#L116-L172 | train |
vitessio/vitess | go/cmd/automation_client/automation_client.go | waitForClusterOp | func waitForClusterOp(client automationservicepb.AutomationClient, id string) (*automationpb.GetClusterOperationDetailsResponse, error) {
for {
req := &automationpb.GetClusterOperationDetailsRequest{
Id: id,
}
resp, err := client.GetClusterOperationDetails(context.Background(), req, grpc.FailFast(false))
if err != nil {
return nil, fmt.Errorf("failed to get ClusterOperation Details. Request: %v Error: %v", req, err)
}
switch resp.ClusterOp.State {
case automationpb.ClusterOperationState_UNKNOWN_CLUSTER_OPERATION_STATE:
return resp, fmt.Errorf("ClusterOperation is in an unknown state. Details: %v", resp)
case automationpb.ClusterOperationState_CLUSTER_OPERATION_DONE:
if resp.ClusterOp.Error != "" {
return resp, fmt.Errorf("ClusterOperation failed. Details:\n%v", proto.MarshalTextString(resp))
}
return resp, nil
}
time.Sleep(50 * time.Millisecond)
}
} | go | func waitForClusterOp(client automationservicepb.AutomationClient, id string) (*automationpb.GetClusterOperationDetailsResponse, error) {
for {
req := &automationpb.GetClusterOperationDetailsRequest{
Id: id,
}
resp, err := client.GetClusterOperationDetails(context.Background(), req, grpc.FailFast(false))
if err != nil {
return nil, fmt.Errorf("failed to get ClusterOperation Details. Request: %v Error: %v", req, err)
}
switch resp.ClusterOp.State {
case automationpb.ClusterOperationState_UNKNOWN_CLUSTER_OPERATION_STATE:
return resp, fmt.Errorf("ClusterOperation is in an unknown state. Details: %v", resp)
case automationpb.ClusterOperationState_CLUSTER_OPERATION_DONE:
if resp.ClusterOp.Error != "" {
return resp, fmt.Errorf("ClusterOperation failed. Details:\n%v", proto.MarshalTextString(resp))
}
return resp, nil
}
time.Sleep(50 * time.Millisecond)
}
} | [
"func",
"waitForClusterOp",
"(",
"client",
"automationservicepb",
".",
"AutomationClient",
",",
"id",
"string",
")",
"(",
"*",
"automationpb",
".",
"GetClusterOperationDetailsResponse",
",",
"error",
")",
"{",
"for",
"{",
"req",
":=",
"&",
"automationpb",
".",
"GetClusterOperationDetailsRequest",
"{",
"Id",
":",
"id",
",",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"client",
".",
"GetClusterOperationDetails",
"(",
"context",
".",
"Background",
"(",
")",
",",
"req",
",",
"grpc",
".",
"FailFast",
"(",
"false",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"req",
",",
"err",
")",
"\n",
"}",
"\n\n",
"switch",
"resp",
".",
"ClusterOp",
".",
"State",
"{",
"case",
"automationpb",
".",
"ClusterOperationState_UNKNOWN_CLUSTER_OPERATION_STATE",
":",
"return",
"resp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
")",
"\n",
"case",
"automationpb",
".",
"ClusterOperationState_CLUSTER_OPERATION_DONE",
":",
"if",
"resp",
".",
"ClusterOp",
".",
"Error",
"!=",
"\"",
"\"",
"{",
"return",
"resp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"proto",
".",
"MarshalTextString",
"(",
"resp",
")",
")",
"\n",
"}",
"\n",
"return",
"resp",
",",
"nil",
"\n",
"}",
"\n\n",
"time",
".",
"Sleep",
"(",
"50",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"}"
] | // waitForClusterOp polls and blocks until the ClusterOperation invocation specified by "id" has finished. If an error occurred, it will be returned. | [
"waitForClusterOp",
"polls",
"and",
"blocks",
"until",
"the",
"ClusterOperation",
"invocation",
"specified",
"by",
"id",
"has",
"finished",
".",
"If",
"an",
"error",
"occurred",
"it",
"will",
"be",
"returned",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cmd/automation_client/automation_client.go#L110-L133 | train |
vitessio/vitess | go/vt/topo/etcd2topo/server.go | NewServer | func NewServer(serverAddr, root string) (*Server, error) {
cli, err := clientv3.New(clientv3.Config{
Endpoints: strings.Split(serverAddr, ","),
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, err
}
return &Server{
cli: cli,
root: root,
}, nil
} | go | func NewServer(serverAddr, root string) (*Server, error) {
cli, err := clientv3.New(clientv3.Config{
Endpoints: strings.Split(serverAddr, ","),
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, err
}
return &Server{
cli: cli,
root: root,
}, nil
} | [
"func",
"NewServer",
"(",
"serverAddr",
",",
"root",
"string",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"cli",
",",
"err",
":=",
"clientv3",
".",
"New",
"(",
"clientv3",
".",
"Config",
"{",
"Endpoints",
":",
"strings",
".",
"Split",
"(",
"serverAddr",
",",
"\"",
"\"",
")",
",",
"DialTimeout",
":",
"5",
"*",
"time",
".",
"Second",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Server",
"{",
"cli",
":",
"cli",
",",
"root",
":",
"root",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewServer returns a new etcdtopo.Server. | [
"NewServer",
"returns",
"a",
"new",
"etcdtopo",
".",
"Server",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/etcd2topo/server.go#L75-L88 | train |
vitessio/vitess | go/mysql/streaming_query.go | Fields | func (c *Conn) Fields() ([]*querypb.Field, error) {
if c.fields == nil {
return nil, NewSQLError(CRCommandsOutOfSync, SSUnknownSQLState, "no streaming query in progress")
}
if len(c.fields) == 0 {
// The query returned an empty field list.
return nil, nil
}
return c.fields, nil
} | go | func (c *Conn) Fields() ([]*querypb.Field, error) {
if c.fields == nil {
return nil, NewSQLError(CRCommandsOutOfSync, SSUnknownSQLState, "no streaming query in progress")
}
if len(c.fields) == 0 {
// The query returned an empty field list.
return nil, nil
}
return c.fields, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Fields",
"(",
")",
"(",
"[",
"]",
"*",
"querypb",
".",
"Field",
",",
"error",
")",
"{",
"if",
"c",
".",
"fields",
"==",
"nil",
"{",
"return",
"nil",
",",
"NewSQLError",
"(",
"CRCommandsOutOfSync",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"c",
".",
"fields",
")",
"==",
"0",
"{",
"// The query returned an empty field list.",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"c",
".",
"fields",
",",
"nil",
"\n",
"}"
] | // Fields returns the fields for an ongoing streaming query. | [
"Fields",
"returns",
"the",
"fields",
"for",
"an",
"ongoing",
"streaming",
"query",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/streaming_query.go#L97-L106 | train |
vitessio/vitess | go/mysql/streaming_query.go | CloseResult | func (c *Conn) CloseResult() {
for c.fields != nil {
rows, err := c.FetchNext()
if err != nil || rows == nil {
// We either got an error, or got the last result.
c.fields = nil
}
}
} | go | func (c *Conn) CloseResult() {
for c.fields != nil {
rows, err := c.FetchNext()
if err != nil || rows == nil {
// We either got an error, or got the last result.
c.fields = nil
}
}
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"CloseResult",
"(",
")",
"{",
"for",
"c",
".",
"fields",
"!=",
"nil",
"{",
"rows",
",",
"err",
":=",
"c",
".",
"FetchNext",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"rows",
"==",
"nil",
"{",
"// We either got an error, or got the last result.",
"c",
".",
"fields",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // CloseResult can be used to terminate a streaming query
// early. It just drains the remaining values. | [
"CloseResult",
"can",
"be",
"used",
"to",
"terminate",
"a",
"streaming",
"query",
"early",
".",
"It",
"just",
"drains",
"the",
"remaining",
"values",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/streaming_query.go#L141-L149 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/subquery.go | newSubquery | func newSubquery(alias sqlparser.TableIdent, bldr builder) (*subquery, *symtab, error) {
sq := &subquery{
order: bldr.Order() + 1,
input: bldr,
esubquery: &engine.Subquery{},
}
// Create a 'table' that represents the subquery.
t := &table{
alias: sqlparser.TableName{Name: alias},
origin: sq,
}
// Create column symbols based on the result column names.
for _, rc := range bldr.ResultColumns() {
if _, ok := t.columns[rc.alias.Lowered()]; ok {
return nil, nil, fmt.Errorf("duplicate column names in subquery: %s", sqlparser.String(rc.alias))
}
t.addColumn(rc.alias, &column{origin: sq})
}
t.isAuthoritative = true
st := newSymtab()
// AddTable will not fail because symtab is empty.
_ = st.AddTable(t)
return sq, st, nil
} | go | func newSubquery(alias sqlparser.TableIdent, bldr builder) (*subquery, *symtab, error) {
sq := &subquery{
order: bldr.Order() + 1,
input: bldr,
esubquery: &engine.Subquery{},
}
// Create a 'table' that represents the subquery.
t := &table{
alias: sqlparser.TableName{Name: alias},
origin: sq,
}
// Create column symbols based on the result column names.
for _, rc := range bldr.ResultColumns() {
if _, ok := t.columns[rc.alias.Lowered()]; ok {
return nil, nil, fmt.Errorf("duplicate column names in subquery: %s", sqlparser.String(rc.alias))
}
t.addColumn(rc.alias, &column{origin: sq})
}
t.isAuthoritative = true
st := newSymtab()
// AddTable will not fail because symtab is empty.
_ = st.AddTable(t)
return sq, st, nil
} | [
"func",
"newSubquery",
"(",
"alias",
"sqlparser",
".",
"TableIdent",
",",
"bldr",
"builder",
")",
"(",
"*",
"subquery",
",",
"*",
"symtab",
",",
"error",
")",
"{",
"sq",
":=",
"&",
"subquery",
"{",
"order",
":",
"bldr",
".",
"Order",
"(",
")",
"+",
"1",
",",
"input",
":",
"bldr",
",",
"esubquery",
":",
"&",
"engine",
".",
"Subquery",
"{",
"}",
",",
"}",
"\n\n",
"// Create a 'table' that represents the subquery.",
"t",
":=",
"&",
"table",
"{",
"alias",
":",
"sqlparser",
".",
"TableName",
"{",
"Name",
":",
"alias",
"}",
",",
"origin",
":",
"sq",
",",
"}",
"\n\n",
"// Create column symbols based on the result column names.",
"for",
"_",
",",
"rc",
":=",
"range",
"bldr",
".",
"ResultColumns",
"(",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"t",
".",
"columns",
"[",
"rc",
".",
"alias",
".",
"Lowered",
"(",
")",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sqlparser",
".",
"String",
"(",
"rc",
".",
"alias",
")",
")",
"\n",
"}",
"\n",
"t",
".",
"addColumn",
"(",
"rc",
".",
"alias",
",",
"&",
"column",
"{",
"origin",
":",
"sq",
"}",
")",
"\n",
"}",
"\n",
"t",
".",
"isAuthoritative",
"=",
"true",
"\n",
"st",
":=",
"newSymtab",
"(",
")",
"\n",
"// AddTable will not fail because symtab is empty.",
"_",
"=",
"st",
".",
"AddTable",
"(",
"t",
")",
"\n",
"return",
"sq",
",",
"st",
",",
"nil",
"\n",
"}"
] | // newSubquery builds a new subquery. | [
"newSubquery",
"builds",
"a",
"new",
"subquery",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/subquery.go#L46-L71 | train |
vitessio/vitess | go/vt/sqlannotation/sqlannotation.go | AnnotateIfDML | func AnnotateIfDML(sql string, keyspaceIDs [][]byte) string {
if !sqlparser.IsDML(sql) {
return sql
}
if len(keyspaceIDs) == 1 {
return AddKeyspaceIDs(sql, keyspaceIDs, "")
}
filteredReplicationUnfriendlyStatementsCount.Add(1)
return sql + filteredReplicationUnfriendlyAnnotation
} | go | func AnnotateIfDML(sql string, keyspaceIDs [][]byte) string {
if !sqlparser.IsDML(sql) {
return sql
}
if len(keyspaceIDs) == 1 {
return AddKeyspaceIDs(sql, keyspaceIDs, "")
}
filteredReplicationUnfriendlyStatementsCount.Add(1)
return sql + filteredReplicationUnfriendlyAnnotation
} | [
"func",
"AnnotateIfDML",
"(",
"sql",
"string",
",",
"keyspaceIDs",
"[",
"]",
"[",
"]",
"byte",
")",
"string",
"{",
"if",
"!",
"sqlparser",
".",
"IsDML",
"(",
"sql",
")",
"{",
"return",
"sql",
"\n",
"}",
"\n",
"if",
"len",
"(",
"keyspaceIDs",
")",
"==",
"1",
"{",
"return",
"AddKeyspaceIDs",
"(",
"sql",
",",
"keyspaceIDs",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"filteredReplicationUnfriendlyStatementsCount",
".",
"Add",
"(",
"1",
")",
"\n",
"return",
"sql",
"+",
"filteredReplicationUnfriendlyAnnotation",
"\n",
"}"
] | // AnnotateIfDML annotates 'sql' based on 'keyspaceIDs'
//
// If 'sql' is not a DML statement no annotation is added.
// If 'sql' is a DML statement and contains exactly one keyspaceID
// it is used to annotate 'sql'
// Otherwise 'sql' is annotated as replication-unfriendly. | [
"AnnotateIfDML",
"annotates",
"sql",
"based",
"on",
"keyspaceIDs",
"If",
"sql",
"is",
"not",
"a",
"DML",
"statement",
"no",
"annotation",
"is",
"added",
".",
"If",
"sql",
"is",
"a",
"DML",
"statement",
"and",
"contains",
"exactly",
"one",
"keyspaceID",
"it",
"is",
"used",
"to",
"annotate",
"sql",
"Otherwise",
"sql",
"is",
"annotated",
"as",
"replication",
"-",
"unfriendly",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlannotation/sqlannotation.go#L52-L61 | train |
vitessio/vitess | go/vt/sqlannotation/sqlannotation.go | AddKeyspaceIDs | func AddKeyspaceIDs(sql string, keyspaceIDs [][]byte, marginComments string) string {
encodedIDs := make([][]byte, len(keyspaceIDs))
for i, src := range keyspaceIDs {
encodedIDs[i] = make([]byte, hex.EncodedLen(len(src)))
hex.Encode(encodedIDs[i], src)
}
return fmt.Sprintf("%s /* vtgate:: keyspace_id:%s */%s",
sql, bytes.Join(encodedIDs, []byte(",")), marginComments)
} | go | func AddKeyspaceIDs(sql string, keyspaceIDs [][]byte, marginComments string) string {
encodedIDs := make([][]byte, len(keyspaceIDs))
for i, src := range keyspaceIDs {
encodedIDs[i] = make([]byte, hex.EncodedLen(len(src)))
hex.Encode(encodedIDs[i], src)
}
return fmt.Sprintf("%s /* vtgate:: keyspace_id:%s */%s",
sql, bytes.Join(encodedIDs, []byte(",")), marginComments)
} | [
"func",
"AddKeyspaceIDs",
"(",
"sql",
"string",
",",
"keyspaceIDs",
"[",
"]",
"[",
"]",
"byte",
",",
"marginComments",
"string",
")",
"string",
"{",
"encodedIDs",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"len",
"(",
"keyspaceIDs",
")",
")",
"\n",
"for",
"i",
",",
"src",
":=",
"range",
"keyspaceIDs",
"{",
"encodedIDs",
"[",
"i",
"]",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"hex",
".",
"EncodedLen",
"(",
"len",
"(",
"src",
")",
")",
")",
"\n",
"hex",
".",
"Encode",
"(",
"encodedIDs",
"[",
"i",
"]",
",",
"src",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sql",
",",
"bytes",
".",
"Join",
"(",
"encodedIDs",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
",",
"marginComments",
")",
"\n",
"}"
] | // AddKeyspaceIDs returns a copy of 'sql' annotated
// with the given keyspace id. It also appends the
// additional marginComments, if any. | [
"AddKeyspaceIDs",
"returns",
"a",
"copy",
"of",
"sql",
"annotated",
"with",
"the",
"given",
"keyspace",
"id",
".",
"It",
"also",
"appends",
"the",
"additional",
"marginComments",
"if",
"any",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlannotation/sqlannotation.go#L66-L74 | train |
vitessio/vitess | go/vt/sqlannotation/sqlannotation.go | ExtractKeyspaceIDS | func ExtractKeyspaceIDS(sql string) (keyspaceIDs [][]byte, err error) {
_, comments := sqlparser.SplitMarginComments(sql)
keyspaceIDString, hasKeyspaceID := extractStringBetween(comments.Trailing, "/* vtgate:: keyspace_id:", " ")
hasUnfriendlyAnnotation := strings.Contains(sql, filteredReplicationUnfriendlyAnnotation)
if !hasKeyspaceID {
if hasUnfriendlyAnnotation {
return nil, &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDReplicationUnfriendlyError,
Message: fmt.Sprintf("Statement: %v", sql),
}
}
// No annotations.
return nil, &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDParseError,
Message: fmt.Sprintf("No annotation found in '%v'", sql),
}
}
if hasUnfriendlyAnnotation {
return nil, &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDParseError,
Message: fmt.Sprintf("Conflicting annotations in statement '%v'", sql),
}
}
ksidStr := strings.Split(keyspaceIDString, ",")
keyspaceIDs = make([][]byte, len(ksidStr))
for row, ksid := range ksidStr {
err = nil
keyspaceIDs[row], err = hex.DecodeString(ksid)
if err != nil {
keyspaceIDs[row] = nil
err = &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDParseError,
Message: fmt.Sprintf(
"Error parsing keyspace id value in statement: %v (%v)", sql, err),
}
}
}
return
} | go | func ExtractKeyspaceIDS(sql string) (keyspaceIDs [][]byte, err error) {
_, comments := sqlparser.SplitMarginComments(sql)
keyspaceIDString, hasKeyspaceID := extractStringBetween(comments.Trailing, "/* vtgate:: keyspace_id:", " ")
hasUnfriendlyAnnotation := strings.Contains(sql, filteredReplicationUnfriendlyAnnotation)
if !hasKeyspaceID {
if hasUnfriendlyAnnotation {
return nil, &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDReplicationUnfriendlyError,
Message: fmt.Sprintf("Statement: %v", sql),
}
}
// No annotations.
return nil, &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDParseError,
Message: fmt.Sprintf("No annotation found in '%v'", sql),
}
}
if hasUnfriendlyAnnotation {
return nil, &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDParseError,
Message: fmt.Sprintf("Conflicting annotations in statement '%v'", sql),
}
}
ksidStr := strings.Split(keyspaceIDString, ",")
keyspaceIDs = make([][]byte, len(ksidStr))
for row, ksid := range ksidStr {
err = nil
keyspaceIDs[row], err = hex.DecodeString(ksid)
if err != nil {
keyspaceIDs[row] = nil
err = &ExtractKeySpaceIDError{
Kind: ExtractKeySpaceIDParseError,
Message: fmt.Sprintf(
"Error parsing keyspace id value in statement: %v (%v)", sql, err),
}
}
}
return
} | [
"func",
"ExtractKeyspaceIDS",
"(",
"sql",
"string",
")",
"(",
"keyspaceIDs",
"[",
"]",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"_",
",",
"comments",
":=",
"sqlparser",
".",
"SplitMarginComments",
"(",
"sql",
")",
"\n",
"keyspaceIDString",
",",
"hasKeyspaceID",
":=",
"extractStringBetween",
"(",
"comments",
".",
"Trailing",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"hasUnfriendlyAnnotation",
":=",
"strings",
".",
"Contains",
"(",
"sql",
",",
"filteredReplicationUnfriendlyAnnotation",
")",
"\n",
"if",
"!",
"hasKeyspaceID",
"{",
"if",
"hasUnfriendlyAnnotation",
"{",
"return",
"nil",
",",
"&",
"ExtractKeySpaceIDError",
"{",
"Kind",
":",
"ExtractKeySpaceIDReplicationUnfriendlyError",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sql",
")",
",",
"}",
"\n",
"}",
"\n",
"// No annotations.",
"return",
"nil",
",",
"&",
"ExtractKeySpaceIDError",
"{",
"Kind",
":",
"ExtractKeySpaceIDParseError",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sql",
")",
",",
"}",
"\n",
"}",
"\n",
"if",
"hasUnfriendlyAnnotation",
"{",
"return",
"nil",
",",
"&",
"ExtractKeySpaceIDError",
"{",
"Kind",
":",
"ExtractKeySpaceIDParseError",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sql",
")",
",",
"}",
"\n",
"}",
"\n",
"ksidStr",
":=",
"strings",
".",
"Split",
"(",
"keyspaceIDString",
",",
"\"",
"\"",
")",
"\n",
"keyspaceIDs",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"len",
"(",
"ksidStr",
")",
")",
"\n",
"for",
"row",
",",
"ksid",
":=",
"range",
"ksidStr",
"{",
"err",
"=",
"nil",
"\n",
"keyspaceIDs",
"[",
"row",
"]",
",",
"err",
"=",
"hex",
".",
"DecodeString",
"(",
"ksid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"keyspaceIDs",
"[",
"row",
"]",
"=",
"nil",
"\n",
"err",
"=",
"&",
"ExtractKeySpaceIDError",
"{",
"Kind",
":",
"ExtractKeySpaceIDParseError",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sql",
",",
"err",
")",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // ExtractKeyspaceIDS parses the annotation of the given statement and tries
// to extract the keyspace id.
// If a keyspace-id comment exists 'keyspaceID' is set to the parsed keyspace id
// and err is set to nil; otherwise, if a filtered-replication-unfriendly comment exists
// or some other parsing error occured, keyspaceID is set to nil and err is set to a non-nil
// error value. | [
"ExtractKeyspaceIDS",
"parses",
"the",
"annotation",
"of",
"the",
"given",
"statement",
"and",
"tries",
"to",
"extract",
"the",
"keyspace",
"id",
".",
"If",
"a",
"keyspace",
"-",
"id",
"comment",
"exists",
"keyspaceID",
"is",
"set",
"to",
"the",
"parsed",
"keyspace",
"id",
"and",
"err",
"is",
"set",
"to",
"nil",
";",
"otherwise",
"if",
"a",
"filtered",
"-",
"replication",
"-",
"unfriendly",
"comment",
"exists",
"or",
"some",
"other",
"parsing",
"error",
"occured",
"keyspaceID",
"is",
"set",
"to",
"nil",
"and",
"err",
"is",
"set",
"to",
"a",
"non",
"-",
"nil",
"error",
"value",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlannotation/sqlannotation.go#L82-L120 | train |
vitessio/vitess | go/vt/sqlannotation/sqlannotation.go | extractStringBetween | func extractStringBetween(source string, leftDelim string, rightDelim string) (match string, found bool) {
leftDelimStart := strings.Index(source, leftDelim)
if leftDelimStart == -1 {
found = false
match = ""
return
}
found = true
matchStart := leftDelimStart + len(leftDelim)
matchEnd := strings.Index(source[matchStart:], rightDelim)
if matchEnd != -1 {
match = source[matchStart : matchStart+matchEnd]
return
}
match = source[matchStart:]
return
} | go | func extractStringBetween(source string, leftDelim string, rightDelim string) (match string, found bool) {
leftDelimStart := strings.Index(source, leftDelim)
if leftDelimStart == -1 {
found = false
match = ""
return
}
found = true
matchStart := leftDelimStart + len(leftDelim)
matchEnd := strings.Index(source[matchStart:], rightDelim)
if matchEnd != -1 {
match = source[matchStart : matchStart+matchEnd]
return
}
match = source[matchStart:]
return
} | [
"func",
"extractStringBetween",
"(",
"source",
"string",
",",
"leftDelim",
"string",
",",
"rightDelim",
"string",
")",
"(",
"match",
"string",
",",
"found",
"bool",
")",
"{",
"leftDelimStart",
":=",
"strings",
".",
"Index",
"(",
"source",
",",
"leftDelim",
")",
"\n",
"if",
"leftDelimStart",
"==",
"-",
"1",
"{",
"found",
"=",
"false",
"\n",
"match",
"=",
"\"",
"\"",
"\n",
"return",
"\n",
"}",
"\n",
"found",
"=",
"true",
"\n",
"matchStart",
":=",
"leftDelimStart",
"+",
"len",
"(",
"leftDelim",
")",
"\n",
"matchEnd",
":=",
"strings",
".",
"Index",
"(",
"source",
"[",
"matchStart",
":",
"]",
",",
"rightDelim",
")",
"\n",
"if",
"matchEnd",
"!=",
"-",
"1",
"{",
"match",
"=",
"source",
"[",
"matchStart",
":",
"matchStart",
"+",
"matchEnd",
"]",
"\n",
"return",
"\n",
"}",
"\n",
"match",
"=",
"source",
"[",
"matchStart",
":",
"]",
"\n",
"return",
"\n",
"}"
] | // Extracts the string from source contained between the leftmost instance of
// 'leftDelim' and the next instance of 'rightDelim'. If there is no next instance
// of 'rightDelim', returns the string contained between the end of the leftmost instance
// of 'leftDelim' to the end of 'source'. If 'leftDelim' does not appear in 'source',
// sets 'found' to false and 'match' to the empty string, otherwise 'found' is set to true
// and 'match' is set to the extracted string. | [
"Extracts",
"the",
"string",
"from",
"source",
"contained",
"between",
"the",
"leftmost",
"instance",
"of",
"leftDelim",
"and",
"the",
"next",
"instance",
"of",
"rightDelim",
".",
"If",
"there",
"is",
"no",
"next",
"instance",
"of",
"rightDelim",
"returns",
"the",
"string",
"contained",
"between",
"the",
"end",
"of",
"the",
"leftmost",
"instance",
"of",
"leftDelim",
"to",
"the",
"end",
"of",
"source",
".",
"If",
"leftDelim",
"does",
"not",
"appear",
"in",
"source",
"sets",
"found",
"to",
"false",
"and",
"match",
"to",
"the",
"empty",
"string",
"otherwise",
"found",
"is",
"set",
"to",
"true",
"and",
"match",
"is",
"set",
"to",
"the",
"extracted",
"string",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlannotation/sqlannotation.go#L128-L144 | train |
vitessio/vitess | go/ratelimiter/ratelimiter.go | Allow | func (rl *RateLimiter) Allow() bool {
rl.mu.Lock()
defer rl.mu.Unlock()
if time.Since(rl.lastTime) < rl.interval {
if rl.curCount > 0 {
rl.curCount--
return true
}
return false
}
rl.curCount = rl.maxCount - 1
rl.lastTime = time.Now()
return true
} | go | func (rl *RateLimiter) Allow() bool {
rl.mu.Lock()
defer rl.mu.Unlock()
if time.Since(rl.lastTime) < rl.interval {
if rl.curCount > 0 {
rl.curCount--
return true
}
return false
}
rl.curCount = rl.maxCount - 1
rl.lastTime = time.Now()
return true
} | [
"func",
"(",
"rl",
"*",
"RateLimiter",
")",
"Allow",
"(",
")",
"bool",
"{",
"rl",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rl",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"time",
".",
"Since",
"(",
"rl",
".",
"lastTime",
")",
"<",
"rl",
".",
"interval",
"{",
"if",
"rl",
".",
"curCount",
">",
"0",
"{",
"rl",
".",
"curCount",
"--",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"rl",
".",
"curCount",
"=",
"rl",
".",
"maxCount",
"-",
"1",
"\n",
"rl",
".",
"lastTime",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // Allow returns true if a request is within the rate limit norms.
// Otherwise, it returns false. | [
"Allow",
"returns",
"true",
"if",
"a",
"request",
"is",
"within",
"the",
"rate",
"limit",
"norms",
".",
"Otherwise",
"it",
"returns",
"false",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/ratelimiter/ratelimiter.go#L53-L66 | train |
vitessio/vitess | go/cmd/zk/zkcmd.go | cmdWatch | func cmdWatch(ctx context.Context, subFlags *flag.FlagSet, args []string) error {
subFlags.Parse(args)
eventChan := make(chan zk.Event, 16)
for _, arg := range subFlags.Args() {
zkPath := fixZkPath(arg)
_, _, watch, err := zconn.GetW(ctx, zkPath)
if err != nil {
return fmt.Errorf("watch error: %v", err)
}
go func() {
eventChan <- <-watch
}()
}
for {
select {
case <-ctx.Done():
return nil
case event := <-eventChan:
log.Infof("watch: event %v: %v", event.Path, event)
if event.Type == zk.EventNodeDataChanged {
data, stat, watch, err := zconn.GetW(ctx, event.Path)
if err != nil {
return fmt.Errorf("ERROR: failed to watch %v", err)
}
log.Infof("watch: %v %v\n", event.Path, stat)
println(data)
go func() {
eventChan <- <-watch
}()
} else if event.State == zk.StateDisconnected {
return nil
} else if event.Type == zk.EventNodeDeleted {
log.Infof("watch: %v deleted\n", event.Path)
} else {
// Most likely a session event - try t
_, _, watch, err := zconn.GetW(ctx, event.Path)
if err != nil {
return fmt.Errorf("ERROR: failed to watch %v", err)
}
go func() {
eventChan <- <-watch
}()
}
}
}
} | go | func cmdWatch(ctx context.Context, subFlags *flag.FlagSet, args []string) error {
subFlags.Parse(args)
eventChan := make(chan zk.Event, 16)
for _, arg := range subFlags.Args() {
zkPath := fixZkPath(arg)
_, _, watch, err := zconn.GetW(ctx, zkPath)
if err != nil {
return fmt.Errorf("watch error: %v", err)
}
go func() {
eventChan <- <-watch
}()
}
for {
select {
case <-ctx.Done():
return nil
case event := <-eventChan:
log.Infof("watch: event %v: %v", event.Path, event)
if event.Type == zk.EventNodeDataChanged {
data, stat, watch, err := zconn.GetW(ctx, event.Path)
if err != nil {
return fmt.Errorf("ERROR: failed to watch %v", err)
}
log.Infof("watch: %v %v\n", event.Path, stat)
println(data)
go func() {
eventChan <- <-watch
}()
} else if event.State == zk.StateDisconnected {
return nil
} else if event.Type == zk.EventNodeDeleted {
log.Infof("watch: %v deleted\n", event.Path)
} else {
// Most likely a session event - try t
_, _, watch, err := zconn.GetW(ctx, event.Path)
if err != nil {
return fmt.Errorf("ERROR: failed to watch %v", err)
}
go func() {
eventChan <- <-watch
}()
}
}
}
} | [
"func",
"cmdWatch",
"(",
"ctx",
"context",
".",
"Context",
",",
"subFlags",
"*",
"flag",
".",
"FlagSet",
",",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"subFlags",
".",
"Parse",
"(",
"args",
")",
"\n\n",
"eventChan",
":=",
"make",
"(",
"chan",
"zk",
".",
"Event",
",",
"16",
")",
"\n",
"for",
"_",
",",
"arg",
":=",
"range",
"subFlags",
".",
"Args",
"(",
")",
"{",
"zkPath",
":=",
"fixZkPath",
"(",
"arg",
")",
"\n",
"_",
",",
"_",
",",
"watch",
",",
"err",
":=",
"zconn",
".",
"GetW",
"(",
"ctx",
",",
"zkPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"eventChan",
"<-",
"<-",
"watch",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
"\n",
"case",
"event",
":=",
"<-",
"eventChan",
":",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"event",
".",
"Path",
",",
"event",
")",
"\n",
"if",
"event",
".",
"Type",
"==",
"zk",
".",
"EventNodeDataChanged",
"{",
"data",
",",
"stat",
",",
"watch",
",",
"err",
":=",
"zconn",
".",
"GetW",
"(",
"ctx",
",",
"event",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\\n",
"\"",
",",
"event",
".",
"Path",
",",
"stat",
")",
"\n",
"println",
"(",
"data",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"eventChan",
"<-",
"<-",
"watch",
"\n",
"}",
"(",
")",
"\n",
"}",
"else",
"if",
"event",
".",
"State",
"==",
"zk",
".",
"StateDisconnected",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"event",
".",
"Type",
"==",
"zk",
".",
"EventNodeDeleted",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\\n",
"\"",
",",
"event",
".",
"Path",
")",
"\n",
"}",
"else",
"{",
"// Most likely a session event - try t",
"_",
",",
"_",
",",
"watch",
",",
"err",
":=",
"zconn",
".",
"GetW",
"(",
"ctx",
",",
"event",
".",
"Path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"eventChan",
"<-",
"<-",
"watch",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Watch for changes to the node. | [
"Watch",
"for",
"changes",
"to",
"the",
"node",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cmd/zk/zkcmd.go#L227-L274 | train |
vitessio/vitess | go/cmd/zk/zkcmd.go | cmdZip | func cmdZip(ctx context.Context, subFlags *flag.FlagSet, args []string) error {
subFlags.Parse(args)
if subFlags.NArg() < 2 {
return fmt.Errorf("zip: need to specify source and destination paths")
}
dstPath := subFlags.Arg(subFlags.NArg() - 1)
paths := subFlags.Args()[:len(args)-1]
if !strings.HasSuffix(dstPath, ".zip") {
return fmt.Errorf("zip: need to specify destination .zip path: %v", dstPath)
}
zipFile, err := os.Create(dstPath)
if err != nil {
return fmt.Errorf("zip: error %v", err)
}
wg := sync.WaitGroup{}
items := make(chan *zkItem, 64)
for _, arg := range paths {
zkPath := fixZkPath(arg)
children, err := zk2topo.ChildrenRecursive(ctx, zconn, zkPath)
if err != nil {
return fmt.Errorf("zip: error %v", err)
}
for _, child := range children {
toAdd := path.Join(zkPath, child)
wg.Add(1)
go func() {
data, stat, err := zconn.Get(ctx, toAdd)
items <- &zkItem{toAdd, data, stat, err}
wg.Done()
}()
}
}
go func() {
wg.Wait()
close(items)
}()
zipWriter := zip.NewWriter(zipFile)
for item := range items {
path, data, stat, err := item.path, item.data, item.stat, item.err
if err != nil {
return fmt.Errorf("zip: get failed: %v", err)
}
// Skip ephemerals - not sure why you would archive them.
if stat.EphemeralOwner > 0 {
continue
}
fi := &zip.FileHeader{Name: path, Method: zip.Deflate}
fi.Modified = zk2topo.Time(stat.Mtime)
f, err := zipWriter.CreateHeader(fi)
if err != nil {
return fmt.Errorf("zip: create failed: %v", err)
}
_, err = f.Write(data)
if err != nil {
return fmt.Errorf("zip: create failed: %v", err)
}
}
err = zipWriter.Close()
if err != nil {
return fmt.Errorf("zip: close failed: %v", err)
}
zipFile.Close()
return nil
} | go | func cmdZip(ctx context.Context, subFlags *flag.FlagSet, args []string) error {
subFlags.Parse(args)
if subFlags.NArg() < 2 {
return fmt.Errorf("zip: need to specify source and destination paths")
}
dstPath := subFlags.Arg(subFlags.NArg() - 1)
paths := subFlags.Args()[:len(args)-1]
if !strings.HasSuffix(dstPath, ".zip") {
return fmt.Errorf("zip: need to specify destination .zip path: %v", dstPath)
}
zipFile, err := os.Create(dstPath)
if err != nil {
return fmt.Errorf("zip: error %v", err)
}
wg := sync.WaitGroup{}
items := make(chan *zkItem, 64)
for _, arg := range paths {
zkPath := fixZkPath(arg)
children, err := zk2topo.ChildrenRecursive(ctx, zconn, zkPath)
if err != nil {
return fmt.Errorf("zip: error %v", err)
}
for _, child := range children {
toAdd := path.Join(zkPath, child)
wg.Add(1)
go func() {
data, stat, err := zconn.Get(ctx, toAdd)
items <- &zkItem{toAdd, data, stat, err}
wg.Done()
}()
}
}
go func() {
wg.Wait()
close(items)
}()
zipWriter := zip.NewWriter(zipFile)
for item := range items {
path, data, stat, err := item.path, item.data, item.stat, item.err
if err != nil {
return fmt.Errorf("zip: get failed: %v", err)
}
// Skip ephemerals - not sure why you would archive them.
if stat.EphemeralOwner > 0 {
continue
}
fi := &zip.FileHeader{Name: path, Method: zip.Deflate}
fi.Modified = zk2topo.Time(stat.Mtime)
f, err := zipWriter.CreateHeader(fi)
if err != nil {
return fmt.Errorf("zip: create failed: %v", err)
}
_, err = f.Write(data)
if err != nil {
return fmt.Errorf("zip: create failed: %v", err)
}
}
err = zipWriter.Close()
if err != nil {
return fmt.Errorf("zip: close failed: %v", err)
}
zipFile.Close()
return nil
} | [
"func",
"cmdZip",
"(",
"ctx",
"context",
".",
"Context",
",",
"subFlags",
"*",
"flag",
".",
"FlagSet",
",",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"subFlags",
".",
"Parse",
"(",
"args",
")",
"\n",
"if",
"subFlags",
".",
"NArg",
"(",
")",
"<",
"2",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"dstPath",
":=",
"subFlags",
".",
"Arg",
"(",
"subFlags",
".",
"NArg",
"(",
")",
"-",
"1",
")",
"\n",
"paths",
":=",
"subFlags",
".",
"Args",
"(",
")",
"[",
":",
"len",
"(",
"args",
")",
"-",
"1",
"]",
"\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"dstPath",
",",
"\"",
"\"",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dstPath",
")",
"\n",
"}",
"\n",
"zipFile",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"dstPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"items",
":=",
"make",
"(",
"chan",
"*",
"zkItem",
",",
"64",
")",
"\n",
"for",
"_",
",",
"arg",
":=",
"range",
"paths",
"{",
"zkPath",
":=",
"fixZkPath",
"(",
"arg",
")",
"\n",
"children",
",",
"err",
":=",
"zk2topo",
".",
"ChildrenRecursive",
"(",
"ctx",
",",
"zconn",
",",
"zkPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"child",
":=",
"range",
"children",
"{",
"toAdd",
":=",
"path",
".",
"Join",
"(",
"zkPath",
",",
"child",
")",
"\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"data",
",",
"stat",
",",
"err",
":=",
"zconn",
".",
"Get",
"(",
"ctx",
",",
"toAdd",
")",
"\n",
"items",
"<-",
"&",
"zkItem",
"{",
"toAdd",
",",
"data",
",",
"stat",
",",
"err",
"}",
"\n",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"items",
")",
"\n",
"}",
"(",
")",
"\n\n",
"zipWriter",
":=",
"zip",
".",
"NewWriter",
"(",
"zipFile",
")",
"\n",
"for",
"item",
":=",
"range",
"items",
"{",
"path",
",",
"data",
",",
"stat",
",",
"err",
":=",
"item",
".",
"path",
",",
"item",
".",
"data",
",",
"item",
".",
"stat",
",",
"item",
".",
"err",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// Skip ephemerals - not sure why you would archive them.",
"if",
"stat",
".",
"EphemeralOwner",
">",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"fi",
":=",
"&",
"zip",
".",
"FileHeader",
"{",
"Name",
":",
"path",
",",
"Method",
":",
"zip",
".",
"Deflate",
"}",
"\n",
"fi",
".",
"Modified",
"=",
"zk2topo",
".",
"Time",
"(",
"stat",
".",
"Mtime",
")",
"\n",
"f",
",",
"err",
":=",
"zipWriter",
".",
"CreateHeader",
"(",
"fi",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"f",
".",
"Write",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"zipWriter",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"zipFile",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Store a zk tree in a zip archive. This won't be immediately useful to
// zip tools since even "directories" can contain data. | [
"Store",
"a",
"zk",
"tree",
"in",
"a",
"zip",
"archive",
".",
"This",
"won",
"t",
"be",
"immediately",
"useful",
"to",
"zip",
"tools",
"since",
"even",
"directories",
"can",
"contain",
"data",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cmd/zk/zkcmd.go#L865-L931 | train |
vitessio/vitess | go/sqltypes/event_token.go | EventTokenMinimum | func EventTokenMinimum(ev1, ev2 *querypb.EventToken) *querypb.EventToken {
if ev1 == nil || ev2 == nil {
// One or the other is not set, we can't do anything.
return nil
}
if ev1.Timestamp < ev2.Timestamp {
return &querypb.EventToken{
Timestamp: ev1.Timestamp,
}
}
return &querypb.EventToken{
Timestamp: ev2.Timestamp,
}
} | go | func EventTokenMinimum(ev1, ev2 *querypb.EventToken) *querypb.EventToken {
if ev1 == nil || ev2 == nil {
// One or the other is not set, we can't do anything.
return nil
}
if ev1.Timestamp < ev2.Timestamp {
return &querypb.EventToken{
Timestamp: ev1.Timestamp,
}
}
return &querypb.EventToken{
Timestamp: ev2.Timestamp,
}
} | [
"func",
"EventTokenMinimum",
"(",
"ev1",
",",
"ev2",
"*",
"querypb",
".",
"EventToken",
")",
"*",
"querypb",
".",
"EventToken",
"{",
"if",
"ev1",
"==",
"nil",
"||",
"ev2",
"==",
"nil",
"{",
"// One or the other is not set, we can't do anything.",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"ev1",
".",
"Timestamp",
"<",
"ev2",
".",
"Timestamp",
"{",
"return",
"&",
"querypb",
".",
"EventToken",
"{",
"Timestamp",
":",
"ev1",
".",
"Timestamp",
",",
"}",
"\n",
"}",
"\n",
"return",
"&",
"querypb",
".",
"EventToken",
"{",
"Timestamp",
":",
"ev2",
".",
"Timestamp",
",",
"}",
"\n",
"}"
] | // EventTokenMinimum returns an event token that is guaranteed to
// happen before both provided EventToken objects. Note it doesn't
// parse the position, but rather only uses the timestamp. This is
// meant to be used for EventToken objects coming from different
// source shard. | [
"EventTokenMinimum",
"returns",
"an",
"event",
"token",
"that",
"is",
"guaranteed",
"to",
"happen",
"before",
"both",
"provided",
"EventToken",
"objects",
".",
"Note",
"it",
"doesn",
"t",
"parse",
"the",
"position",
"but",
"rather",
"only",
"uses",
"the",
"timestamp",
".",
"This",
"is",
"meant",
"to",
"be",
"used",
"for",
"EventToken",
"objects",
"coming",
"from",
"different",
"source",
"shard",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/event_token.go#L28-L42 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/from.go | processDMLTable | func (pb *primitiveBuilder) processDMLTable(tableExprs sqlparser.TableExprs) (*routeOption, error) {
if err := pb.processTableExprs(tableExprs); err != nil {
return nil, err
}
rb, ok := pb.bldr.(*route)
if !ok {
return nil, errors.New("unsupported: multi-shard or vindex write statement")
}
ro := rb.routeOptions[0]
for _, sub := range ro.substitutions {
*sub.oldExpr = *sub.newExpr
}
return ro, nil
} | go | func (pb *primitiveBuilder) processDMLTable(tableExprs sqlparser.TableExprs) (*routeOption, error) {
if err := pb.processTableExprs(tableExprs); err != nil {
return nil, err
}
rb, ok := pb.bldr.(*route)
if !ok {
return nil, errors.New("unsupported: multi-shard or vindex write statement")
}
ro := rb.routeOptions[0]
for _, sub := range ro.substitutions {
*sub.oldExpr = *sub.newExpr
}
return ro, nil
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"processDMLTable",
"(",
"tableExprs",
"sqlparser",
".",
"TableExprs",
")",
"(",
"*",
"routeOption",
",",
"error",
")",
"{",
"if",
"err",
":=",
"pb",
".",
"processTableExprs",
"(",
"tableExprs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"rb",
",",
"ok",
":=",
"pb",
".",
"bldr",
".",
"(",
"*",
"route",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ro",
":=",
"rb",
".",
"routeOptions",
"[",
"0",
"]",
"\n",
"for",
"_",
",",
"sub",
":=",
"range",
"ro",
".",
"substitutions",
"{",
"*",
"sub",
".",
"oldExpr",
"=",
"*",
"sub",
".",
"newExpr",
"\n",
"}",
"\n",
"return",
"ro",
",",
"nil",
"\n",
"}"
] | // This file has functions to analyze the FROM clause.
// processDMLTable analyzes the FROM clause for DMLs and returns a routeOption. | [
"This",
"file",
"has",
"functions",
"to",
"analyze",
"the",
"FROM",
"clause",
".",
"processDMLTable",
"analyzes",
"the",
"FROM",
"clause",
"for",
"DMLs",
"and",
"returns",
"a",
"routeOption",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/from.go#L32-L45 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/from.go | processTableExprs | func (pb *primitiveBuilder) processTableExprs(tableExprs sqlparser.TableExprs) error {
if len(tableExprs) == 1 {
return pb.processTableExpr(tableExprs[0])
}
if err := pb.processTableExpr(tableExprs[0]); err != nil {
return err
}
rpb := newPrimitiveBuilder(pb.vschema, pb.jt)
if err := rpb.processTableExprs(tableExprs[1:]); err != nil {
return err
}
return pb.join(rpb, nil)
} | go | func (pb *primitiveBuilder) processTableExprs(tableExprs sqlparser.TableExprs) error {
if len(tableExprs) == 1 {
return pb.processTableExpr(tableExprs[0])
}
if err := pb.processTableExpr(tableExprs[0]); err != nil {
return err
}
rpb := newPrimitiveBuilder(pb.vschema, pb.jt)
if err := rpb.processTableExprs(tableExprs[1:]); err != nil {
return err
}
return pb.join(rpb, nil)
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"processTableExprs",
"(",
"tableExprs",
"sqlparser",
".",
"TableExprs",
")",
"error",
"{",
"if",
"len",
"(",
"tableExprs",
")",
"==",
"1",
"{",
"return",
"pb",
".",
"processTableExpr",
"(",
"tableExprs",
"[",
"0",
"]",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"pb",
".",
"processTableExpr",
"(",
"tableExprs",
"[",
"0",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rpb",
":=",
"newPrimitiveBuilder",
"(",
"pb",
".",
"vschema",
",",
"pb",
".",
"jt",
")",
"\n",
"if",
"err",
":=",
"rpb",
".",
"processTableExprs",
"(",
"tableExprs",
"[",
"1",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"pb",
".",
"join",
"(",
"rpb",
",",
"nil",
")",
"\n",
"}"
] | // processTableExprs analyzes the FROM clause. It produces a builder
// with all the routes identified. | [
"processTableExprs",
"analyzes",
"the",
"FROM",
"clause",
".",
"It",
"produces",
"a",
"builder",
"with",
"all",
"the",
"routes",
"identified",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/from.go#L49-L62 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/from.go | processTableExpr | func (pb *primitiveBuilder) processTableExpr(tableExpr sqlparser.TableExpr) error {
switch tableExpr := tableExpr.(type) {
case *sqlparser.AliasedTableExpr:
return pb.processAliasedTable(tableExpr)
case *sqlparser.ParenTableExpr:
err := pb.processTableExprs(tableExpr.Exprs)
// If it's a route, preserve the parenthesis so things
// don't associate differently when more things are pushed
// into it. FROM a, (b, c) should not become FROM a, b, c.
if rb, ok := pb.bldr.(*route); ok {
sel := rb.Select.(*sqlparser.Select)
sel.From = sqlparser.TableExprs{&sqlparser.ParenTableExpr{Exprs: sel.From}}
}
return err
case *sqlparser.JoinTableExpr:
return pb.processJoin(tableExpr)
}
panic(fmt.Sprintf("BUG: unexpected table expression type: %T", tableExpr))
} | go | func (pb *primitiveBuilder) processTableExpr(tableExpr sqlparser.TableExpr) error {
switch tableExpr := tableExpr.(type) {
case *sqlparser.AliasedTableExpr:
return pb.processAliasedTable(tableExpr)
case *sqlparser.ParenTableExpr:
err := pb.processTableExprs(tableExpr.Exprs)
// If it's a route, preserve the parenthesis so things
// don't associate differently when more things are pushed
// into it. FROM a, (b, c) should not become FROM a, b, c.
if rb, ok := pb.bldr.(*route); ok {
sel := rb.Select.(*sqlparser.Select)
sel.From = sqlparser.TableExprs{&sqlparser.ParenTableExpr{Exprs: sel.From}}
}
return err
case *sqlparser.JoinTableExpr:
return pb.processJoin(tableExpr)
}
panic(fmt.Sprintf("BUG: unexpected table expression type: %T", tableExpr))
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"processTableExpr",
"(",
"tableExpr",
"sqlparser",
".",
"TableExpr",
")",
"error",
"{",
"switch",
"tableExpr",
":=",
"tableExpr",
".",
"(",
"type",
")",
"{",
"case",
"*",
"sqlparser",
".",
"AliasedTableExpr",
":",
"return",
"pb",
".",
"processAliasedTable",
"(",
"tableExpr",
")",
"\n",
"case",
"*",
"sqlparser",
".",
"ParenTableExpr",
":",
"err",
":=",
"pb",
".",
"processTableExprs",
"(",
"tableExpr",
".",
"Exprs",
")",
"\n",
"// If it's a route, preserve the parenthesis so things",
"// don't associate differently when more things are pushed",
"// into it. FROM a, (b, c) should not become FROM a, b, c.",
"if",
"rb",
",",
"ok",
":=",
"pb",
".",
"bldr",
".",
"(",
"*",
"route",
")",
";",
"ok",
"{",
"sel",
":=",
"rb",
".",
"Select",
".",
"(",
"*",
"sqlparser",
".",
"Select",
")",
"\n",
"sel",
".",
"From",
"=",
"sqlparser",
".",
"TableExprs",
"{",
"&",
"sqlparser",
".",
"ParenTableExpr",
"{",
"Exprs",
":",
"sel",
".",
"From",
"}",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"case",
"*",
"sqlparser",
".",
"JoinTableExpr",
":",
"return",
"pb",
".",
"processJoin",
"(",
"tableExpr",
")",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tableExpr",
")",
")",
"\n",
"}"
] | // processTableExpr produces a builder subtree for the given TableExpr. | [
"processTableExpr",
"produces",
"a",
"builder",
"subtree",
"for",
"the",
"given",
"TableExpr",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/from.go#L65-L83 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/from.go | processAliasedTable | func (pb *primitiveBuilder) processAliasedTable(tableExpr *sqlparser.AliasedTableExpr) error {
switch expr := tableExpr.Expr.(type) {
case sqlparser.TableName:
return pb.buildTablePrimitive(tableExpr, expr)
case *sqlparser.Subquery:
spb := newPrimitiveBuilder(pb.vschema, pb.jt)
switch stmt := expr.Select.(type) {
case *sqlparser.Select:
if err := spb.processSelect(stmt, nil); err != nil {
return err
}
case *sqlparser.Union:
if err := spb.processUnion(stmt, nil); err != nil {
return err
}
default:
panic(fmt.Sprintf("BUG: unexpected SELECT type: %T", stmt))
}
subroute, ok := spb.bldr.(*route)
if !ok {
var err error
pb.bldr, pb.st, err = newSubquery(tableExpr.As, spb.bldr)
return err
}
// Since a route is more versatile than a subquery, we
// build a route primitive that has the subquery in its
// FROM clause. This allows for other constructs to be
// later pushed into it.
rb, st := newRoute(&sqlparser.Select{From: sqlparser.TableExprs([]sqlparser.TableExpr{tableExpr})})
// The subquery needs to be represented as a new logical table in the symtab.
// The new route will inherit the routeOptions of the underlying subquery.
// For this, we first build new vschema tables based on the columns returned
// by the subquery, and re-expose possible vindexes. When added to the symtab,
// a new set of column references will be generated against the new tables,
// and those vindex maps will be returned. They have to replace the old vindex
// maps of the inherited route options.
vschemaTables := make([]*vindexes.Table, 0, len(subroute.routeOptions))
for _, ro := range subroute.routeOptions {
vst := &vindexes.Table{
Keyspace: ro.eroute.Keyspace,
}
vschemaTables = append(vschemaTables, vst)
for _, rc := range subroute.ResultColumns() {
vindex, ok := ro.vindexMap[rc.column]
if !ok {
continue
}
// Check if a colvindex of the same name already exists.
// Dups are not allowed in subqueries in this situation.
for _, colVindex := range vst.ColumnVindexes {
if colVindex.Columns[0].Equal(rc.alias) {
return fmt.Errorf("duplicate column aliases: %v", rc.alias)
}
}
vst.ColumnVindexes = append(vst.ColumnVindexes, &vindexes.ColumnVindex{
Columns: []sqlparser.ColIdent{rc.alias},
Vindex: vindex,
})
}
}
vindexMaps, err := st.AddVSchemaTable(sqlparser.TableName{Name: tableExpr.As}, vschemaTables, rb)
if err != nil {
return err
}
for i, ro := range subroute.routeOptions {
ro.SubqueryToTable(rb, vindexMaps[i])
}
rb.routeOptions = subroute.routeOptions
subroute.Redirect = rb
pb.bldr, pb.st = rb, st
return nil
}
panic(fmt.Sprintf("BUG: unexpected table expression type: %T", tableExpr.Expr))
} | go | func (pb *primitiveBuilder) processAliasedTable(tableExpr *sqlparser.AliasedTableExpr) error {
switch expr := tableExpr.Expr.(type) {
case sqlparser.TableName:
return pb.buildTablePrimitive(tableExpr, expr)
case *sqlparser.Subquery:
spb := newPrimitiveBuilder(pb.vschema, pb.jt)
switch stmt := expr.Select.(type) {
case *sqlparser.Select:
if err := spb.processSelect(stmt, nil); err != nil {
return err
}
case *sqlparser.Union:
if err := spb.processUnion(stmt, nil); err != nil {
return err
}
default:
panic(fmt.Sprintf("BUG: unexpected SELECT type: %T", stmt))
}
subroute, ok := spb.bldr.(*route)
if !ok {
var err error
pb.bldr, pb.st, err = newSubquery(tableExpr.As, spb.bldr)
return err
}
// Since a route is more versatile than a subquery, we
// build a route primitive that has the subquery in its
// FROM clause. This allows for other constructs to be
// later pushed into it.
rb, st := newRoute(&sqlparser.Select{From: sqlparser.TableExprs([]sqlparser.TableExpr{tableExpr})})
// The subquery needs to be represented as a new logical table in the symtab.
// The new route will inherit the routeOptions of the underlying subquery.
// For this, we first build new vschema tables based on the columns returned
// by the subquery, and re-expose possible vindexes. When added to the symtab,
// a new set of column references will be generated against the new tables,
// and those vindex maps will be returned. They have to replace the old vindex
// maps of the inherited route options.
vschemaTables := make([]*vindexes.Table, 0, len(subroute.routeOptions))
for _, ro := range subroute.routeOptions {
vst := &vindexes.Table{
Keyspace: ro.eroute.Keyspace,
}
vschemaTables = append(vschemaTables, vst)
for _, rc := range subroute.ResultColumns() {
vindex, ok := ro.vindexMap[rc.column]
if !ok {
continue
}
// Check if a colvindex of the same name already exists.
// Dups are not allowed in subqueries in this situation.
for _, colVindex := range vst.ColumnVindexes {
if colVindex.Columns[0].Equal(rc.alias) {
return fmt.Errorf("duplicate column aliases: %v", rc.alias)
}
}
vst.ColumnVindexes = append(vst.ColumnVindexes, &vindexes.ColumnVindex{
Columns: []sqlparser.ColIdent{rc.alias},
Vindex: vindex,
})
}
}
vindexMaps, err := st.AddVSchemaTable(sqlparser.TableName{Name: tableExpr.As}, vschemaTables, rb)
if err != nil {
return err
}
for i, ro := range subroute.routeOptions {
ro.SubqueryToTable(rb, vindexMaps[i])
}
rb.routeOptions = subroute.routeOptions
subroute.Redirect = rb
pb.bldr, pb.st = rb, st
return nil
}
panic(fmt.Sprintf("BUG: unexpected table expression type: %T", tableExpr.Expr))
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"processAliasedTable",
"(",
"tableExpr",
"*",
"sqlparser",
".",
"AliasedTableExpr",
")",
"error",
"{",
"switch",
"expr",
":=",
"tableExpr",
".",
"Expr",
".",
"(",
"type",
")",
"{",
"case",
"sqlparser",
".",
"TableName",
":",
"return",
"pb",
".",
"buildTablePrimitive",
"(",
"tableExpr",
",",
"expr",
")",
"\n",
"case",
"*",
"sqlparser",
".",
"Subquery",
":",
"spb",
":=",
"newPrimitiveBuilder",
"(",
"pb",
".",
"vschema",
",",
"pb",
".",
"jt",
")",
"\n",
"switch",
"stmt",
":=",
"expr",
".",
"Select",
".",
"(",
"type",
")",
"{",
"case",
"*",
"sqlparser",
".",
"Select",
":",
"if",
"err",
":=",
"spb",
".",
"processSelect",
"(",
"stmt",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"case",
"*",
"sqlparser",
".",
"Union",
":",
"if",
"err",
":=",
"spb",
".",
"processUnion",
"(",
"stmt",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"stmt",
")",
")",
"\n",
"}",
"\n\n",
"subroute",
",",
"ok",
":=",
"spb",
".",
"bldr",
".",
"(",
"*",
"route",
")",
"\n",
"if",
"!",
"ok",
"{",
"var",
"err",
"error",
"\n",
"pb",
".",
"bldr",
",",
"pb",
".",
"st",
",",
"err",
"=",
"newSubquery",
"(",
"tableExpr",
".",
"As",
",",
"spb",
".",
"bldr",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Since a route is more versatile than a subquery, we",
"// build a route primitive that has the subquery in its",
"// FROM clause. This allows for other constructs to be",
"// later pushed into it.",
"rb",
",",
"st",
":=",
"newRoute",
"(",
"&",
"sqlparser",
".",
"Select",
"{",
"From",
":",
"sqlparser",
".",
"TableExprs",
"(",
"[",
"]",
"sqlparser",
".",
"TableExpr",
"{",
"tableExpr",
"}",
")",
"}",
")",
"\n\n",
"// The subquery needs to be represented as a new logical table in the symtab.",
"// The new route will inherit the routeOptions of the underlying subquery.",
"// For this, we first build new vschema tables based on the columns returned",
"// by the subquery, and re-expose possible vindexes. When added to the symtab,",
"// a new set of column references will be generated against the new tables,",
"// and those vindex maps will be returned. They have to replace the old vindex",
"// maps of the inherited route options.",
"vschemaTables",
":=",
"make",
"(",
"[",
"]",
"*",
"vindexes",
".",
"Table",
",",
"0",
",",
"len",
"(",
"subroute",
".",
"routeOptions",
")",
")",
"\n",
"for",
"_",
",",
"ro",
":=",
"range",
"subroute",
".",
"routeOptions",
"{",
"vst",
":=",
"&",
"vindexes",
".",
"Table",
"{",
"Keyspace",
":",
"ro",
".",
"eroute",
".",
"Keyspace",
",",
"}",
"\n",
"vschemaTables",
"=",
"append",
"(",
"vschemaTables",
",",
"vst",
")",
"\n",
"for",
"_",
",",
"rc",
":=",
"range",
"subroute",
".",
"ResultColumns",
"(",
")",
"{",
"vindex",
",",
"ok",
":=",
"ro",
".",
"vindexMap",
"[",
"rc",
".",
"column",
"]",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"// Check if a colvindex of the same name already exists.",
"// Dups are not allowed in subqueries in this situation.",
"for",
"_",
",",
"colVindex",
":=",
"range",
"vst",
".",
"ColumnVindexes",
"{",
"if",
"colVindex",
".",
"Columns",
"[",
"0",
"]",
".",
"Equal",
"(",
"rc",
".",
"alias",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rc",
".",
"alias",
")",
"\n",
"}",
"\n",
"}",
"\n",
"vst",
".",
"ColumnVindexes",
"=",
"append",
"(",
"vst",
".",
"ColumnVindexes",
",",
"&",
"vindexes",
".",
"ColumnVindex",
"{",
"Columns",
":",
"[",
"]",
"sqlparser",
".",
"ColIdent",
"{",
"rc",
".",
"alias",
"}",
",",
"Vindex",
":",
"vindex",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"vindexMaps",
",",
"err",
":=",
"st",
".",
"AddVSchemaTable",
"(",
"sqlparser",
".",
"TableName",
"{",
"Name",
":",
"tableExpr",
".",
"As",
"}",
",",
"vschemaTables",
",",
"rb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"i",
",",
"ro",
":=",
"range",
"subroute",
".",
"routeOptions",
"{",
"ro",
".",
"SubqueryToTable",
"(",
"rb",
",",
"vindexMaps",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"rb",
".",
"routeOptions",
"=",
"subroute",
".",
"routeOptions",
"\n",
"subroute",
".",
"Redirect",
"=",
"rb",
"\n",
"pb",
".",
"bldr",
",",
"pb",
".",
"st",
"=",
"rb",
",",
"st",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tableExpr",
".",
"Expr",
")",
")",
"\n",
"}"
] | // processAliasedTable produces a builder subtree for the given AliasedTableExpr.
// If the expression is a subquery, then the primitive will create a table
// for it in the symtab. If the subquery is a route, then we build a route
// primitive with the subquery in the From clause, because a route is more
// versatile than a subquery. If a subquery becomes a route, then any result
// columns that represent underlying vindex columns are also exposed as
// vindex columns. | [
"processAliasedTable",
"produces",
"a",
"builder",
"subtree",
"for",
"the",
"given",
"AliasedTableExpr",
".",
"If",
"the",
"expression",
"is",
"a",
"subquery",
"then",
"the",
"primitive",
"will",
"create",
"a",
"table",
"for",
"it",
"in",
"the",
"symtab",
".",
"If",
"the",
"subquery",
"is",
"a",
"route",
"then",
"we",
"build",
"a",
"route",
"primitive",
"with",
"the",
"subquery",
"in",
"the",
"From",
"clause",
"because",
"a",
"route",
"is",
"more",
"versatile",
"than",
"a",
"subquery",
".",
"If",
"a",
"subquery",
"becomes",
"a",
"route",
"then",
"any",
"result",
"columns",
"that",
"represent",
"underlying",
"vindex",
"columns",
"are",
"also",
"exposed",
"as",
"vindex",
"columns",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/from.go#L92-L168 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/from.go | processJoin | func (pb *primitiveBuilder) processJoin(ajoin *sqlparser.JoinTableExpr) error {
switch ajoin.Join {
case sqlparser.JoinStr, sqlparser.StraightJoinStr, sqlparser.LeftJoinStr:
case sqlparser.RightJoinStr:
convertToLeftJoin(ajoin)
default:
return fmt.Errorf("unsupported: %s", ajoin.Join)
}
if err := pb.processTableExpr(ajoin.LeftExpr); err != nil {
return err
}
rpb := newPrimitiveBuilder(pb.vschema, pb.jt)
if err := rpb.processTableExpr(ajoin.RightExpr); err != nil {
return err
}
return pb.join(rpb, ajoin)
} | go | func (pb *primitiveBuilder) processJoin(ajoin *sqlparser.JoinTableExpr) error {
switch ajoin.Join {
case sqlparser.JoinStr, sqlparser.StraightJoinStr, sqlparser.LeftJoinStr:
case sqlparser.RightJoinStr:
convertToLeftJoin(ajoin)
default:
return fmt.Errorf("unsupported: %s", ajoin.Join)
}
if err := pb.processTableExpr(ajoin.LeftExpr); err != nil {
return err
}
rpb := newPrimitiveBuilder(pb.vschema, pb.jt)
if err := rpb.processTableExpr(ajoin.RightExpr); err != nil {
return err
}
return pb.join(rpb, ajoin)
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"processJoin",
"(",
"ajoin",
"*",
"sqlparser",
".",
"JoinTableExpr",
")",
"error",
"{",
"switch",
"ajoin",
".",
"Join",
"{",
"case",
"sqlparser",
".",
"JoinStr",
",",
"sqlparser",
".",
"StraightJoinStr",
",",
"sqlparser",
".",
"LeftJoinStr",
":",
"case",
"sqlparser",
".",
"RightJoinStr",
":",
"convertToLeftJoin",
"(",
"ajoin",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ajoin",
".",
"Join",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"pb",
".",
"processTableExpr",
"(",
"ajoin",
".",
"LeftExpr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rpb",
":=",
"newPrimitiveBuilder",
"(",
"pb",
".",
"vschema",
",",
"pb",
".",
"jt",
")",
"\n",
"if",
"err",
":=",
"rpb",
".",
"processTableExpr",
"(",
"ajoin",
".",
"RightExpr",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"pb",
".",
"join",
"(",
"rpb",
",",
"ajoin",
")",
"\n",
"}"
] | // processJoin produces a builder subtree for the given Join.
// If the left and right nodes can be part of the same route,
// then it's a route. Otherwise, it's a join. | [
"processJoin",
"produces",
"a",
"builder",
"subtree",
"for",
"the",
"given",
"Join",
".",
"If",
"the",
"left",
"and",
"right",
"nodes",
"can",
"be",
"part",
"of",
"the",
"same",
"route",
"then",
"it",
"s",
"a",
"route",
".",
"Otherwise",
"it",
"s",
"a",
"join",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/from.go#L254-L270 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/from.go | convertToLeftJoin | func convertToLeftJoin(ajoin *sqlparser.JoinTableExpr) {
newRHS := ajoin.LeftExpr
// If the LHS is a join, we have to parenthesize it.
// Otherwise, it can be used as is.
if _, ok := newRHS.(*sqlparser.JoinTableExpr); ok {
newRHS = &sqlparser.ParenTableExpr{
Exprs: sqlparser.TableExprs{newRHS},
}
}
ajoin.LeftExpr, ajoin.RightExpr = ajoin.RightExpr, newRHS
ajoin.Join = sqlparser.LeftJoinStr
} | go | func convertToLeftJoin(ajoin *sqlparser.JoinTableExpr) {
newRHS := ajoin.LeftExpr
// If the LHS is a join, we have to parenthesize it.
// Otherwise, it can be used as is.
if _, ok := newRHS.(*sqlparser.JoinTableExpr); ok {
newRHS = &sqlparser.ParenTableExpr{
Exprs: sqlparser.TableExprs{newRHS},
}
}
ajoin.LeftExpr, ajoin.RightExpr = ajoin.RightExpr, newRHS
ajoin.Join = sqlparser.LeftJoinStr
} | [
"func",
"convertToLeftJoin",
"(",
"ajoin",
"*",
"sqlparser",
".",
"JoinTableExpr",
")",
"{",
"newRHS",
":=",
"ajoin",
".",
"LeftExpr",
"\n",
"// If the LHS is a join, we have to parenthesize it.",
"// Otherwise, it can be used as is.",
"if",
"_",
",",
"ok",
":=",
"newRHS",
".",
"(",
"*",
"sqlparser",
".",
"JoinTableExpr",
")",
";",
"ok",
"{",
"newRHS",
"=",
"&",
"sqlparser",
".",
"ParenTableExpr",
"{",
"Exprs",
":",
"sqlparser",
".",
"TableExprs",
"{",
"newRHS",
"}",
",",
"}",
"\n",
"}",
"\n",
"ajoin",
".",
"LeftExpr",
",",
"ajoin",
".",
"RightExpr",
"=",
"ajoin",
".",
"RightExpr",
",",
"newRHS",
"\n",
"ajoin",
".",
"Join",
"=",
"sqlparser",
".",
"LeftJoinStr",
"\n",
"}"
] | // convertToLeftJoin converts a right join into a left join. | [
"convertToLeftJoin",
"converts",
"a",
"right",
"join",
"into",
"a",
"left",
"join",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/from.go#L273-L284 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/from.go | mergeRoutes | func (pb *primitiveBuilder) mergeRoutes(rpb *primitiveBuilder, routeOptions []*routeOption, ajoin *sqlparser.JoinTableExpr) error {
lRoute := pb.bldr.(*route)
rRoute := rpb.bldr.(*route)
sel := lRoute.Select.(*sqlparser.Select)
if ajoin == nil {
rhsSel := rRoute.Select.(*sqlparser.Select)
sel.From = append(sel.From, rhsSel.From...)
} else {
sel.From = sqlparser.TableExprs{ajoin}
}
rRoute.Redirect = lRoute
// Since the routes have merged, set st.singleRoute to point at
// the merged route.
pb.st.singleRoute = lRoute
lRoute.routeOptions = routeOptions
if ajoin == nil {
return nil
}
pullouts, _, expr, err := pb.findOrigin(ajoin.Condition.On)
if err != nil {
return err
}
ajoin.Condition.On = expr
pb.addPullouts(pullouts)
for _, filter := range splitAndExpression(nil, ajoin.Condition.On) {
lRoute.UpdatePlans(pb, filter)
}
return nil
} | go | func (pb *primitiveBuilder) mergeRoutes(rpb *primitiveBuilder, routeOptions []*routeOption, ajoin *sqlparser.JoinTableExpr) error {
lRoute := pb.bldr.(*route)
rRoute := rpb.bldr.(*route)
sel := lRoute.Select.(*sqlparser.Select)
if ajoin == nil {
rhsSel := rRoute.Select.(*sqlparser.Select)
sel.From = append(sel.From, rhsSel.From...)
} else {
sel.From = sqlparser.TableExprs{ajoin}
}
rRoute.Redirect = lRoute
// Since the routes have merged, set st.singleRoute to point at
// the merged route.
pb.st.singleRoute = lRoute
lRoute.routeOptions = routeOptions
if ajoin == nil {
return nil
}
pullouts, _, expr, err := pb.findOrigin(ajoin.Condition.On)
if err != nil {
return err
}
ajoin.Condition.On = expr
pb.addPullouts(pullouts)
for _, filter := range splitAndExpression(nil, ajoin.Condition.On) {
lRoute.UpdatePlans(pb, filter)
}
return nil
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"mergeRoutes",
"(",
"rpb",
"*",
"primitiveBuilder",
",",
"routeOptions",
"[",
"]",
"*",
"routeOption",
",",
"ajoin",
"*",
"sqlparser",
".",
"JoinTableExpr",
")",
"error",
"{",
"lRoute",
":=",
"pb",
".",
"bldr",
".",
"(",
"*",
"route",
")",
"\n",
"rRoute",
":=",
"rpb",
".",
"bldr",
".",
"(",
"*",
"route",
")",
"\n",
"sel",
":=",
"lRoute",
".",
"Select",
".",
"(",
"*",
"sqlparser",
".",
"Select",
")",
"\n\n",
"if",
"ajoin",
"==",
"nil",
"{",
"rhsSel",
":=",
"rRoute",
".",
"Select",
".",
"(",
"*",
"sqlparser",
".",
"Select",
")",
"\n",
"sel",
".",
"From",
"=",
"append",
"(",
"sel",
".",
"From",
",",
"rhsSel",
".",
"From",
"...",
")",
"\n",
"}",
"else",
"{",
"sel",
".",
"From",
"=",
"sqlparser",
".",
"TableExprs",
"{",
"ajoin",
"}",
"\n",
"}",
"\n",
"rRoute",
".",
"Redirect",
"=",
"lRoute",
"\n",
"// Since the routes have merged, set st.singleRoute to point at",
"// the merged route.",
"pb",
".",
"st",
".",
"singleRoute",
"=",
"lRoute",
"\n",
"lRoute",
".",
"routeOptions",
"=",
"routeOptions",
"\n",
"if",
"ajoin",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"pullouts",
",",
"_",
",",
"expr",
",",
"err",
":=",
"pb",
".",
"findOrigin",
"(",
"ajoin",
".",
"Condition",
".",
"On",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"ajoin",
".",
"Condition",
".",
"On",
"=",
"expr",
"\n",
"pb",
".",
"addPullouts",
"(",
"pullouts",
")",
"\n",
"for",
"_",
",",
"filter",
":=",
"range",
"splitAndExpression",
"(",
"nil",
",",
"ajoin",
".",
"Condition",
".",
"On",
")",
"{",
"lRoute",
".",
"UpdatePlans",
"(",
"pb",
",",
"filter",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // mergeRoutes merges the two routes. The ON clause is also analyzed to
// see if the primitive can be improved. The operation can fail if
// the expression contains a non-pushable subquery. ajoin can be nil
// if the join is on a ',' operator. | [
"mergeRoutes",
"merges",
"the",
"two",
"routes",
".",
"The",
"ON",
"clause",
"is",
"also",
"analyzed",
"to",
"see",
"if",
"the",
"primitive",
"can",
"be",
"improved",
".",
"The",
"operation",
"can",
"fail",
"if",
"the",
"expression",
"contains",
"a",
"non",
"-",
"pushable",
"subquery",
".",
"ajoin",
"can",
"be",
"nil",
"if",
"the",
"join",
"is",
"on",
"a",
"operator",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/from.go#L326-L355 | train |
vitessio/vitess | go/vt/vttablet/sysloglogger/sysloglogger.go | run | func run() {
log.Info("Logging queries to syslog")
defer writer.Close()
// ch will only be non-nil in a unit test context, when a mock has been populated
if ch == nil {
ch = tabletenv.StatsLogger.Subscribe("gwslog")
defer tabletenv.StatsLogger.Unsubscribe(ch)
}
formatParams := map[string][]string{"full": {}}
for out := range ch {
stats, ok := out.(*tabletenv.LogStats)
if !ok {
log.Errorf("Unexpected value in query logs: %#v (expecting value of type %T)", out, &tabletenv.LogStats{})
continue
}
var b bytes.Buffer
if err := stats.Logf(&b, formatParams); err != nil {
log.Errorf("Error formatting logStats: %v", err)
continue
}
if err := writer.Info(b.String()); err != nil {
log.Errorf("Error writing to syslog: %v", err)
continue
}
}
} | go | func run() {
log.Info("Logging queries to syslog")
defer writer.Close()
// ch will only be non-nil in a unit test context, when a mock has been populated
if ch == nil {
ch = tabletenv.StatsLogger.Subscribe("gwslog")
defer tabletenv.StatsLogger.Unsubscribe(ch)
}
formatParams := map[string][]string{"full": {}}
for out := range ch {
stats, ok := out.(*tabletenv.LogStats)
if !ok {
log.Errorf("Unexpected value in query logs: %#v (expecting value of type %T)", out, &tabletenv.LogStats{})
continue
}
var b bytes.Buffer
if err := stats.Logf(&b, formatParams); err != nil {
log.Errorf("Error formatting logStats: %v", err)
continue
}
if err := writer.Info(b.String()); err != nil {
log.Errorf("Error writing to syslog: %v", err)
continue
}
}
} | [
"func",
"run",
"(",
")",
"{",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"defer",
"writer",
".",
"Close",
"(",
")",
"\n\n",
"// ch will only be non-nil in a unit test context, when a mock has been populated",
"if",
"ch",
"==",
"nil",
"{",
"ch",
"=",
"tabletenv",
".",
"StatsLogger",
".",
"Subscribe",
"(",
"\"",
"\"",
")",
"\n",
"defer",
"tabletenv",
".",
"StatsLogger",
".",
"Unsubscribe",
"(",
"ch",
")",
"\n",
"}",
"\n\n",
"formatParams",
":=",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"\"",
"\"",
":",
"{",
"}",
"}",
"\n",
"for",
"out",
":=",
"range",
"ch",
"{",
"stats",
",",
"ok",
":=",
"out",
".",
"(",
"*",
"tabletenv",
".",
"LogStats",
")",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"out",
",",
"&",
"tabletenv",
".",
"LogStats",
"{",
"}",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"stats",
".",
"Logf",
"(",
"&",
"b",
",",
"formatParams",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"writer",
".",
"Info",
"(",
"b",
".",
"String",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Run logs queries to syslog, if the "log_queries" flag is set to true when starting vttablet. | [
"Run",
"logs",
"queries",
"to",
"syslog",
"if",
"the",
"log_queries",
"flag",
"is",
"set",
"to",
"true",
"when",
"starting",
"vttablet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/sysloglogger/sysloglogger.go#L60-L87 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/query_list.go | NewQueryDetail | func NewQueryDetail(ctx context.Context, conn killable) *QueryDetail {
return &QueryDetail{ctx: ctx, conn: conn, connID: conn.ID(), start: time.Now()}
} | go | func NewQueryDetail(ctx context.Context, conn killable) *QueryDetail {
return &QueryDetail{ctx: ctx, conn: conn, connID: conn.ID(), start: time.Now()}
} | [
"func",
"NewQueryDetail",
"(",
"ctx",
"context",
".",
"Context",
",",
"conn",
"killable",
")",
"*",
"QueryDetail",
"{",
"return",
"&",
"QueryDetail",
"{",
"ctx",
":",
"ctx",
",",
"conn",
":",
"conn",
",",
"connID",
":",
"conn",
".",
"ID",
"(",
")",
",",
"start",
":",
"time",
".",
"Now",
"(",
")",
"}",
"\n",
"}"
] | // NewQueryDetail creates a new QueryDetail | [
"NewQueryDetail",
"creates",
"a",
"new",
"QueryDetail"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_list.go#L45-L47 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/query_list.go | Add | func (ql *QueryList) Add(qd *QueryDetail) {
ql.mu.Lock()
defer ql.mu.Unlock()
ql.queryDetails[qd.connID] = qd
} | go | func (ql *QueryList) Add(qd *QueryDetail) {
ql.mu.Lock()
defer ql.mu.Unlock()
ql.queryDetails[qd.connID] = qd
} | [
"func",
"(",
"ql",
"*",
"QueryList",
")",
"Add",
"(",
"qd",
"*",
"QueryDetail",
")",
"{",
"ql",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ql",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"ql",
".",
"queryDetails",
"[",
"qd",
".",
"connID",
"]",
"=",
"qd",
"\n",
"}"
] | // Add adds a QueryDetail to QueryList | [
"Add",
"adds",
"a",
"QueryDetail",
"to",
"QueryList"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_list.go#L61-L65 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/query_list.go | Remove | func (ql *QueryList) Remove(qd *QueryDetail) {
ql.mu.Lock()
defer ql.mu.Unlock()
delete(ql.queryDetails, qd.connID)
} | go | func (ql *QueryList) Remove(qd *QueryDetail) {
ql.mu.Lock()
defer ql.mu.Unlock()
delete(ql.queryDetails, qd.connID)
} | [
"func",
"(",
"ql",
"*",
"QueryList",
")",
"Remove",
"(",
"qd",
"*",
"QueryDetail",
")",
"{",
"ql",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ql",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"ql",
".",
"queryDetails",
",",
"qd",
".",
"connID",
")",
"\n",
"}"
] | // Remove removes a QueryDetail from QueryList | [
"Remove",
"removes",
"a",
"QueryDetail",
"from",
"QueryList"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_list.go#L68-L72 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/query_list.go | Terminate | func (ql *QueryList) Terminate(connID int64) error {
ql.mu.Lock()
defer ql.mu.Unlock()
qd := ql.queryDetails[connID]
if qd == nil {
return fmt.Errorf("query %v not found", connID)
}
qd.conn.Kill("QueryList.Terminate()", time.Since(qd.start))
return nil
} | go | func (ql *QueryList) Terminate(connID int64) error {
ql.mu.Lock()
defer ql.mu.Unlock()
qd := ql.queryDetails[connID]
if qd == nil {
return fmt.Errorf("query %v not found", connID)
}
qd.conn.Kill("QueryList.Terminate()", time.Since(qd.start))
return nil
} | [
"func",
"(",
"ql",
"*",
"QueryList",
")",
"Terminate",
"(",
"connID",
"int64",
")",
"error",
"{",
"ql",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ql",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"qd",
":=",
"ql",
".",
"queryDetails",
"[",
"connID",
"]",
"\n",
"if",
"qd",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"connID",
")",
"\n",
"}",
"\n",
"qd",
".",
"conn",
".",
"Kill",
"(",
"\"",
"\"",
",",
"time",
".",
"Since",
"(",
"qd",
".",
"start",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Terminate updates the query status and kills the connection | [
"Terminate",
"updates",
"the",
"query",
"status",
"and",
"kills",
"the",
"connection"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_list.go#L75-L84 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/query_list.go | TerminateAll | func (ql *QueryList) TerminateAll() {
ql.mu.Lock()
defer ql.mu.Unlock()
for _, qd := range ql.queryDetails {
qd.conn.Kill("QueryList.TerminateAll()", time.Since(qd.start))
}
} | go | func (ql *QueryList) TerminateAll() {
ql.mu.Lock()
defer ql.mu.Unlock()
for _, qd := range ql.queryDetails {
qd.conn.Kill("QueryList.TerminateAll()", time.Since(qd.start))
}
} | [
"func",
"(",
"ql",
"*",
"QueryList",
")",
"TerminateAll",
"(",
")",
"{",
"ql",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ql",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"qd",
":=",
"range",
"ql",
".",
"queryDetails",
"{",
"qd",
".",
"conn",
".",
"Kill",
"(",
"\"",
"\"",
",",
"time",
".",
"Since",
"(",
"qd",
".",
"start",
")",
")",
"\n",
"}",
"\n",
"}"
] | // TerminateAll terminates all queries and kills the MySQL connections | [
"TerminateAll",
"terminates",
"all",
"queries",
"and",
"kills",
"the",
"MySQL",
"connections"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_list.go#L87-L93 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/query_list.go | GetQueryzRows | func (ql *QueryList) GetQueryzRows() []QueryDetailzRow {
ql.mu.Lock()
rows := []QueryDetailzRow{}
for _, qd := range ql.queryDetails {
row := QueryDetailzRow{
Query: qd.conn.Current(),
ContextHTML: callinfo.HTMLFromContext(qd.ctx),
Start: qd.start,
Duration: time.Since(qd.start),
ConnID: qd.connID,
}
rows = append(rows, row)
}
ql.mu.Unlock()
sort.Sort(byStartTime(rows))
return rows
} | go | func (ql *QueryList) GetQueryzRows() []QueryDetailzRow {
ql.mu.Lock()
rows := []QueryDetailzRow{}
for _, qd := range ql.queryDetails {
row := QueryDetailzRow{
Query: qd.conn.Current(),
ContextHTML: callinfo.HTMLFromContext(qd.ctx),
Start: qd.start,
Duration: time.Since(qd.start),
ConnID: qd.connID,
}
rows = append(rows, row)
}
ql.mu.Unlock()
sort.Sort(byStartTime(rows))
return rows
} | [
"func",
"(",
"ql",
"*",
"QueryList",
")",
"GetQueryzRows",
"(",
")",
"[",
"]",
"QueryDetailzRow",
"{",
"ql",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"rows",
":=",
"[",
"]",
"QueryDetailzRow",
"{",
"}",
"\n",
"for",
"_",
",",
"qd",
":=",
"range",
"ql",
".",
"queryDetails",
"{",
"row",
":=",
"QueryDetailzRow",
"{",
"Query",
":",
"qd",
".",
"conn",
".",
"Current",
"(",
")",
",",
"ContextHTML",
":",
"callinfo",
".",
"HTMLFromContext",
"(",
"qd",
".",
"ctx",
")",
",",
"Start",
":",
"qd",
".",
"start",
",",
"Duration",
":",
"time",
".",
"Since",
"(",
"qd",
".",
"start",
")",
",",
"ConnID",
":",
"qd",
".",
"connID",
",",
"}",
"\n",
"rows",
"=",
"append",
"(",
"rows",
",",
"row",
")",
"\n",
"}",
"\n",
"ql",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"sort",
".",
"Sort",
"(",
"byStartTime",
"(",
"rows",
")",
")",
"\n",
"return",
"rows",
"\n",
"}"
] | // GetQueryzRows returns a list of QueryDetailzRow sorted by start time | [
"GetQueryzRows",
"returns",
"a",
"list",
"of",
"QueryDetailzRow",
"sorted",
"by",
"start",
"time"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_list.go#L113-L129 | train |
vitessio/vitess | go/mysql/conn.go | newConn | func newConn(conn net.Conn) *Conn {
return &Conn{
conn: conn,
closed: sync2.NewAtomicBool(false),
bufferedReader: bufio.NewReaderSize(conn, connBufferSize),
}
} | go | func newConn(conn net.Conn) *Conn {
return &Conn{
conn: conn,
closed: sync2.NewAtomicBool(false),
bufferedReader: bufio.NewReaderSize(conn, connBufferSize),
}
} | [
"func",
"newConn",
"(",
"conn",
"net",
".",
"Conn",
")",
"*",
"Conn",
"{",
"return",
"&",
"Conn",
"{",
"conn",
":",
"conn",
",",
"closed",
":",
"sync2",
".",
"NewAtomicBool",
"(",
"false",
")",
",",
"bufferedReader",
":",
"bufio",
".",
"NewReaderSize",
"(",
"conn",
",",
"connBufferSize",
")",
",",
"}",
"\n",
"}"
] | // newConn is an internal method to create a Conn. Used by client and server
// side for common creation code. | [
"newConn",
"is",
"an",
"internal",
"method",
"to",
"create",
"a",
"Conn",
".",
"Used",
"by",
"client",
"and",
"server",
"side",
"for",
"common",
"creation",
"code",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L168-L174 | train |
vitessio/vitess | go/mysql/conn.go | newServerConn | func newServerConn(conn net.Conn, listener *Listener) *Conn {
c := &Conn{
conn: conn,
listener: listener,
closed: sync2.NewAtomicBool(false),
}
if listener.connReadBufferSize > 0 {
c.bufferedReader = bufio.NewReaderSize(conn, listener.connReadBufferSize)
}
return c
} | go | func newServerConn(conn net.Conn, listener *Listener) *Conn {
c := &Conn{
conn: conn,
listener: listener,
closed: sync2.NewAtomicBool(false),
}
if listener.connReadBufferSize > 0 {
c.bufferedReader = bufio.NewReaderSize(conn, listener.connReadBufferSize)
}
return c
} | [
"func",
"newServerConn",
"(",
"conn",
"net",
".",
"Conn",
",",
"listener",
"*",
"Listener",
")",
"*",
"Conn",
"{",
"c",
":=",
"&",
"Conn",
"{",
"conn",
":",
"conn",
",",
"listener",
":",
"listener",
",",
"closed",
":",
"sync2",
".",
"NewAtomicBool",
"(",
"false",
")",
",",
"}",
"\n",
"if",
"listener",
".",
"connReadBufferSize",
">",
"0",
"{",
"c",
".",
"bufferedReader",
"=",
"bufio",
".",
"NewReaderSize",
"(",
"conn",
",",
"listener",
".",
"connReadBufferSize",
")",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // newServerConn should be used to create server connections.
//
// It stashes a reference to the listener to be able to determine if
// the server is shutting down, and has the ability to control buffer
// size for reads. | [
"newServerConn",
"should",
"be",
"used",
"to",
"create",
"server",
"connections",
".",
"It",
"stashes",
"a",
"reference",
"to",
"the",
"listener",
"to",
"be",
"able",
"to",
"determine",
"if",
"the",
"server",
"is",
"shutting",
"down",
"and",
"has",
"the",
"ability",
"to",
"control",
"buffer",
"size",
"for",
"reads",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L181-L191 | train |
vitessio/vitess | go/mysql/conn.go | startWriterBuffering | func (c *Conn) startWriterBuffering() {
c.bufferedWriter = writersPool.Get().(*bufio.Writer)
c.bufferedWriter.Reset(c.conn)
} | go | func (c *Conn) startWriterBuffering() {
c.bufferedWriter = writersPool.Get().(*bufio.Writer)
c.bufferedWriter.Reset(c.conn)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"startWriterBuffering",
"(",
")",
"{",
"c",
".",
"bufferedWriter",
"=",
"writersPool",
".",
"Get",
"(",
")",
".",
"(",
"*",
"bufio",
".",
"Writer",
")",
"\n",
"c",
".",
"bufferedWriter",
".",
"Reset",
"(",
"c",
".",
"conn",
")",
"\n",
"}"
] | // startWriterBuffering starts using buffered writes. This should
// be terminated by a call to flush. | [
"startWriterBuffering",
"starts",
"using",
"buffered",
"writes",
".",
"This",
"should",
"be",
"terminated",
"by",
"a",
"call",
"to",
"flush",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L195-L198 | train |
vitessio/vitess | go/mysql/conn.go | flush | func (c *Conn) flush() error {
if c.bufferedWriter == nil {
return nil
}
defer func() {
c.bufferedWriter.Reset(nil)
writersPool.Put(c.bufferedWriter)
c.bufferedWriter = nil
}()
return c.bufferedWriter.Flush()
} | go | func (c *Conn) flush() error {
if c.bufferedWriter == nil {
return nil
}
defer func() {
c.bufferedWriter.Reset(nil)
writersPool.Put(c.bufferedWriter)
c.bufferedWriter = nil
}()
return c.bufferedWriter.Flush()
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"flush",
"(",
")",
"error",
"{",
"if",
"c",
".",
"bufferedWriter",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"c",
".",
"bufferedWriter",
".",
"Reset",
"(",
"nil",
")",
"\n",
"writersPool",
".",
"Put",
"(",
"c",
".",
"bufferedWriter",
")",
"\n",
"c",
".",
"bufferedWriter",
"=",
"nil",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"c",
".",
"bufferedWriter",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // flush flushes the written data to the socket.
// This must be called to terminate startBuffering. | [
"flush",
"flushes",
"the",
"written",
"data",
"to",
"the",
"socket",
".",
"This",
"must",
"be",
"called",
"to",
"terminate",
"startBuffering",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L202-L214 | train |
vitessio/vitess | go/mysql/conn.go | getWriter | func (c *Conn) getWriter() io.Writer {
if c.bufferedWriter != nil {
return c.bufferedWriter
}
return c.conn
} | go | func (c *Conn) getWriter() io.Writer {
if c.bufferedWriter != nil {
return c.bufferedWriter
}
return c.conn
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"getWriter",
"(",
")",
"io",
".",
"Writer",
"{",
"if",
"c",
".",
"bufferedWriter",
"!=",
"nil",
"{",
"return",
"c",
".",
"bufferedWriter",
"\n",
"}",
"\n",
"return",
"c",
".",
"conn",
"\n",
"}"
] | // getWriter returns the current writer. It may be either
// the original connection or a wrapper. | [
"getWriter",
"returns",
"the",
"current",
"writer",
".",
"It",
"may",
"be",
"either",
"the",
"original",
"connection",
"or",
"a",
"wrapper",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L218-L223 | train |
vitessio/vitess | go/mysql/conn.go | readEphemeralPacket | func (c *Conn) readEphemeralPacket() ([]byte, error) {
if c.currentEphemeralPolicy != ephemeralUnused {
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "readEphemeralPacket: unexpected currentEphemeralPolicy: %v", c.currentEphemeralPolicy))
}
r := c.getReader()
length, err := c.readHeaderFrom(r)
if err != nil {
return nil, err
}
c.currentEphemeralPolicy = ephemeralRead
if length == 0 {
// This can be caused by the packet after a packet of
// exactly size MaxPacketSize.
return nil, nil
}
// Use the bufPool.
if length < MaxPacketSize {
c.currentEphemeralBuffer = bufPool.Get(length)
if _, err := io.ReadFull(r, *c.currentEphemeralBuffer); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
return *c.currentEphemeralBuffer, nil
}
// Much slower path, revert to allocating everything from scratch.
// We're going to concatenate a lot of data anyway, can't really
// optimize this code path easily.
data := make([]byte, length)
if _, err := io.ReadFull(r, data); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
for {
next, err := c.readOnePacket()
if err != nil {
return nil, err
}
if len(next) == 0 {
// Again, the packet after a packet of exactly size MaxPacketSize.
break
}
data = append(data, next...)
if len(next) < MaxPacketSize {
break
}
}
return data, nil
} | go | func (c *Conn) readEphemeralPacket() ([]byte, error) {
if c.currentEphemeralPolicy != ephemeralUnused {
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "readEphemeralPacket: unexpected currentEphemeralPolicy: %v", c.currentEphemeralPolicy))
}
r := c.getReader()
length, err := c.readHeaderFrom(r)
if err != nil {
return nil, err
}
c.currentEphemeralPolicy = ephemeralRead
if length == 0 {
// This can be caused by the packet after a packet of
// exactly size MaxPacketSize.
return nil, nil
}
// Use the bufPool.
if length < MaxPacketSize {
c.currentEphemeralBuffer = bufPool.Get(length)
if _, err := io.ReadFull(r, *c.currentEphemeralBuffer); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
return *c.currentEphemeralBuffer, nil
}
// Much slower path, revert to allocating everything from scratch.
// We're going to concatenate a lot of data anyway, can't really
// optimize this code path easily.
data := make([]byte, length)
if _, err := io.ReadFull(r, data); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
for {
next, err := c.readOnePacket()
if err != nil {
return nil, err
}
if len(next) == 0 {
// Again, the packet after a packet of exactly size MaxPacketSize.
break
}
data = append(data, next...)
if len(next) < MaxPacketSize {
break
}
}
return data, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"readEphemeralPacket",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"c",
".",
"currentEphemeralPolicy",
"!=",
"ephemeralUnused",
"{",
"panic",
"(",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
",",
"c",
".",
"currentEphemeralPolicy",
")",
")",
"\n",
"}",
"\n\n",
"r",
":=",
"c",
".",
"getReader",
"(",
")",
"\n\n",
"length",
",",
"err",
":=",
"c",
".",
"readHeaderFrom",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"currentEphemeralPolicy",
"=",
"ephemeralRead",
"\n",
"if",
"length",
"==",
"0",
"{",
"// This can be caused by the packet after a packet of",
"// exactly size MaxPacketSize.",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// Use the bufPool.",
"if",
"length",
"<",
"MaxPacketSize",
"{",
"c",
".",
"currentEphemeralBuffer",
"=",
"bufPool",
".",
"Get",
"(",
"length",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"*",
"c",
".",
"currentEphemeralBuffer",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"length",
")",
"\n",
"}",
"\n",
"return",
"*",
"c",
".",
"currentEphemeralBuffer",
",",
"nil",
"\n",
"}",
"\n\n",
"// Much slower path, revert to allocating everything from scratch.",
"// We're going to concatenate a lot of data anyway, can't really",
"// optimize this code path easily.",
"data",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"length",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"length",
")",
"\n",
"}",
"\n",
"for",
"{",
"next",
",",
"err",
":=",
"c",
".",
"readOnePacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"next",
")",
"==",
"0",
"{",
"// Again, the packet after a packet of exactly size MaxPacketSize.",
"break",
"\n",
"}",
"\n\n",
"data",
"=",
"append",
"(",
"data",
",",
"next",
"...",
")",
"\n",
"if",
"len",
"(",
"next",
")",
"<",
"MaxPacketSize",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // readEphemeralPacket attempts to read a packet into buffer from sync.Pool. Do
// not use this method if the contents of the packet needs to be kept
// after the next readEphemeralPacket.
//
// Note if the connection is closed already, an error will be
// returned, and it may not be io.EOF. If the connection closes while
// we are stuck waiting for data, an error will also be returned, and
// it most likely will be io.EOF. | [
"readEphemeralPacket",
"attempts",
"to",
"read",
"a",
"packet",
"into",
"buffer",
"from",
"sync",
".",
"Pool",
".",
"Do",
"not",
"use",
"this",
"method",
"if",
"the",
"contents",
"of",
"the",
"packet",
"needs",
"to",
"be",
"kept",
"after",
"the",
"next",
"readEphemeralPacket",
".",
"Note",
"if",
"the",
"connection",
"is",
"closed",
"already",
"an",
"error",
"will",
"be",
"returned",
"and",
"it",
"may",
"not",
"be",
"io",
".",
"EOF",
".",
"If",
"the",
"connection",
"closes",
"while",
"we",
"are",
"stuck",
"waiting",
"for",
"data",
"an",
"error",
"will",
"also",
"be",
"returned",
"and",
"it",
"most",
"likely",
"will",
"be",
"io",
".",
"EOF",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L273-L326 | train |
vitessio/vitess | go/mysql/conn.go | readEphemeralPacketDirect | func (c *Conn) readEphemeralPacketDirect() ([]byte, error) {
if c.currentEphemeralPolicy != ephemeralUnused {
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "readEphemeralPacketDirect: unexpected currentEphemeralPolicy: %v", c.currentEphemeralPolicy))
}
var r io.Reader = c.conn
length, err := c.readHeaderFrom(r)
if err != nil {
return nil, err
}
c.currentEphemeralPolicy = ephemeralRead
if length == 0 {
// This can be caused by the packet after a packet of
// exactly size MaxPacketSize.
return nil, nil
}
if length < MaxPacketSize {
c.currentEphemeralBuffer = bufPool.Get(length)
if _, err := io.ReadFull(r, *c.currentEphemeralBuffer); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
return *c.currentEphemeralBuffer, nil
}
return nil, vterrors.Errorf(vtrpc.Code_INTERNAL, "readEphemeralPacketDirect doesn't support more than one packet")
} | go | func (c *Conn) readEphemeralPacketDirect() ([]byte, error) {
if c.currentEphemeralPolicy != ephemeralUnused {
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "readEphemeralPacketDirect: unexpected currentEphemeralPolicy: %v", c.currentEphemeralPolicy))
}
var r io.Reader = c.conn
length, err := c.readHeaderFrom(r)
if err != nil {
return nil, err
}
c.currentEphemeralPolicy = ephemeralRead
if length == 0 {
// This can be caused by the packet after a packet of
// exactly size MaxPacketSize.
return nil, nil
}
if length < MaxPacketSize {
c.currentEphemeralBuffer = bufPool.Get(length)
if _, err := io.ReadFull(r, *c.currentEphemeralBuffer); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
return *c.currentEphemeralBuffer, nil
}
return nil, vterrors.Errorf(vtrpc.Code_INTERNAL, "readEphemeralPacketDirect doesn't support more than one packet")
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"readEphemeralPacketDirect",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"c",
".",
"currentEphemeralPolicy",
"!=",
"ephemeralUnused",
"{",
"panic",
"(",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
",",
"c",
".",
"currentEphemeralPolicy",
")",
")",
"\n",
"}",
"\n\n",
"var",
"r",
"io",
".",
"Reader",
"=",
"c",
".",
"conn",
"\n\n",
"length",
",",
"err",
":=",
"c",
".",
"readHeaderFrom",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"currentEphemeralPolicy",
"=",
"ephemeralRead",
"\n",
"if",
"length",
"==",
"0",
"{",
"// This can be caused by the packet after a packet of",
"// exactly size MaxPacketSize.",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"length",
"<",
"MaxPacketSize",
"{",
"c",
".",
"currentEphemeralBuffer",
"=",
"bufPool",
".",
"Get",
"(",
"length",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"*",
"c",
".",
"currentEphemeralBuffer",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"length",
")",
"\n",
"}",
"\n",
"return",
"*",
"c",
".",
"currentEphemeralBuffer",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // readEphemeralPacketDirect attempts to read a packet from the socket directly.
// It needs to be used for the first handshake packet the server receives,
// so we do't buffer the SSL negotiation packet. As a shortcut, only
// packets smaller than MaxPacketSize can be read here.
// This function usually shouldn't be used - use readEphemeralPacket. | [
"readEphemeralPacketDirect",
"attempts",
"to",
"read",
"a",
"packet",
"from",
"the",
"socket",
"directly",
".",
"It",
"needs",
"to",
"be",
"used",
"for",
"the",
"first",
"handshake",
"packet",
"the",
"server",
"receives",
"so",
"we",
"do",
"t",
"buffer",
"the",
"SSL",
"negotiation",
"packet",
".",
"As",
"a",
"shortcut",
"only",
"packets",
"smaller",
"than",
"MaxPacketSize",
"can",
"be",
"read",
"here",
".",
"This",
"function",
"usually",
"shouldn",
"t",
"be",
"used",
"-",
"use",
"readEphemeralPacket",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L333-L361 | train |
vitessio/vitess | go/mysql/conn.go | recycleReadPacket | func (c *Conn) recycleReadPacket() {
if c.currentEphemeralPolicy != ephemeralRead {
// Programming error.
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "trying to call recycleReadPacket while currentEphemeralPolicy is %d", c.currentEphemeralPolicy))
}
if c.currentEphemeralBuffer != nil {
// We are using the pool, put the buffer back in.
bufPool.Put(c.currentEphemeralBuffer)
c.currentEphemeralBuffer = nil
}
c.currentEphemeralPolicy = ephemeralUnused
} | go | func (c *Conn) recycleReadPacket() {
if c.currentEphemeralPolicy != ephemeralRead {
// Programming error.
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "trying to call recycleReadPacket while currentEphemeralPolicy is %d", c.currentEphemeralPolicy))
}
if c.currentEphemeralBuffer != nil {
// We are using the pool, put the buffer back in.
bufPool.Put(c.currentEphemeralBuffer)
c.currentEphemeralBuffer = nil
}
c.currentEphemeralPolicy = ephemeralUnused
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"recycleReadPacket",
"(",
")",
"{",
"if",
"c",
".",
"currentEphemeralPolicy",
"!=",
"ephemeralRead",
"{",
"// Programming error.",
"panic",
"(",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
",",
"c",
".",
"currentEphemeralPolicy",
")",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"currentEphemeralBuffer",
"!=",
"nil",
"{",
"// We are using the pool, put the buffer back in.",
"bufPool",
".",
"Put",
"(",
"c",
".",
"currentEphemeralBuffer",
")",
"\n",
"c",
".",
"currentEphemeralBuffer",
"=",
"nil",
"\n",
"}",
"\n",
"c",
".",
"currentEphemeralPolicy",
"=",
"ephemeralUnused",
"\n",
"}"
] | // recycleReadPacket recycles the read packet. It needs to be called
// after readEphemeralPacket was called. | [
"recycleReadPacket",
"recycles",
"the",
"read",
"packet",
".",
"It",
"needs",
"to",
"be",
"called",
"after",
"readEphemeralPacket",
"was",
"called",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L365-L376 | train |
vitessio/vitess | go/mysql/conn.go | readOnePacket | func (c *Conn) readOnePacket() ([]byte, error) {
r := c.getReader()
length, err := c.readHeaderFrom(r)
if err != nil {
return nil, err
}
if length == 0 {
// This can be caused by the packet after a packet of
// exactly size MaxPacketSize.
return nil, nil
}
data := make([]byte, length)
if _, err := io.ReadFull(r, data); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
return data, nil
} | go | func (c *Conn) readOnePacket() ([]byte, error) {
r := c.getReader()
length, err := c.readHeaderFrom(r)
if err != nil {
return nil, err
}
if length == 0 {
// This can be caused by the packet after a packet of
// exactly size MaxPacketSize.
return nil, nil
}
data := make([]byte, length)
if _, err := io.ReadFull(r, data); err != nil {
return nil, vterrors.Wrapf(err, "io.ReadFull(packet body of length %v) failed", length)
}
return data, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"readOnePacket",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"r",
":=",
"c",
".",
"getReader",
"(",
")",
"\n",
"length",
",",
"err",
":=",
"c",
".",
"readHeaderFrom",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"length",
"==",
"0",
"{",
"// This can be caused by the packet after a packet of",
"// exactly size MaxPacketSize.",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"data",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"length",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"length",
")",
"\n",
"}",
"\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // readOnePacket reads a single packet into a newly allocated buffer. | [
"readOnePacket",
"reads",
"a",
"single",
"packet",
"into",
"a",
"newly",
"allocated",
"buffer",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L379-L396 | train |
vitessio/vitess | go/mysql/conn.go | readPacket | func (c *Conn) readPacket() ([]byte, error) {
// Optimize for a single packet case.
data, err := c.readOnePacket()
if err != nil {
return nil, err
}
// This is a single packet.
if len(data) < MaxPacketSize {
return data, nil
}
// There is more than one packet, read them all.
for {
next, err := c.readOnePacket()
if err != nil {
return nil, err
}
if len(next) == 0 {
// Again, the packet after a packet of exactly size MaxPacketSize.
break
}
data = append(data, next...)
if len(next) < MaxPacketSize {
break
}
}
return data, nil
} | go | func (c *Conn) readPacket() ([]byte, error) {
// Optimize for a single packet case.
data, err := c.readOnePacket()
if err != nil {
return nil, err
}
// This is a single packet.
if len(data) < MaxPacketSize {
return data, nil
}
// There is more than one packet, read them all.
for {
next, err := c.readOnePacket()
if err != nil {
return nil, err
}
if len(next) == 0 {
// Again, the packet after a packet of exactly size MaxPacketSize.
break
}
data = append(data, next...)
if len(next) < MaxPacketSize {
break
}
}
return data, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"readPacket",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Optimize for a single packet case.",
"data",
",",
"err",
":=",
"c",
".",
"readOnePacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// This is a single packet.",
"if",
"len",
"(",
"data",
")",
"<",
"MaxPacketSize",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n\n",
"// There is more than one packet, read them all.",
"for",
"{",
"next",
",",
"err",
":=",
"c",
".",
"readOnePacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"next",
")",
"==",
"0",
"{",
"// Again, the packet after a packet of exactly size MaxPacketSize.",
"break",
"\n",
"}",
"\n\n",
"data",
"=",
"append",
"(",
"data",
",",
"next",
"...",
")",
"\n",
"if",
"len",
"(",
"next",
")",
"<",
"MaxPacketSize",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // readPacket reads a packet from the underlying connection.
// It re-assembles packets that span more than one message.
// This method returns a generic error, not a SQLError. | [
"readPacket",
"reads",
"a",
"packet",
"from",
"the",
"underlying",
"connection",
".",
"It",
"re",
"-",
"assembles",
"packets",
"that",
"span",
"more",
"than",
"one",
"message",
".",
"This",
"method",
"returns",
"a",
"generic",
"error",
"not",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L401-L432 | train |
vitessio/vitess | go/mysql/conn.go | ReadPacket | func (c *Conn) ReadPacket() ([]byte, error) {
result, err := c.readPacket()
if err != nil {
return nil, NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
return result, err
} | go | func (c *Conn) ReadPacket() ([]byte, error) {
result, err := c.readPacket()
if err != nil {
return nil, NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
return result, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ReadPacket",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"result",
",",
"err",
":=",
"c",
".",
"readPacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"NewSQLError",
"(",
"CRServerLost",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"err",
"\n",
"}"
] | // ReadPacket reads a packet from the underlying connection.
// it is the public API version, that returns a SQLError.
// The memory for the packet is always allocated, and it is owned by the caller
// after this function returns. | [
"ReadPacket",
"reads",
"a",
"packet",
"from",
"the",
"underlying",
"connection",
".",
"it",
"is",
"the",
"public",
"API",
"version",
"that",
"returns",
"a",
"SQLError",
".",
"The",
"memory",
"for",
"the",
"packet",
"is",
"always",
"allocated",
"and",
"it",
"is",
"owned",
"by",
"the",
"caller",
"after",
"this",
"function",
"returns",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L438-L444 | train |
vitessio/vitess | go/mysql/conn.go | writeEphemeralPacket | func (c *Conn) writeEphemeralPacket() error {
defer c.recycleWritePacket()
switch c.currentEphemeralPolicy {
case ephemeralWrite:
if err := c.writePacket(*c.currentEphemeralBuffer); err != nil {
return vterrors.Wrapf(err, "conn %v", c.ID())
}
case ephemeralUnused, ephemeralRead:
// Programming error.
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "conn %v: trying to call writeEphemeralPacket while currentEphemeralPolicy is %v", c.ID(), c.currentEphemeralPolicy))
}
return nil
} | go | func (c *Conn) writeEphemeralPacket() error {
defer c.recycleWritePacket()
switch c.currentEphemeralPolicy {
case ephemeralWrite:
if err := c.writePacket(*c.currentEphemeralBuffer); err != nil {
return vterrors.Wrapf(err, "conn %v", c.ID())
}
case ephemeralUnused, ephemeralRead:
// Programming error.
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "conn %v: trying to call writeEphemeralPacket while currentEphemeralPolicy is %v", c.ID(), c.currentEphemeralPolicy))
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeEphemeralPacket",
"(",
")",
"error",
"{",
"defer",
"c",
".",
"recycleWritePacket",
"(",
")",
"\n\n",
"switch",
"c",
".",
"currentEphemeralPolicy",
"{",
"case",
"ephemeralWrite",
":",
"if",
"err",
":=",
"c",
".",
"writePacket",
"(",
"*",
"c",
".",
"currentEphemeralBuffer",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"c",
".",
"ID",
"(",
")",
")",
"\n",
"}",
"\n",
"case",
"ephemeralUnused",
",",
"ephemeralRead",
":",
"// Programming error.",
"panic",
"(",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
",",
"c",
".",
"ID",
"(",
")",
",",
"c",
".",
"currentEphemeralPolicy",
")",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // writeEphemeralPacket writes the packet that was allocated by
// startEphemeralPacket. | [
"writeEphemeralPacket",
"writes",
"the",
"packet",
"that",
"was",
"allocated",
"by",
"startEphemeralPacket",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L522-L536 | train |
vitessio/vitess | go/mysql/conn.go | recycleWritePacket | func (c *Conn) recycleWritePacket() {
if c.currentEphemeralPolicy != ephemeralWrite {
// Programming error.
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "trying to call recycleWritePacket while currentEphemeralPolicy is %d", c.currentEphemeralPolicy))
}
// Release our reference so the buffer can be gced
bufPool.Put(c.currentEphemeralBuffer)
c.currentEphemeralBuffer = nil
c.currentEphemeralPolicy = ephemeralUnused
} | go | func (c *Conn) recycleWritePacket() {
if c.currentEphemeralPolicy != ephemeralWrite {
// Programming error.
panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "trying to call recycleWritePacket while currentEphemeralPolicy is %d", c.currentEphemeralPolicy))
}
// Release our reference so the buffer can be gced
bufPool.Put(c.currentEphemeralBuffer)
c.currentEphemeralBuffer = nil
c.currentEphemeralPolicy = ephemeralUnused
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"recycleWritePacket",
"(",
")",
"{",
"if",
"c",
".",
"currentEphemeralPolicy",
"!=",
"ephemeralWrite",
"{",
"// Programming error.",
"panic",
"(",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
",",
"c",
".",
"currentEphemeralPolicy",
")",
")",
"\n",
"}",
"\n",
"// Release our reference so the buffer can be gced",
"bufPool",
".",
"Put",
"(",
"c",
".",
"currentEphemeralBuffer",
")",
"\n",
"c",
".",
"currentEphemeralBuffer",
"=",
"nil",
"\n",
"c",
".",
"currentEphemeralPolicy",
"=",
"ephemeralUnused",
"\n",
"}"
] | // recycleWritePacket recycles the write packet. It needs to be called
// after writeEphemeralPacket was called. | [
"recycleWritePacket",
"recycles",
"the",
"write",
"packet",
".",
"It",
"needs",
"to",
"be",
"called",
"after",
"writeEphemeralPacket",
"was",
"called",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L540-L549 | train |
vitessio/vitess | go/mysql/conn.go | String | func (c *Conn) String() string {
return fmt.Sprintf("client %v (%s)", c.ConnectionID, c.RemoteAddr().String())
} | go | func (c *Conn) String() string {
return fmt.Sprintf("client %v (%s)", c.ConnectionID, c.RemoteAddr().String())
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"ConnectionID",
",",
"c",
".",
"RemoteAddr",
"(",
")",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // Ident returns a useful identification string for error logging | [
"Ident",
"returns",
"a",
"useful",
"identification",
"string",
"for",
"error",
"logging"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L578-L580 | train |
vitessio/vitess | go/mysql/conn.go | Close | func (c *Conn) Close() {
if c.closed.CompareAndSwap(false, true) {
c.conn.Close()
}
} | go | func (c *Conn) Close() {
if c.closed.CompareAndSwap(false, true) {
c.conn.Close()
}
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Close",
"(",
")",
"{",
"if",
"c",
".",
"closed",
".",
"CompareAndSwap",
"(",
"false",
",",
"true",
")",
"{",
"c",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Close closes the connection. It can be called from a different go
// routine to interrupt the current connection. | [
"Close",
"closes",
"the",
"connection",
".",
"It",
"can",
"be",
"called",
"from",
"a",
"different",
"go",
"routine",
"to",
"interrupt",
"the",
"current",
"connection",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L584-L588 | train |
vitessio/vitess | go/mysql/conn.go | writeOKPacket | func (c *Conn) writeOKPacket(affectedRows, lastInsertID uint64, flags uint16, warnings uint16) error {
length := 1 + // OKPacket
lenEncIntSize(affectedRows) +
lenEncIntSize(lastInsertID) +
2 + // flags
2 // warnings
data := c.startEphemeralPacket(length)
pos := 0
pos = writeByte(data, pos, OKPacket)
pos = writeLenEncInt(data, pos, affectedRows)
pos = writeLenEncInt(data, pos, lastInsertID)
pos = writeUint16(data, pos, flags)
_ = writeUint16(data, pos, warnings)
return c.writeEphemeralPacket()
} | go | func (c *Conn) writeOKPacket(affectedRows, lastInsertID uint64, flags uint16, warnings uint16) error {
length := 1 + // OKPacket
lenEncIntSize(affectedRows) +
lenEncIntSize(lastInsertID) +
2 + // flags
2 // warnings
data := c.startEphemeralPacket(length)
pos := 0
pos = writeByte(data, pos, OKPacket)
pos = writeLenEncInt(data, pos, affectedRows)
pos = writeLenEncInt(data, pos, lastInsertID)
pos = writeUint16(data, pos, flags)
_ = writeUint16(data, pos, warnings)
return c.writeEphemeralPacket()
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeOKPacket",
"(",
"affectedRows",
",",
"lastInsertID",
"uint64",
",",
"flags",
"uint16",
",",
"warnings",
"uint16",
")",
"error",
"{",
"length",
":=",
"1",
"+",
"// OKPacket",
"lenEncIntSize",
"(",
"affectedRows",
")",
"+",
"lenEncIntSize",
"(",
"lastInsertID",
")",
"+",
"2",
"+",
"// flags",
"2",
"// warnings",
"\n",
"data",
":=",
"c",
".",
"startEphemeralPacket",
"(",
"length",
")",
"\n",
"pos",
":=",
"0",
"\n",
"pos",
"=",
"writeByte",
"(",
"data",
",",
"pos",
",",
"OKPacket",
")",
"\n",
"pos",
"=",
"writeLenEncInt",
"(",
"data",
",",
"pos",
",",
"affectedRows",
")",
"\n",
"pos",
"=",
"writeLenEncInt",
"(",
"data",
",",
"pos",
",",
"lastInsertID",
")",
"\n",
"pos",
"=",
"writeUint16",
"(",
"data",
",",
"pos",
",",
"flags",
")",
"\n",
"_",
"=",
"writeUint16",
"(",
"data",
",",
"pos",
",",
"warnings",
")",
"\n\n",
"return",
"c",
".",
"writeEphemeralPacket",
"(",
")",
"\n",
"}"
] | //
// Packet writing methods, for generic packets.
//
// writeOKPacket writes an OK packet.
// Server -> Client.
// This method returns a generic error, not a SQLError. | [
"Packet",
"writing",
"methods",
"for",
"generic",
"packets",
".",
"writeOKPacket",
"writes",
"an",
"OK",
"packet",
".",
"Server",
"-",
">",
"Client",
".",
"This",
"method",
"returns",
"a",
"generic",
"error",
"not",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L604-L619 | train |
vitessio/vitess | go/mysql/conn.go | writeErrorPacket | func (c *Conn) writeErrorPacket(errorCode uint16, sqlState string, format string, args ...interface{}) error {
errorMessage := fmt.Sprintf(format, args...)
length := 1 + 2 + 1 + 5 + len(errorMessage)
data := c.startEphemeralPacket(length)
pos := 0
pos = writeByte(data, pos, ErrPacket)
pos = writeUint16(data, pos, errorCode)
pos = writeByte(data, pos, '#')
if sqlState == "" {
sqlState = SSUnknownSQLState
}
if len(sqlState) != 5 {
panic("sqlState has to be 5 characters long")
}
pos = writeEOFString(data, pos, sqlState)
_ = writeEOFString(data, pos, errorMessage)
return c.writeEphemeralPacket()
} | go | func (c *Conn) writeErrorPacket(errorCode uint16, sqlState string, format string, args ...interface{}) error {
errorMessage := fmt.Sprintf(format, args...)
length := 1 + 2 + 1 + 5 + len(errorMessage)
data := c.startEphemeralPacket(length)
pos := 0
pos = writeByte(data, pos, ErrPacket)
pos = writeUint16(data, pos, errorCode)
pos = writeByte(data, pos, '#')
if sqlState == "" {
sqlState = SSUnknownSQLState
}
if len(sqlState) != 5 {
panic("sqlState has to be 5 characters long")
}
pos = writeEOFString(data, pos, sqlState)
_ = writeEOFString(data, pos, errorMessage)
return c.writeEphemeralPacket()
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeErrorPacket",
"(",
"errorCode",
"uint16",
",",
"sqlState",
"string",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"errorMessage",
":=",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"args",
"...",
")",
"\n",
"length",
":=",
"1",
"+",
"2",
"+",
"1",
"+",
"5",
"+",
"len",
"(",
"errorMessage",
")",
"\n",
"data",
":=",
"c",
".",
"startEphemeralPacket",
"(",
"length",
")",
"\n",
"pos",
":=",
"0",
"\n",
"pos",
"=",
"writeByte",
"(",
"data",
",",
"pos",
",",
"ErrPacket",
")",
"\n",
"pos",
"=",
"writeUint16",
"(",
"data",
",",
"pos",
",",
"errorCode",
")",
"\n",
"pos",
"=",
"writeByte",
"(",
"data",
",",
"pos",
",",
"'#'",
")",
"\n",
"if",
"sqlState",
"==",
"\"",
"\"",
"{",
"sqlState",
"=",
"SSUnknownSQLState",
"\n",
"}",
"\n",
"if",
"len",
"(",
"sqlState",
")",
"!=",
"5",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"pos",
"=",
"writeEOFString",
"(",
"data",
",",
"pos",
",",
"sqlState",
")",
"\n",
"_",
"=",
"writeEOFString",
"(",
"data",
",",
"pos",
",",
"errorMessage",
")",
"\n\n",
"return",
"c",
".",
"writeEphemeralPacket",
"(",
")",
"\n",
"}"
] | // writeErrorPacket writes an error packet.
// Server -> Client.
// This method returns a generic error, not a SQLError. | [
"writeErrorPacket",
"writes",
"an",
"error",
"packet",
".",
"Server",
"-",
">",
"Client",
".",
"This",
"method",
"returns",
"a",
"generic",
"error",
"not",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L646-L664 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.