diff --git a/.dockerignore b/.dockerignore index b71f6e4df5e..8714585aa78 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,9 +1,6 @@ -Godeps/_workspace/pkg -Godeps/_workspace/bin _test java/*/target java/*/bin -php/vendor releases /dist/ /vthook/ diff --git a/.gitignore b/.gitignore index 088ef5bb574..38cfbcc1406 100644 --- a/.gitignore +++ b/.gitignore @@ -37,10 +37,6 @@ __debug_bin # generated protobuf files /go/vt/.proto.tmp -# Godeps files -/Godeps/_workspace/pkg -/Godeps/_workspace/bin - # Eclipse Java CheckStyle plugin configuration. /java/*/.checkstyle # java target files @@ -52,10 +48,6 @@ __debug_bin /java/pom.xml.versionsBackup /java/*/pom.xml.versionsBackup -# php downloaded dependencies -/php/composer.phar -/php/vendor - report*.xml # vitess.io preview site diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/.golangci.yml b/.golangci.yml index 249240a0132..292f77adff3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -14,6 +14,7 @@ linters: - nolintlint - nosprintfhostport - perfsprint + - prealloc - sqlclosecheck - staticcheck - whitespace @@ -144,6 +145,7 @@ linters: path: ^go/mysql/ - linters: - errcheck + - prealloc path: ^go/pools/.*_test.go - linters: - errcheck @@ -157,6 +159,7 @@ linters: - linters: - errcheck - nosprintfhostport + - prealloc - sqlclosecheck path: ^go/test/ - linters: @@ -179,9 +182,11 @@ linters: path: ^go/vt/sqlparser/goyacc - linters: - errcheck + - prealloc path: ^go/vt/throttler/.*_test.go - linters: - errcheck + - prealloc path: ^go/vt/topo/.*/*._test.go - linters: - errcheck @@ -197,12 +202,14 @@ linters: path: ^go/vt/vtctl/grpcvtctlserver/ - linters: - errcheck + - prealloc path: ^go/vt/vtctld/(schema|.*_test).go - linters: - errcheck path: ^go/vt/vtexplain/ - linters: - errcheck + - prealloc path: ^go/vt/vtgate/.*_test.go - linters: - errcheck @@ -215,9 +222,11 @@ linters: path: ^go/vt/vttablet/tabletmanager/vreplication - linters: - errcheck + - prealloc path: ^go/vt/vttablet/(.*endtoend.*|.*_test.go) - linters: - errcheck + - prealloc path: ^go/vt/vttest - linters: - errcheck diff --git a/go/cache/theine/list_test.go b/go/cache/theine/list_test.go index b6aac5539aa..c74610c9cad 100644 --- a/go/cache/theine/list_test.go +++ b/go/cache/theine/list_test.go @@ -49,7 +49,7 @@ func TestList(t *testing.T) { entry := l.PopTail() require.Nil(t, entry) - var entries []*Entry[StringKey, string] + entries := make([]*Entry[StringKey, string], 0, 5) for i := range 5 { new := NewEntry(StringKey(strconv.Itoa(i)), "", 1) evicted := l.PushFront(new) diff --git a/go/cache/theine/tlfu_test.go b/go/cache/theine/tlfu_test.go index a9953bdb806..7aab693db6a 100644 --- a/go/cache/theine/tlfu_test.go +++ b/go/cache/theine/tlfu_test.go @@ -33,7 +33,7 @@ func TestTlfu(t *testing.T) { require.Equal(t, 0, tlfu.slru.probation.len) require.Equal(t, 0, tlfu.slru.protected.len) - var entries []*Entry[StringKey, string] + entries := make([]*Entry[StringKey, string], 0, 200) for i := range 200 { e := NewEntry(StringKey(strconv.Itoa(i)), "", 1) evicted := tlfu.Set(e) @@ -78,7 +78,7 @@ func TestTlfu(t *testing.T) { require.Equal(t, StringKey("1a"), evicted.key) require.Equal(t, 998, tlfu.slru.probation.len) - var entries2 []*Entry[StringKey, string] + entries2 := make([]*Entry[StringKey, string], 0, 1000) for i := range 1000 { e := NewEntry(StringKey(fmt.Sprintf("%d*", i)), "", 1) tlfu.Set(e) diff --git a/go/cmd/vtclient/cli/vtclient.go b/go/cmd/vtclient/cli/vtclient.go index 7f4590d127a..f4ca343da0b 100644 --- a/go/cmd/vtclient/cli/vtclient.go +++ b/go/cmd/vtclient/cli/vtclient.go @@ -430,7 +430,7 @@ func (r *results) print(w io.Writer) { code vtrpcpb.Code count int } - var counts []errorCounts + counts := make([]errorCounts, 0, len(r.errorCount)) for code, count := range r.errorCount { counts = append(counts, errorCounts{code, count}) } diff --git a/go/cmd/vtctldclient/command/query.go b/go/cmd/vtctldclient/command/query.go index d00b7447bdd..9882aa4f04f 100644 --- a/go/cmd/vtctldclient/command/query.go +++ b/go/cmd/vtctldclient/command/query.go @@ -177,7 +177,7 @@ func commandExecuteMultiFetchAsDBA(cmd *cobra.Command, args []string) error { return err } - var qrs []*sqltypes.Result + qrs := make([]*sqltypes.Result, 0, len(resp.Results)) for _, result := range resp.Results { qr := sqltypes.Proto3ToResult(result) qrs = append(qrs, qr) diff --git a/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff.go b/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff.go index 913f2c31a35..ecd5f432305 100644 --- a/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff.go +++ b/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff.go @@ -473,7 +473,7 @@ func getStructFieldNames(s any) []string { } func buildListings(listings []*listing) string { - var lines [][]string + lines := make([][]string, 0, len(listings)+1) var result string if len(listings) == 0 { diff --git a/go/cmd/vtgateclienttest/services/echo.go b/go/cmd/vtgateclienttest/services/echo.go index 1f8b72c408b..dbbec253f0a 100644 --- a/go/cmd/vtgateclienttest/services/echo.go +++ b/go/cmd/vtgateclienttest/services/echo.go @@ -53,8 +53,9 @@ func newEchoClient(fallback vtgateservice.VTGateService) *echoClient { } func printSortedMap(val reflect.Value) []byte { - var keys []string - for _, key := range val.MapKeys() { + mapKeys := val.MapKeys() + keys := make([]string, 0, len(mapKeys)) + for _, key := range mapKeys { keys = append(keys, key.String()) } sort.Strings(keys) @@ -73,7 +74,7 @@ func printSortedMap(val reflect.Value) []byte { func echoQueryResult(vals map[string]any) *sqltypes.Result { qr := &sqltypes.Result{} - var row []sqltypes.Value + row := make([]sqltypes.Value, 0, len(vals)+2) // The first two returned fields are always a field with a MySQL NULL value, // and another field with a zero-length string. diff --git a/go/cmd/vttablet/cli/cli_test.go b/go/cmd/vttablet/cli/cli_test.go index 305e736f4c4..1b5a2174961 100644 --- a/go/cmd/vttablet/cli/cli_test.go +++ b/go/cmd/vttablet/cli/cli_test.go @@ -53,7 +53,7 @@ func TestRunFailsToStartTabletManager(t *testing.T) { "--init-tablet-type": "replica", } - var flagArgs []string + flagArgs := make([]string, 0, len(flags)) for flag, value := range flags { flagArgs = append(flagArgs, flag, value) } diff --git a/go/event/syslogger/fake_logger.go b/go/event/syslogger/fake_logger.go index 852ca2a72a6..83732a58bac 100644 --- a/go/event/syslogger/fake_logger.go +++ b/go/event/syslogger/fake_logger.go @@ -77,7 +77,7 @@ func (tl *testLogger) getLog() loggerMsg { } func (tl *testLogger) GetAllLogs() []string { - var logs []string + logs := make([]string, 0, len(tl.logs)) for _, l := range tl.logs { logs = append(logs, l.level+":"+l.msg) } diff --git a/go/flagutil/flagutil.go b/go/flagutil/flagutil.go index bbb8a49569b..5bd5fc3a65b 100644 --- a/go/flagutil/flagutil.go +++ b/go/flagutil/flagutil.go @@ -42,8 +42,7 @@ func (value StringListValue) Get() any { func parseListWithEscapes(v string, delimiter rune) (value []string) { var escaped, lastWasDelimiter bool - var current []rune - + current := make([]rune, 0, len(v)) for _, r := range v { lastWasDelimiter = false if !escaped { diff --git a/go/mysql/binlog/binlog_json.go b/go/mysql/binlog/binlog_json.go index 51b4fef0ef8..d134a99908c 100644 --- a/go/mysql/binlog/binlog_json.go +++ b/go/mysql/binlog/binlog_json.go @@ -512,12 +512,15 @@ func binparserString(_ jsonDataType, data []byte, pos int) (node *json.Value, er // arrays are stored thus: // | type_identifier(one of [2,3]) | elem count | obj size | list of offsets+lengths of values | actual values | func binparserArray(typ jsonDataType, data []byte, pos int) (node *json.Value, err error) { - var nodes []*json.Value var elem *json.Value var elementCount int large := typ == jsonLargeArray elementCount, pos = readInt(data, pos, large) _, pos = readInt(data, pos, large) + if elementCount == 0 { + return json.NewArray(nil), nil + } + nodes := make([]*json.Value, 0, elementCount) for range elementCount { elem, pos, err = binparserElement(data, pos, large) if err != nil { diff --git a/go/mysql/collations/colldata/uca_contraction_test.go b/go/mysql/collations/colldata/uca_contraction_test.go index 7c010c5a18c..f404b186094 100644 --- a/go/mysql/collations/colldata/uca_contraction_test.go +++ b/go/mysql/collations/colldata/uca_contraction_test.go @@ -194,7 +194,7 @@ func (s *strgen) withText(in string) *strgen { } func (s *strgen) generate(length int, freq float64) (out []byte) { - var flat []rune + flat := make([]rune, 0, len(s.repertoire)) for r := range s.repertoire { flat = append(flat, r) } diff --git a/go/mysql/collations/colldata/wildcard_test.go b/go/mysql/collations/colldata/wildcard_test.go index 923b47ec1d8..4f552da5700 100644 --- a/go/mysql/collations/colldata/wildcard_test.go +++ b/go/mysql/collations/colldata/wildcard_test.go @@ -366,7 +366,7 @@ func BenchmarkWildcardMatching(b *testing.B) { m2 WildcardPattern } - var patterns []bench + patterns := make([]bench, 0, len(wildcardTestCases)) for _, tc := range wildcardTestCases { patterns = append(patterns, bench{ input: []byte(tc.in), diff --git a/go/mysql/collations/golden_test.go b/go/mysql/collations/golden_test.go index 4c6d7c1f0d3..680c1a42a03 100644 --- a/go/mysql/collations/golden_test.go +++ b/go/mysql/collations/golden_test.go @@ -84,12 +84,12 @@ func XTestSupportTables(t *testing.T) { collverMariaDB100, } - var envs []*Environment + envs := make([]*Environment, 0, len(versions)) for _, v := range versions { envs = append(envs, makeEnv(v)) } - var all []ID + all := make([]ID, 0, len(globalVersionInfo)) for id := range globalVersionInfo { all = append(all, id) } diff --git a/go/mysql/collations/integration/coercion_test.go b/go/mysql/collations/integration/coercion_test.go index 8311650fa4c..b5ff0299576 100644 --- a/go/mysql/collations/integration/coercion_test.go +++ b/go/mysql/collations/integration/coercion_test.go @@ -124,7 +124,6 @@ func (tc *testComparison) Test(t *testing.T, remote *RemoteCoercionResult, local func TestComparisonSemantics(t *testing.T) { const BaseString = "abcdABCD01234" - var testInputs []*TextWithCollation conn := mysqlconn(t) defer conn.Close() @@ -133,7 +132,9 @@ func TestComparisonSemantics(t *testing.T) { t.Skipf("The behavior of Coercion Semantics is not correct before 8.0.31") } - for _, coll := range colldata.All(collations.MySQL8()) { + allCollations := colldata.All(collations.MySQL8()) + testInputs := make([]*TextWithCollation, 0, len(allCollations)) + for _, coll := range allCollations { text := verifyTranscoding(t, coll, remote.NewCollation(conn, coll.Name()), []byte(BaseString)) testInputs = append(testInputs, &TextWithCollation{Text: text, Collation: coll.ID()}) } diff --git a/go/mysql/collations/integration/weight_string_test.go b/go/mysql/collations/integration/weight_string_test.go index ad4ad4270fc..33b2f3731a5 100644 --- a/go/mysql/collations/integration/weight_string_test.go +++ b/go/mysql/collations/integration/weight_string_test.go @@ -76,7 +76,7 @@ func TestWeightStringsComprehensive(t *testing.T) { c4cs.remotes = append(c4cs.remotes, remote.NewCollation(conn, coll.Name())) } - var allCharsets []*collationsForCharset + allCharsets := make([]*collationsForCharset, 0, len(charsetMap)) for _, c4cs := range charsetMap { allCharsets = append(allCharsets, c4cs) } diff --git a/go/mysql/collations/tools/makecolldata/codegen/codegen.go b/go/mysql/collations/tools/makecolldata/codegen/codegen.go index b07bcb2b846..eddf6ba7a7d 100644 --- a/go/mysql/collations/tools/makecolldata/codegen/codegen.go +++ b/go/mysql/collations/tools/makecolldata/codegen/codegen.go @@ -92,7 +92,7 @@ func (g *Generator) WriteToFile(out string) { fmt.Fprintf(&file, "package %s\n\n", g.local.Name()) fmt.Fprintf(&file, "import (\n") - var sortedPackages []Package + sortedPackages := make([]Package, 0, len(g.imported)) for pkg := range g.imported { sortedPackages = append(sortedPackages, pkg) } diff --git a/go/mysql/collations/tools/makecolldata/codegen/tablegen.go b/go/mysql/collations/tools/makecolldata/codegen/tablegen.go index 479e876f1f3..57e01facade 100644 --- a/go/mysql/collations/tools/makecolldata/codegen/tablegen.go +++ b/go/mysql/collations/tools/makecolldata/codegen/tablegen.go @@ -251,7 +251,7 @@ func (tg *TableGenerator) writePage(g *Generator, p *page, layout uca.Layout) st } func (tg *TableGenerator) WriteTables(g *Generator, layout uca.Layout) { - var pagePtrs []string + pagePtrs := make([]string, 0, len(tg.pages)) for _, page := range tg.pages { pagePtrs = append(pagePtrs, tg.writePage(g, &page, layout)) } diff --git a/go/mysql/collations/tools/makecolldata/mysqlversions.go b/go/mysql/collations/tools/makecolldata/mysqlversions.go index f0578ecd95b..fa354a67ab3 100644 --- a/go/mysql/collations/tools/makecolldata/mysqlversions.go +++ b/go/mysql/collations/tools/makecolldata/mysqlversions.go @@ -117,7 +117,7 @@ func makeversions(output string) { } } - var versions []string + versions := make([]string, 0, len(versionfiles)) for _, versionCsv := range versionfiles { base := filepath.Base(versionCsv) base = strings.TrimPrefix(base, "collations_") @@ -158,7 +158,7 @@ func makeversions(output string) { g.P() g.P("var globalVersionInfo = map[ID]struct{alias []collalias; isdefault collver}{") - var sorted []*versionInfo + sorted := make([]*versionInfo, 0, len(versioninfo)) for _, vi := range versioninfo { sorted = append(sorted, vi) } diff --git a/go/mysql/collations/tools/maketestdata/maketestdata.go b/go/mysql/collations/tools/maketestdata/maketestdata.go index 4ac790f78ae..390b9ffc4dc 100644 --- a/go/mysql/collations/tools/maketestdata/maketestdata.go +++ b/go/mysql/collations/tools/maketestdata/maketestdata.go @@ -96,7 +96,7 @@ func getTextFromWikipedia(lang testutil.Lang, article string) (string, error) { return "", err } - var chunks []string + chunks := make([]string, 0, len(response.Query.Pages)) for _, page := range response.Query.Pages { chunks = append(chunks, page.Extract) } diff --git a/go/mysql/fakesqldb/server.go b/go/mysql/fakesqldb/server.go index cff28d710d7..d776c4140e1 100644 --- a/go/mysql/fakesqldb/server.go +++ b/go/mysql/fakesqldb/server.go @@ -846,7 +846,7 @@ func (db *DB) MockQueriesForTable(table string, result *sqltypes.Result) { db.AddQueryPattern(selectQueryPattern, result) // mock query for returning columns from information_schema.columns based on specified result - var cols []string + cols := make([]string, 0, len(result.Fields)) for _, field := range result.Fields { cols = append(cols, field.Name) } diff --git a/go/sqltypes/marshal.go b/go/sqltypes/marshal.go index bbf43106110..2e5b34982ca 100644 --- a/go/sqltypes/marshal.go +++ b/go/sqltypes/marshal.go @@ -99,14 +99,14 @@ func ReplaceFields(result *Result, remap map[string]string) *Result { } } - var fields []*querypb.Field + fields := make([]*querypb.Field, 0, len(fieldIdx)) for _, name := range fieldIdx { fields = append(fields, result.Fields[orig[name]]) } fields = fields[:len(result.Fields)-len(remap)] - var rows []Row + rows := make([]Row, 0, len(result.Rows)) for _, origRow := range result.Rows { var row []Value for _, name := range rowIdx { @@ -142,13 +142,15 @@ func MarshalResult(v any) (*Result, error) { elem := val.Type().Elem() elemType := elem.Elem() + visibleFields := reflect.VisibleFields(elemType) + var ( - exportedStructFields []reflect.StructField - fields []*querypb.Field - rows []Row + exportedStructFields = make([]reflect.StructField, 0, len(visibleFields)) + fields = make([]*querypb.Field, 0, len(visibleFields)) + rows = make([]Row, 0, val.Len()) ) - for _, field := range reflect.VisibleFields(elemType) { + for _, field := range visibleFields { if !field.IsExported() { continue } diff --git a/go/sqltypes/testing.go b/go/sqltypes/testing.go index 9c6c642673f..6c4c6442269 100644 --- a/go/sqltypes/testing.go +++ b/go/sqltypes/testing.go @@ -46,7 +46,7 @@ import ( func MakeTestFields(names, types string) []*querypb.Field { n := split(names) t := split(types) - var fields []*querypb.Field + fields := make([]*querypb.Field, 0, len(n)) for i := range n { fields = append(fields, &querypb.Field{ Name: n[i], diff --git a/go/stats/statsd/statsd.go b/go/stats/statsd/statsd.go index 6101d570bbe..097a84b4e3f 100644 --- a/go/stats/statsd/statsd.go +++ b/go/stats/statsd/statsd.go @@ -61,7 +61,7 @@ func makeLabels(labelNames []string, labelValsCombined string) []string { } func makeCommonTags(tags map[string]string) []string { - var commonTags []string + commonTags := make([]string, 0, len(tags)) for k, v := range tags { commonTag := fmt.Sprintf("%s:%s", k, v) commonTags = append(commonTags, commonTag) diff --git a/go/tools/asthelpergen/integration/types.go b/go/tools/asthelpergen/integration/types.go index 84d78994ddc..afb0cede3f6 100644 --- a/go/tools/asthelpergen/integration/types.go +++ b/go/tools/asthelpergen/integration/types.go @@ -131,7 +131,7 @@ func (r ValueSliceContainer) String() string { } func (r InterfaceSlice) String() string { - var elements []string + elements := make([]string, 0, len(r)) for _, el := range r { elements = append(elements, el.String()) } @@ -144,7 +144,7 @@ func (r Bytes) String() string { } func (r LeafSlice) String() string { - var elements []string + elements := make([]string, 0, len(r)) for _, el := range r { elements = append(elements, el.String()) } diff --git a/go/tools/asthelpergen/paths_gen.go b/go/tools/asthelpergen/paths_gen.go index 2596e9ea068..09ecba28cbf 100644 --- a/go/tools/asthelpergen/paths_gen.go +++ b/go/tools/asthelpergen/paths_gen.go @@ -148,8 +148,7 @@ func (p *pathGen) basicMethod(t types.Type, basic *types.Basic, spi generatorSPI } func (p *pathGen) debugString() *jen.Statement { - var switchCases []jen.Code - + switchCases := make([]jen.Code, 0, len(p.steps)+1) for _, step := range p.steps { stepName := step.AsEnum() @@ -230,8 +229,7 @@ func (p *pathGen) generateGetNodeFromPath(spi generatorSPI) *jen.Statement { } func (p *pathGen) generateWalkCases(spi generatorSPI) []jen.Code { - var cases []jen.Code - + cases := make([]jen.Code, 0, len(p.steps)+2) for _, step := range p.steps { stepName := step.AsEnum() diff --git a/go/tools/release-notes/release_notes.go b/go/tools/release-notes/release_notes.go index 0c23e21b7c5..a3993c4d34b 100644 --- a/go/tools/release-notes/release_notes.go +++ b/go/tools/release-notes/release_notes.go @@ -264,7 +264,7 @@ func groupPRs(pris []pullRequestInformation) prsByType { } func createSortedPrTypeSlice(prPerType prsByType) []sortedPRType { - var data []sortedPRType + data := make([]sortedPRType, 0, len(prPerType)) for typeKey, typeElem := range prPerType { newPrType := sortedPRType{ Name: typeKey, diff --git a/go/vt/discovery/healthcheck.go b/go/vt/discovery/healthcheck.go index ee5e2fe1cad..a6132789fce 100644 --- a/go/vt/discovery/healthcheck.go +++ b/go/vt/discovery/healthcheck.go @@ -380,12 +380,11 @@ func NewHealthCheck( hc.logger().Infof("loading tablets for cells: %v", cellsToWatch) - var topoWatchers []*TopologyWatcher cells := strings.Split(cellsToWatch, ",") if cellsToWatch == "" { cells = append(cells, localCell) } - + topoWatchers := make([]*TopologyWatcher, 0, len(cells)) for _, c := range cells { hc.logger().Infof("Setting up healthcheck for cell: %v", c) if c == "" { @@ -796,10 +795,10 @@ func (hc *HealthCheckImpl) GetHealthyTabletStats(target *query.Target) []*Tablet // For TabletType_PRIMARY, this will only return at most one entry, // the most recent tablet of type primary. func (hc *HealthCheckImpl) GetTabletStats(target *query.Target) []*TabletHealth { - var result []*TabletHealth hc.mu.Lock() defer hc.mu.Unlock() ths := hc.healthData[KeyFromTarget(target)] + result := make([]*TabletHealth, 0, len(ths)) for _, th := range ths { result = append(result, th) } diff --git a/go/vt/discovery/tablets_cache_status.go b/go/vt/discovery/tablets_cache_status.go index 110974189f0..15f5dc54c2c 100644 --- a/go/vt/discovery/tablets_cache_status.go +++ b/go/vt/discovery/tablets_cache_status.go @@ -68,10 +68,10 @@ func (tcs *TabletsCacheStatus) StatusAsHTML() safehtml.HTML { Extra string } - var tLinks []link if tcs.TabletsStats != nil { sort.Sort(tcs.TabletsStats) } + tLinks := make([]link, 0, len(tcs.TabletsStats)) for _, ts := range tcs.TabletsStats { color := "green" extra := "" diff --git a/go/vt/mysqlctl/cephbackupstorage/ceph.go b/go/vt/mysqlctl/cephbackupstorage/ceph.go index 5c4b91a6e62..96bc831f01e 100644 --- a/go/vt/mysqlctl/cephbackupstorage/ceph.go +++ b/go/vt/mysqlctl/cephbackupstorage/ceph.go @@ -162,11 +162,12 @@ func (bs *CephBackupStorage) ListBackups(ctx context.Context, dir string) ([]bac bucket := alterBucketName(dir) // List prefixes that begin with dir (i.e. list subdirs). - var subdirs []string + doneCh := make(chan struct{}) searchPrefix := objName(dir, "") + objects := c.ListObjects(bucket, searchPrefix, false, doneCh) + subdirs := make([]string, 0) - doneCh := make(chan struct{}) - for object := range c.ListObjects(bucket, searchPrefix, false, doneCh) { + for object := range objects { if object.Err != nil { _, err := c.BucketExists(bucket) if err != nil { @@ -238,10 +239,11 @@ func (bs *CephBackupStorage) RemoveBackup(ctx context.Context, dir, name string) bucket := alterBucketName(dir) fullName := objName(dir, name, "") - var arr []string doneCh := make(chan struct{}) defer close(doneCh) - for object := range c.ListObjects(bucket, fullName, true, doneCh) { + objects := c.ListObjects(bucket, fullName, true, doneCh) + arr := make([]string, 0, len(objects)) + for object := range objects { if object.Err != nil { return object.Err } diff --git a/go/vt/schemadiff/schema.go b/go/vt/schemadiff/schema.go index da9f831fcc6..397c06bb4c3 100644 --- a/go/vt/schemadiff/schema.go +++ b/go/vt/schemadiff/schema.go @@ -519,7 +519,7 @@ func (s *Schema) Entities() []Entity { // EntityNames is a convenience function that returns just the names of entities, in good order func (s *Schema) EntityNames() []string { - var names []string + names := make([]string, 0, len(s.Entities())) for _, e := range s.Entities() { names = append(names, e.Name()) } @@ -528,7 +528,7 @@ func (s *Schema) EntityNames() []string { // Tables returns this schema's tables in good order (may be applied without error) func (s *Schema) Tables() []*CreateTableEntity { - var tables []*CreateTableEntity + tables := make([]*CreateTableEntity, 0, len(s.sorted)) for _, entity := range s.sorted { if table, ok := entity.(*CreateTableEntity); ok { tables = append(tables, table) @@ -539,7 +539,7 @@ func (s *Schema) Tables() []*CreateTableEntity { // TableNames is a convenience function that returns just the names of tables, in good order func (s *Schema) TableNames() []string { - var names []string + names := make([]string, 0, len(s.Tables())) for _, e := range s.Tables() { names = append(names, e.Name()) } @@ -548,7 +548,7 @@ func (s *Schema) TableNames() []string { // Views returns this schema's views in good order (may be applied without error) func (s *Schema) Views() []*CreateViewEntity { - var views []*CreateViewEntity + views := make([]*CreateViewEntity, 0, len(s.sorted)) for _, entity := range s.sorted { if view, ok := entity.(*CreateViewEntity); ok { views = append(views, view) @@ -559,7 +559,7 @@ func (s *Schema) Views() []*CreateViewEntity { // ViewNames is a convenience function that returns just the names of views, in good order func (s *Schema) ViewNames() []string { - var names []string + names := make([]string, 0, len(s.Views())) for _, e := range s.Views() { names = append(names, e.Name()) } diff --git a/go/vt/schemadiff/table.go b/go/vt/schemadiff/table.go index eb118555371..ca4c1fd261d 100644 --- a/go/vt/schemadiff/table.go +++ b/go/vt/schemadiff/table.go @@ -1415,7 +1415,7 @@ func (c *CreateTableEntity) isRangePartitionsRotation( // And the suffix is any remaining definitions addedPartitions2 := definitions2[len(definitions1):] - var partitionSpecs []*sqlparser.PartitionSpec + partitionSpecs := make([]*sqlparser.PartitionSpec, 0, 2) // Dropped partitions: if len(droppedPartitions1) > 0 { // A single DROP PARTITION clause can specify multiple partition names diff --git a/go/vt/schemamanager/tablet_executor.go b/go/vt/schemamanager/tablet_executor.go index 2f1766d09f5..835be11f721 100644 --- a/go/vt/schemamanager/tablet_executor.go +++ b/go/vt/schemamanager/tablet_executor.go @@ -545,7 +545,7 @@ func applyAllowZeroInDate(sql string, parser *sqlparser.Parser) (string, error) if err != nil { return sql, err } - var modifiedSqls []string + modifiedSqls := make([]string, 0, len(sqls)) for _, singleSQL := range sqls { // --allow-zero-in-date Applies to DDLs stmt, err := parser.Parse(singleSQL) diff --git a/go/vt/sidecardb/sidecardb_test.go b/go/vt/sidecardb/sidecardb_test.go index 906f066839a..4f04cdb4669 100644 --- a/go/vt/sidecardb/sidecardb_test.go +++ b/go/vt/sidecardb/sidecardb_test.go @@ -93,7 +93,7 @@ func TestInitErrors(t *testing.T) { require.Equal(t, int64(len(sidecarTables)-len(schemaErrors)), getDDLCount()) require.Equal(t, int64(len(schemaErrors)), getDDLErrorCount()) - var want []string + want := make([]string, 0, len(schemaErrors)) for _, e := range schemaErrors { want = append(want, e.errorValue) } diff --git a/go/vt/sqlparser/ast_funcs.go b/go/vt/sqlparser/ast_funcs.go index 48e673eebfb..fad8349ed27 100644 --- a/go/vt/sqlparser/ast_funcs.go +++ b/go/vt/sqlparser/ast_funcs.go @@ -3156,8 +3156,8 @@ func (node *ValuesStatement) GetColumnCount() int { } func (node *ValuesStatement) GetColumns() []SelectExpr { - var sel []SelectExpr columnCount := node.GetColumnCount() + sel := make([]SelectExpr, 0, columnCount) for i := range columnCount { sel = append(sel, &AliasedExpr{Expr: NewColName(fmt.Sprintf("column_%d", i))}) } diff --git a/go/vt/sqlparser/predicate_rewriting.go b/go/vt/sqlparser/predicate_rewriting.go index 4dd4c09556d..b8654ef68eb 100644 --- a/go/vt/sqlparser/predicate_rewriting.go +++ b/go/vt/sqlparser/predicate_rewriting.go @@ -213,8 +213,8 @@ func simplifyAnd(expr *AndExpr) (Expr, bool) { // And rewrite that to WHERE (a, b) IN ((1,11), (2,12), (3,13)) func ExtractINFromOR(expr *OrExpr) []Expr { var varNames []*ColName - var values [][]Expr orSlice := orToSlice(expr) + values := make([][]Expr, 0, len(orSlice)) for _, expr := range orSlice { andSlice := andToSlice(expr) if len(andSlice) == 0 { diff --git a/go/vt/sqlparser/utils.go b/go/vt/sqlparser/utils.go index 707a37a3376..b39a65678ee 100644 --- a/go/vt/sqlparser/utils.go +++ b/go/vt/sqlparser/utils.go @@ -170,7 +170,7 @@ func (p *Parser) ReplaceTableQualifiersMultiQuery(multiQuery, olddb, newdb strin if err != nil { return multiQuery, err } - var modifiedQueries []string + modifiedQueries := make([]string, 0, len(queries)) for _, query := range queries { // Replace any provided sidecar database qualifiers with the correct one. query, err := p.ReplaceTableQualifiers(query, olddb, newdb) diff --git a/go/vt/sysvars/sysvars.go b/go/vt/sysvars/sysvars.go index 2af5f820abc..f783ff036ed 100644 --- a/go/vt/sysvars/sysvars.go +++ b/go/vt/sysvars/sysvars.go @@ -301,8 +301,8 @@ func SupportsSetVar(name string) bool { // GetInterestingVariables is used to return all the variables that may be listed in a SHOW VARIABLES command. func GetInterestingVariables() []string { - var res []string // Add all the vitess aware variables + res := make([]string, 0, len(VitessAware)+len(UseReservedConn)+3) for _, variable := range VitessAware { res = append(res, variable.Name) } diff --git a/go/vt/throttler/manager.go b/go/vt/throttler/manager.go index ee142190f75..e9eacfe6ed7 100644 --- a/go/vt/throttler/manager.go +++ b/go/vt/throttler/manager.go @@ -197,7 +197,7 @@ func (m *managerImpl) Throttlers() []string { } func (m *managerImpl) throttlerNamesLocked() []string { - var names []string + names := make([]string, 0, len(m.throttlers)) for k := range m.throttlers { names = append(names, k) } diff --git a/go/vt/topo/etcd2topo/watch.go b/go/vt/topo/etcd2topo/watch.go index acbfae00980..093a0b063f3 100644 --- a/go/vt/topo/etcd2topo/watch.go +++ b/go/vt/topo/etcd2topo/watch.go @@ -177,8 +177,7 @@ func (s *Server) WatchRecursive(ctx context.Context, dirpath string) ([]*topo.Wa return nil, nil, convertError(err, nodePath) } - var initialwd []*topo.WatchDataRecursive - + initialwd := make([]*topo.WatchDataRecursive, 0, len(initial.Kvs)) for _, kv := range initial.Kvs { var wd topo.WatchDataRecursive wd.Path = string(kv.Key) diff --git a/go/vt/topo/topoproto/tablet.go b/go/vt/topo/topoproto/tablet.go index 31ac41e14a0..6a06b095a65 100644 --- a/go/vt/topo/topoproto/tablet.go +++ b/go/vt/topo/topoproto/tablet.go @@ -180,11 +180,12 @@ func ParseTabletType(param string) (topodatapb.TabletType, error) { // ParseTabletTypes parses a comma separated list of tablet types and returns a slice with the respective enums. func ParseTabletTypes(param string) ([]topodatapb.TabletType, error) { - var tabletTypes []topodatapb.TabletType if param == "" { - return tabletTypes, nil + return nil, nil } - for _, typeStr := range strings.Split(param, ",") { + params := strings.Split(param, ",") + tabletTypes := make([]topodatapb.TabletType, 0, len(params)) + for _, typeStr := range params { t, err := ParseTabletType(typeStr) if err != nil { return nil, err diff --git a/go/vt/vtctl/grpcvtctldserver/server.go b/go/vt/vtctl/grpcvtctldserver/server.go index d9f834dd355..c2ed7aa8f7a 100644 --- a/go/vt/vtctl/grpcvtctldserver/server.go +++ b/go/vt/vtctl/grpcvtctldserver/server.go @@ -381,22 +381,24 @@ func (s *VtctldServer) ApplyVSchema(ctx context.Context, req *vtctldatapb.ApplyV } // Attach unknown Vindex params to the response. - var vdxNames []string - var unknownVindexParams []string + vdxNames := make([]string, 0, len(ksVs.Vindexes)) + unknownVindexParams := make([]string, 0, len(vdxNames)) for name := range ksVs.Vindexes { vdxNames = append(vdxNames, name) } sort.Strings(vdxNames) for _, name := range vdxNames { vdx := ksVs.Vindexes[name] - if val, ok := vdx.(vindexes.ParamValidating); ok { - ups := val.UnknownParams() - if len(ups) == 0 { - continue - } - response.UnknownVindexParams[name] = &vtctldatapb.ApplyVSchemaResponse_ParamList{Params: ups} - unknownVindexParams = append(unknownVindexParams, fmt.Sprintf("%s (%s)", name, strings.Join(ups, ", "))) + val, ok := vdx.(vindexes.ParamValidating) + if !ok { + continue + } + ups := val.UnknownParams() + if len(ups) == 0 { + continue } + response.UnknownVindexParams[name] = &vtctldatapb.ApplyVSchemaResponse_ParamList{Params: ups} + unknownVindexParams = append(unknownVindexParams, fmt.Sprintf("%s (%s)", name, strings.Join(ups, ", "))) } if req.Strict && len(unknownVindexParams) > 0 { // return early if unknown params found in strict mode diff --git a/go/vt/vtctl/reparentutil/emergency_reparenter.go b/go/vt/vtctl/reparentutil/emergency_reparenter.go index 12bb8bd7e2b..d59665cc0e3 100644 --- a/go/vt/vtctl/reparentutil/emergency_reparenter.go +++ b/go/vt/vtctl/reparentutil/emergency_reparenter.go @@ -816,7 +816,7 @@ func (erp *EmergencyReparenter) findErrantGTIDs( } // We use all the candidates with the maximum length of the reparent journal to find the errant GTIDs amongst them. - var maxLenPositions []replication.Position + maxLenPositions := make([]replication.Position, 0, len(maxLenCandidates)) updatedValidCandidates := make(map[string]*RelayLogPositions) for _, candidate := range maxLenCandidates { candidatePositions := validCandidates[candidate] diff --git a/go/vt/vtctl/reparentutil/planned_reparenter.go b/go/vt/vtctl/reparentutil/planned_reparenter.go index dcd6dc7c590..b5b8becbc21 100644 --- a/go/vt/vtctl/reparentutil/planned_reparenter.go +++ b/go/vt/vtctl/reparentutil/planned_reparenter.go @@ -206,7 +206,7 @@ func (pr *PlannedReparenter) preflightChecks( // where they require 2 semi-sync acks but from cross-cell replicas. // Let's say they have 3 replicas A in zone 1 and B and C in zone 2. In this case, A is the only // eligible primary elect. Both B and C won't be able to make forward progress if they are promoted. - var tabletsReachable []*topodatapb.Tablet + tabletsReachable := make([]*topodatapb.Tablet, 0, len(tabletMap)) for _, info := range tabletMap { tabletsReachable = append(tabletsReachable, info.Tablet) } diff --git a/go/vt/vtctl/reparentutil/replication.go b/go/vt/vtctl/reparentutil/replication.go index 096cb7166ee..89dd55485b8 100644 --- a/go/vt/vtctl/reparentutil/replication.go +++ b/go/vt/vtctl/reparentutil/replication.go @@ -226,7 +226,7 @@ func stopReplicationAndBuildStatusMaps( var ( m sync.Mutex errChan = make(chan concurrency.Error) - allTablets []*topodatapb.Tablet + allTablets = make([]*topodatapb.Tablet, 0, len(tabletMap)) res = &replicationSnapshot{ statusMap: map[string]*replicationdatapb.StopReplicationStatus{}, primaryStatusMap: map[string]*replicationdatapb.PrimaryStatus{}, diff --git a/go/vt/vtctl/reparentutil/util.go b/go/vt/vtctl/reparentutil/util.go index 38a9efc1051..4dc473101ef 100644 --- a/go/vt/vtctl/reparentutil/util.go +++ b/go/vt/vtctl/reparentutil/util.go @@ -302,8 +302,8 @@ func ShardReplicationStatuses(ctx context.Context, ts *topo.Server, tmc tmclient // getValidCandidatesAndPositionsAsList converts the valid candidates from a map to a list of tablets, making it easier to sort func getValidCandidatesAndPositionsAsList(validCandidates map[string]*RelayLogPositions, tabletMap map[string]*topo.TabletInfo) ([]*topodatapb.Tablet, []*RelayLogPositions, error) { - var validTablets []*topodatapb.Tablet - var tabletPositions []*RelayLogPositions + validTablets := make([]*topodatapb.Tablet, 0, len(validCandidates)) + tabletPositions := make([]*RelayLogPositions, 0, len(validCandidates)) for tabletAlias, position := range validCandidates { tablet, isFound := tabletMap[tabletAlias] if !isFound { diff --git a/go/vt/vtctl/topo.go b/go/vt/vtctl/topo.go index 01df48ca69e..97e4347801d 100644 --- a/go/vt/vtctl/topo.go +++ b/go/vt/vtctl/topo.go @@ -200,8 +200,8 @@ func (d PlainTopologyDecoder) decode(ctx context.Context, topoPaths []string, co } func (d JSONTopologyDecoder) decode(ctx context.Context, topoPaths []string, conn topo.Conn, wr *wrangler.Wrangler, long bool) error { - hasError := false - var jsonData []any + var hasError bool + jsonData := make([]any, 0, len(topoPaths)) for _, topoPath := range topoPaths { data, version, err := conn.Get(ctx, topoPath) if err != nil { diff --git a/go/vt/vtctl/vdiff2.go b/go/vt/vtctl/vdiff2.go index 044eedd1721..3af32d2ded3 100644 --- a/go/vt/vtctl/vdiff2.go +++ b/go/vt/vtctl/vdiff2.go @@ -299,18 +299,19 @@ func getStructFieldNames(s any) []string { } func displayListings(listings []*VDiffListing) string { - var strArray2 [][]string - var strArray []string - str := "" - if len(listings) == 0 { return "" } + + var str string fields := getStructFieldNames(VDiffListing{}) + strArray := make([]string, 0, len(fields)) + strArray2 := make([][]string, 0, len(listings)) + strArray = append(strArray, fields...) strArray2 = append(strArray2, strArray) for _, listing := range listings { - strArray = nil + strArray = strArray[:0] v := reflect.ValueOf(*listing) for _, field := range fields { strArray = append(strArray, v.FieldByName(field).String()) diff --git a/go/vt/vtctl/vtctl.go b/go/vt/vtctl/vtctl.go index 1d74dd1b888..721ea17c203 100644 --- a/go/vt/vtctl/vtctl.go +++ b/go/vt/vtctl/vtctl.go @@ -3420,7 +3420,7 @@ func commandApplyVSchema(ctx context.Context, wr *wrangler.Wrangler, subFlags *p } // Log unknown Vindex params as warnings. - var vdxNames []string + vdxNames := make([]string, 0, len(ksVs.Vindexes)) for name := range ksVs.Vindexes { vdxNames = append(vdxNames, name) } diff --git a/go/vt/vtctl/workflow/lookup_vindex.go b/go/vt/vtctl/workflow/lookup_vindex.go index fca52f13c0d..f96e499663d 100644 --- a/go/vt/vtctl/workflow/lookup_vindex.go +++ b/go/vt/vtctl/workflow/lookup_vindex.go @@ -83,7 +83,7 @@ func (lv *lookupVindex) prepareCreate(ctx context.Context, workflow, keyspace st materializeQuery string targetKeyspace string - tableSettings []*vtctldatapb.TableMaterializeSettings + tableSettings = make([]*vtctldatapb.TableMaterializeSettings, 0) ) if specs == nil || len(specs.Vindexes) == 0 { @@ -432,7 +432,7 @@ func (lv *lookupVindex) generateCreateDDLStatement(tableSchema *tabletmanagerdat tableSchema.TableDefinitions[0].Schema) } - var modified []string + modified := make([]string, 0, len(sourceVindexColumns)+4) modified = append(modified, strings.Replace(lines[0], vInfo.sourceTableName, vInfo.targetTableName, 1)) for i := range sourceVindexColumns { line, err := generateColDef(lines, sourceVindexColumns[i], vInfo.fromCols[i]) diff --git a/go/vt/vtctl/workflow/materializer.go b/go/vt/vtctl/workflow/materializer.go index 244f0d3911e..09f32497a5b 100644 --- a/go/vt/vtctl/workflow/materializer.go +++ b/go/vt/vtctl/workflow/materializer.go @@ -692,7 +692,7 @@ func (mz *materializer) filterSourceShards(targetShard *topo.ShardInfo) []*topo. return mz.sourceShards } // Use intersecting source shards. - var filteredSourceShards []*topo.ShardInfo + filteredSourceShards := make([]*topo.ShardInfo, 0, len(mz.sourceShards)) for _, sourceShard := range mz.sourceShards { if !key.KeyRangeIntersect(sourceShard.KeyRange, targetShard.KeyRange) { continue diff --git a/go/vt/vtctl/workflow/sequences.go b/go/vt/vtctl/workflow/sequences.go index dd4e7d7a6bf..585902aeddf 100644 --- a/go/vt/vtctl/workflow/sequences.go +++ b/go/vt/vtctl/workflow/sequences.go @@ -111,7 +111,7 @@ func (sm *sequenceMetadata) escapeValues() error { } func (ts *trafficSwitcher) getMaxSequenceValues(ctx context.Context, sequences map[string]*sequenceMetadata) (map[string]int64, error) { - var sequencesMetadata []*tabletmanagerdatapb.GetMaxValueForSequencesRequest_SequenceMetadata + sequencesMetadata := make([]*tabletmanagerdatapb.GetMaxValueForSequencesRequest_SequenceMetadata, 0, len(sequences)) for _, seq := range sequences { if err := seq.escapeValues(); err != nil { return nil, err diff --git a/go/vt/vtctl/workflow/server.go b/go/vt/vtctl/workflow/server.go index fe0f09aa4b6..045f008813e 100644 --- a/go/vt/vtctl/workflow/server.go +++ b/go/vt/vtctl/workflow/server.go @@ -1304,7 +1304,7 @@ func (s *Server) moveTablesCreate(ctx context.Context, req *vtctldatapb.MoveTabl return nil, err } } - var targetShards []string + targetShards := make([]string, 0, len(mz.targetShards)) for _, shard := range mz.targetShards { targetShards = append(targetShards, shard.ShardName()) } diff --git a/go/vt/vtctl/workflow/switcher_dry_run.go b/go/vt/vtctl/workflow/switcher_dry_run.go index 5c180311766..8fe35e40a49 100644 --- a/go/vt/vtctl/workflow/switcher_dry_run.go +++ b/go/vt/vtctl/workflow/switcher_dry_run.go @@ -66,7 +66,7 @@ func (dr *switcherDryRun) deleteKeyspaceRoutingRules(ctx context.Context) error } func (dr *switcherDryRun) mirrorTableTraffic(ctx context.Context, types []topodatapb.TabletType, percent float32) error { - var tabletTypes []string + tabletTypes := make([]string, 0, len(types)) for _, servedType := range types { tabletTypes = append(tabletTypes, servedType.String()) } @@ -77,7 +77,7 @@ func (dr *switcherDryRun) mirrorTableTraffic(ctx context.Context, types []topoda } func (dr *switcherDryRun) switchKeyspaceReads(ctx context.Context, types []topodatapb.TabletType) error { - var tabletTypes []string + tabletTypes := make([]string, 0, len(types)) for _, servedType := range types { tabletTypes = append(tabletTypes, servedType.String()) } @@ -113,7 +113,7 @@ func (dr *switcherDryRun) switchTableReads(ctx context.Context, cells []string, if direction == DirectionBackward { ks = dr.ts.SourceKeyspaceName() } - var tabletTypes []string + tabletTypes := make([]string, 0, len(servedTypes)) for _, servedType := range servedTypes { tabletTypes = append(tabletTypes, servedType.String()) } @@ -144,20 +144,18 @@ func (dr *switcherDryRun) allowTargetWrites(ctx context.Context) error { func (dr *switcherDryRun) changeRouting(ctx context.Context) error { dr.drLog.Logf("Switch routing from keyspace %s to keyspace %s", dr.ts.SourceKeyspaceName(), dr.ts.TargetKeyspaceName()) - var deleteLogs, addLogs []string if dr.ts.MigrationType() == binlogdatapb.MigrationType_TABLES { sort.Strings(dr.ts.Tables()) // For deterministic output tables := strings.Join(dr.ts.Tables(), ",") dr.drLog.Logf("Routing rules for tables [%s] will be updated", tables) return nil } - deleteLogs = nil - addLogs = nil sources := maps.Values(dr.ts.Sources()) // Sort the slice for deterministic output. sort.Slice(sources, func(i, j int) bool { return sources[i].GetPrimary().Alias.Uid < sources[j].GetPrimary().Alias.Uid }) + deleteLogs := make([]string, 0, len(sources)) for _, source := range sources { deleteLogs = append(deleteLogs, fmt.Sprintf("shard:%s;tablet:%d", source.GetShard().ShardName(), source.GetShard().PrimaryAlias.Uid)) } @@ -166,6 +164,7 @@ func (dr *switcherDryRun) changeRouting(ctx context.Context) error { sort.Slice(targets, func(i, j int) bool { return targets[i].GetPrimary().Alias.Uid < targets[j].GetPrimary().Alias.Uid }) + addLogs := make([]string, 0, len(targets)) for _, target := range targets { addLogs = append(addLogs, fmt.Sprintf("shard:%s;tablet:%d", target.GetShard().ShardName(), target.GetShard().PrimaryAlias.Uid)) } diff --git a/go/vt/vtctl/workflow/traffic_switcher.go b/go/vt/vtctl/workflow/traffic_switcher.go index c518cda36f4..009cb6b6a87 100644 --- a/go/vt/vtctl/workflow/traffic_switcher.go +++ b/go/vt/vtctl/workflow/traffic_switcher.go @@ -345,7 +345,8 @@ func (ts *trafficSwitcher) TargetShards() []*topo.ShardInfo { } func (ts *trafficSwitcher) getSourceAndTargetShardsNames() ([]string, []string) { - var sourceShards, targetShards []string + sourceShards := make([]string, 0, len(ts.SourceShards())) + targetShards := make([]string, 0, len(ts.TargetShards())) for _, si := range ts.SourceShards() { sourceShards = append(sourceShards, si.ShardName()) } diff --git a/go/vt/vtctl/workflow/utils.go b/go/vt/vtctl/workflow/utils.go index bf4e7739b9b..2538fb9bfe9 100644 --- a/go/vt/vtctl/workflow/utils.go +++ b/go/vt/vtctl/workflow/utils.go @@ -82,7 +82,7 @@ func getTablesInKeyspace(ctx context.Context, ts *topo.Server, tmc tmclient.Tabl } log.Infof("got table schemas: %+v from source primary %v.", schema, primary) - var sourceTables []string + sourceTables := make([]string, 0, len(schema.TableDefinitions)) for _, td := range schema.TableDefinitions { sourceTables = append(sourceTables, td.Name) } diff --git a/go/vt/vtgate/engine/dbddl.go b/go/vt/vtgate/engine/dbddl.go index cb2b859e08e..d8a4a28048f 100644 --- a/go/vt/vtgate/engine/dbddl.go +++ b/go/vt/vtgate/engine/dbddl.go @@ -124,7 +124,7 @@ func (c *DBDDL) createDatabase(ctx context.Context, vcursor VCursor, plugin DBDD case <-time.After(dbDDLDefaultTimeout): // timeout } } - var queries []*querypb.BoundQuery + queries := make([]*querypb.BoundQuery, 0, len(destinations)) for range destinations { queries = append(queries, &querypb.BoundQuery{ Sql: "select 42 from dual where null", diff --git a/go/vt/vtgate/engine/distinct.go b/go/vt/vtgate/engine/distinct.go index 31c51ee8ab8..8eb86aa3ddf 100644 --- a/go/vt/vtgate/engine/distinct.go +++ b/go/vt/vtgate/engine/distinct.go @@ -173,12 +173,11 @@ func (d *Distinct) Inputs() ([]Primitive, []map[string]any) { } func (d *Distinct) description() PrimitiveDescription { - other := map[string]any{} - - var colls []string + colls := make([]string, 0, len(d.CheckCols)) for _, checkCol := range d.CheckCols { colls = append(colls, checkCol.String()) } + other := make(map[string]any, 0) if colls != nil { other["Collations"] = colls } diff --git a/go/vt/vtgate/engine/dml_with_input.go b/go/vt/vtgate/engine/dml_with_input.go index 588879c7be6..8c9588f16c0 100644 --- a/go/vt/vtgate/engine/dml_with_input.go +++ b/go/vt/vtgate/engine/dml_with_input.go @@ -151,14 +151,14 @@ func (dml *DMLWithInput) TryStreamExecute(ctx context.Context, vcursor VCursor, } func (dml *DMLWithInput) description() PrimitiveDescription { - var offsets []string + offsets := make([]string, 0, len(dml.OutputCols)) for idx, offset := range dml.OutputCols { offsets = append(offsets, fmt.Sprintf("%d:%v", idx, offset)) } other := map[string]any{ "Offset": offsets, } - var bvList []string + bvList := make([]string, 0, len(dml.BVList)) for idx, vars := range dml.BVList { if len(vars) == 0 { continue diff --git a/go/vt/vtgate/engine/exec_prepared_statement.go b/go/vt/vtgate/engine/exec_prepared_statement.go index a6a2bb68b16..cdb179814b0 100644 --- a/go/vt/vtgate/engine/exec_prepared_statement.go +++ b/go/vt/vtgate/engine/exec_prepared_statement.go @@ -56,7 +56,7 @@ func (e *ExecStmt) Inputs() ([]Primitive, []map[string]any) { } func (e *ExecStmt) description() PrimitiveDescription { - var params []string + params := make([]string, 0, len(e.Params)) for _, p := range e.Params { params = append(params, p.Name.Lowered()) } diff --git a/go/vt/vtgate/engine/fk_cascade.go b/go/vt/vtgate/engine/fk_cascade.go index 7e580bac67c..f4a2f5d8e1b 100644 --- a/go/vt/vtgate/engine/fk_cascade.go +++ b/go/vt/vtgate/engine/fk_cascade.go @@ -185,8 +185,8 @@ func (fkc *FkCascade) TryStreamExecute(ctx context.Context, vcursor VCursor, bin // Inputs implements the Primitive interface. func (fkc *FkCascade) Inputs() ([]Primitive, []map[string]any) { - var inputs []Primitive - var inputsMap []map[string]any + inputs := make([]Primitive, 0, len(fkc.Children)+2) + inputsMap := make([]map[string]any, 0, len(fkc.Children)+2) inputs = append(inputs, fkc.Selection) inputsMap = append(inputsMap, map[string]any{ inputName: "Selection", diff --git a/go/vt/vtgate/engine/fk_verify.go b/go/vt/vtgate/engine/fk_verify.go index 2242f56389b..9450123c14c 100644 --- a/go/vt/vtgate/engine/fk_verify.go +++ b/go/vt/vtgate/engine/fk_verify.go @@ -73,8 +73,8 @@ func (f *FkVerify) TryStreamExecute(ctx context.Context, vcursor VCursor, bindVa // Inputs implements the Primitive interface func (f *FkVerify) Inputs() ([]Primitive, []map[string]any) { - var inputs []Primitive - var inputsMap []map[string]any + inputs := make([]Primitive, 0, len(f.Verify)) + inputsMap := make([]map[string]any, 0, len(f.Verify)) for idx, v := range f.Verify { inputsMap = append(inputsMap, map[string]any{ inputName: fmt.Sprintf("%s-%d", v.Typ, idx+1), diff --git a/go/vt/vtgate/engine/insert_common.go b/go/vt/vtgate/engine/insert_common.go index e9852b5d6fe..97d4124ad78 100644 --- a/go/vt/vtgate/engine/insert_common.go +++ b/go/vt/vtgate/engine/insert_common.go @@ -215,11 +215,10 @@ func (ic *InsertCommon) processOwned(ctx context.Context, vcursor VCursor, vinde } // InsertIgnore - var createIndexes []int - var createKeys []sqltypes.Row - var createKsids []ksID - var vindexNull []bool - + createIndexes := make([]int, 0, len(vindexColumnsKeys)) + createKeys := make([]sqltypes.Row, 0, len(vindexColumnsKeys)) + createKsids := make([]ksID, 0, len(vindexColumnsKeys)) + vindexNull := make([]bool, 0, len(vindexColumnsKeys)) for rowNum, rowColumnKeys := range vindexColumnsKeys { if ksids[rowNum] == nil { continue @@ -233,7 +232,6 @@ func (ic *InsertCommon) processOwned(ctx context.Context, vcursor VCursor, vinde break } } - createIndexes = append(createIndexes, rowNum) createKeys = append(createKeys, rowColumnKeys) createKsids = append(createKsids, ksids[rowNum]) diff --git a/go/vt/vtgate/engine/lock.go b/go/vt/vtgate/engine/lock.go index 1bb7c7d8733..7d432e9bdbf 100644 --- a/go/vt/vtgate/engine/lock.go +++ b/go/vt/vtgate/engine/lock.go @@ -169,7 +169,7 @@ func (l *Lock) description() PrimitiveDescription { other := map[string]any{ "FieldQuery": l.FieldQuery, } - var lf []string + lf := make([]string, 0, len(l.LockFunctions)) for _, f := range l.LockFunctions { lf = append(lf, sqlparser.String(f.Typ)) } diff --git a/go/vt/vtgate/engine/plan_description.go b/go/vt/vtgate/engine/plan_description.go index 84ffe9de0f9..d562ae4c9fe 100644 --- a/go/vt/vtgate/engine/plan_description.go +++ b/go/vt/vtgate/engine/plan_description.go @@ -280,7 +280,7 @@ func median(nums []int) float64 { } func (pd PrimitiveDescription) addToGraph(g *graphviz.Graph) (*graphviz.Node, error) { - var nodes []*graphviz.Node + nodes := make([]*graphviz.Node, 0, len(pd.Inputs)) for _, input := range pd.Inputs { n, err := input.addToGraph(g) if err != nil { @@ -328,7 +328,7 @@ func GraphViz(p Primitive) (*graphviz.Graph, error) { } func addMap(input map[string]any, buf *bytes.Buffer) error { - var mk []string + mk := make([]string, 0, len(input)) for k, v := range input { if v == "" || v == nil || v == 0 || v == false { continue @@ -452,7 +452,7 @@ func (m orderedMap) MarshalJSON() ([]byte, error) { } func (m orderedMap) String() string { - var output []string + output := make([]string, 0, len(m)) for _, val := range m { output = append(output, fmt.Sprintf("%s:%v", val.key, val.val)) } diff --git a/go/vt/vtgate/engine/projection.go b/go/vt/vtgate/engine/projection.go index d18608393f3..e5c9af4d17a 100644 --- a/go/vt/vtgate/engine/projection.go +++ b/go/vt/vtgate/engine/projection.go @@ -47,7 +47,7 @@ func (p *Projection) TryExecute(ctx context.Context, vcursor VCursor, bindVars m } env := evalengine.NewExpressionEnv(ctx, bindVars, vcursor) - var resultRows []sqltypes.Row + resultRows := make([]sqltypes.Row, 0, len(result.Rows)) for _, row := range result.Rows { resultRow := make(sqltypes.Row, 0, len(p.Exprs)) env.Row = row @@ -133,7 +133,7 @@ func (p *Projection) evalFields(env *evalengine.ExpressionEnv, infields []*query // dependency on these fields altogether env.Fields = infields - var fields []*querypb.Field + fields := make([]*querypb.Field, 0, len(p.Cols)) for i, col := range p.Cols { typ, err := env.TypeOf(p.Exprs[i]) if err != nil { @@ -167,7 +167,7 @@ func (p *Projection) Inputs() ([]Primitive, []map[string]any) { // description implements the Primitive interface func (p *Projection) description() PrimitiveDescription { - var exprs []string + exprs := make([]string, 0, len(p.Exprs)) for idx, e := range p.Exprs { expr := sqlparser.String(e) alias := p.Cols[idx] diff --git a/go/vt/vtgate/engine/routing.go b/go/vt/vtgate/engine/routing.go index 6fafb59e7fc..720e9dd85df 100644 --- a/go/vt/vtgate/engine/routing.go +++ b/go/vt/vtgate/engine/routing.go @@ -362,7 +362,7 @@ func (rp *RoutingParameters) equal(ctx context.Context, vcursor VCursor, bindVar func (rp *RoutingParameters) equalMultiCol(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable) ([]*srvtopo.ResolvedShard, []map[string]*querypb.BindVariable, error) { env := evalengine.NewExpressionEnv(ctx, bindVars, vcursor) - var rowValue []sqltypes.Value + rowValue := make([]sqltypes.Value, 0, len(rp.Values)) for _, rvalue := range rp.Values { v, err := env.Evaluate(rvalue) if err != nil { @@ -440,8 +440,8 @@ func (rp *RoutingParameters) multiEqual(ctx context.Context, vcursor VCursor, bi } func (rp *RoutingParameters) multiEqualMultiCol(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable) ([]*srvtopo.ResolvedShard, []map[string]*querypb.BindVariable, error) { - var multiColValues [][]sqltypes.Value env := evalengine.NewExpressionEnv(ctx, bindVars, vcursor) + multiColValues := make([][]sqltypes.Value, 0, len(rp.Values)) for _, rvalue := range rp.Values { v, err := env.Evaluate(rvalue) if err != nil { @@ -526,7 +526,7 @@ func resolveShardsMultiCol(ctx context.Context, vcursor VCursor, vindex vindexes // and eliminates duplicates, returning the values to be used for each column for a multi column // vindex in each shard. func buildMultiColumnVindexValues(shardsValues [][][]sqltypes.Value) [][][]*querypb.Value { - var shardsIds [][][]*querypb.Value + shardsIds := make([][][]*querypb.Value, 0, len(shardsValues)) for _, shardValues := range shardsValues { // shardValues -> [[0,1], [0,2], [0,3]] // shardIds -> [[0,0,0], [1,2,3]] @@ -608,10 +608,10 @@ func shardVarsMultiCol(bv map[string]*querypb.BindVariable, mapVals [][][]*query func generateRowColValues(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, values []evalengine.Expr) ([][]sqltypes.Value, map[int]any, error) { // gather values from all the column in the vindex - var multiColValues [][]sqltypes.Value var lv []sqltypes.Value isSingleVal := map[int]any{} env := evalengine.NewExpressionEnv(ctx, bindVars, vcursor) + multiColValues := make([][]sqltypes.Value, 0, len(values)) for colIdx, rvalue := range values { result, err := env.Evaluate(rvalue) if err != nil { @@ -637,7 +637,7 @@ func generateRowColValues(ctx context.Context, vcursor VCursor, bindVars map[str so that the vindex can map them into correct destination. */ - var rowColValues [][]sqltypes.Value + rowColValues := make([][]sqltypes.Value, 0, len(multiColValues[0])+(len(multiColValues)-1)) for _, firstCol := range multiColValues[0] { rowColValues = append(rowColValues, []sqltypes.Value{firstCol}) } diff --git a/go/vt/vtgate/engine/update.go b/go/vt/vtgate/engine/update.go index 4b067d512f8..9e9dbe2780e 100644 --- a/go/vt/vtgate/engine/update.go +++ b/go/vt/vtgate/engine/update.go @@ -203,7 +203,7 @@ func (upd *Update) description() PrimitiveDescription { addFieldsIfNotEmpty(upd.DML, other) - var changedVindexes []string + changedVindexes := make([]string, 0, len(upd.ChangedVindexValues)) for k, v := range upd.ChangedVindexValues { changedVindexes = append(changedVindexes, fmt.Sprintf("%s:%d", k, v.Offset)) } diff --git a/go/vt/vtgate/engine/upsert.go b/go/vt/vtgate/engine/upsert.go index 9a57b2fa70c..6b53acacc06 100644 --- a/go/vt/vtgate/engine/upsert.go +++ b/go/vt/vtgate/engine/upsert.go @@ -93,8 +93,8 @@ func (u *Upsert) TryStreamExecute(ctx context.Context, vcursor VCursor, bindVars // Inputs implements Primitive interface type. func (u *Upsert) Inputs() ([]Primitive, []map[string]any) { - var inputs []Primitive - var inputsMap []map[string]any + inputs := make([]Primitive, 0, len(u.Upserts)) + inputsMap := make([]map[string]any, 0, len(u.Upserts)) for i, up := range u.Upserts { inputs = append(inputs, up.Insert, up.Update) inputsMap = append(inputsMap, diff --git a/go/vt/vtgate/evalengine/eval_tuple.go b/go/vt/vtgate/evalengine/eval_tuple.go index 7d665fda36a..ba6ef7d7c35 100644 --- a/go/vt/vtgate/evalengine/eval_tuple.go +++ b/go/vt/vtgate/evalengine/eval_tuple.go @@ -45,7 +45,7 @@ func newEvalTuple(values []*querypb.Value, collation collations.ID) (*evalTuple, } func (e *evalTuple) ToRawBytes() []byte { - var vals []sqltypes.Value + vals := make([]sqltypes.Value, 0, len(e.t)) for _, e2 := range e.t { v, err := sqltypes.NewValue(e2.SQLType(), e2.ToRawBytes()) if err != nil { diff --git a/go/vt/vtgate/evalengine/fn_compare.go b/go/vt/vtgate/evalengine/fn_compare.go index 2a6505bbd68..13eb0bdb7fc 100644 --- a/go/vt/vtgate/evalengine/fn_compare.go +++ b/go/vt/vtgate/evalengine/fn_compare.go @@ -503,7 +503,7 @@ func (call *builtinMultiComparison) compile(c *compiler) (ctype, error) { text int binary int json int - args []ctype + args = make([]ctype, 0) nullable bool prec int ) diff --git a/go/vt/vtgate/executor.go b/go/vt/vtgate/executor.go index 4c1fbedb447..bb34849833f 100644 --- a/go/vt/vtgate/executor.go +++ b/go/vt/vtgate/executor.go @@ -1677,7 +1677,7 @@ func (e *Executor) ExecuteVStream(ctx context.Context, rss []*srvtopo.ResolvedSh } func (e *Executor) startVStream(ctx context.Context, rss []*srvtopo.ResolvedShard, filter *binlogdatapb.Filter, gtid string, callback func(evs []*binlogdatapb.VEvent) error) error { - var shardGtids []*binlogdatapb.ShardGtid + shardGtids := make([]*binlogdatapb.ShardGtid, 0, len(rss)) for _, rs := range rss { shardGtid := &binlogdatapb.ShardGtid{ Keyspace: rs.Target.Keyspace, diff --git a/go/vt/vtgate/executorcontext/vcursor_impl.go b/go/vt/vtgate/executorcontext/vcursor_impl.go index fe4bee5f868..a01b6a2c5cc 100644 --- a/go/vt/vtgate/executorcontext/vcursor_impl.go +++ b/go/vt/vtgate/executorcontext/vcursor_impl.go @@ -430,7 +430,7 @@ func (vc *VCursorImpl) UnresolvedTransactions(ctx context.Context, keyspace stri if err != nil { return nil, err } - var targets []*querypb.Target + targets := make([]*querypb.Target, 0, len(rss)) for _, rs := range rss { targets = append(targets, rs.Target) } @@ -666,7 +666,7 @@ func (vc *VCursorImpl) AllKeyspace() ([]*vindexes.Keyspace, error) { if len(vc.vschema.Keyspaces) == 0 { return nil, errNoDbAvailable } - var kss []*vindexes.Keyspace + kss := make([]*vindexes.Keyspace, 0, len(vc.vschema.Keyspaces)) for _, ks := range vc.vschema.Keyspaces { kss = append(kss, ks.Keyspace) } diff --git a/go/vt/vtgate/planbuilder/builder.go b/go/vt/vtgate/planbuilder/builder.go index da2769742d6..af4f2150c4e 100644 --- a/go/vt/vtgate/planbuilder/builder.go +++ b/go/vt/vtgate/planbuilder/builder.go @@ -430,7 +430,7 @@ func buildFlushTables(stmt *sqlparser.Flush, vschema plancontext.VSchema) (*plan return keys[i].ks.Name < keys[j].ks.Name }) - var sources []engine.Primitive + sources := make([]engine.Primitive, 0, len(keys)) for _, sendDest := range keys { plan := &engine.Send{ Keyspace: sendDest.ks, diff --git a/go/vt/vtgate/planbuilder/expression_converter.go b/go/vt/vtgate/planbuilder/expression_converter.go index 961c4f1fb4b..865ae3aeb7f 100644 --- a/go/vt/vtgate/planbuilder/expression_converter.go +++ b/go/vt/vtgate/planbuilder/expression_converter.go @@ -106,7 +106,7 @@ func (ec *expressionConverter) source(vschema plancontext.VSchema) (engine.Primi return nil, err } - var expr []string + expr := make([]string, 0, len(ec.tabletExpressions)) for _, e := range ec.tabletExpressions { expr = append(expr, sqlparser.String(e)) } diff --git a/go/vt/vtgate/planbuilder/operator_transformers.go b/go/vt/vtgate/planbuilder/operator_transformers.go index c9246f9ec7b..2086bf16c8a 100644 --- a/go/vt/vtgate/planbuilder/operator_transformers.go +++ b/go/vt/vtgate/planbuilder/operator_transformers.go @@ -120,7 +120,7 @@ func transformDMLWithInput(ctx *plancontext.PlanningContext, op *operators.DMLWi return nil, err } - var dmls []engine.Primitive + dmls := make([]engine.Primitive, 0, len(op.DML)) for _, dml := range op.DML { del, err := transformToPrimitive(ctx, dml) if err != nil { @@ -163,7 +163,7 @@ func transformOneUpsert(ctx *plancontext.PlanningContext, source operators.Upser } func transformSequential(ctx *plancontext.PlanningContext, op *operators.Sequential) (engine.Primitive, error) { - var prims []engine.Primitive + prims := make([]engine.Primitive, 0, len(op.Sources)) for _, source := range op.Sources { prim, err := transformToPrimitive(ctx, source) if err != nil { @@ -173,10 +173,8 @@ func transformSequential(ctx *plancontext.PlanningContext, op *operators.Sequent if ok { ins.PreventAutoCommit = true } - prims = append(prims, prim) } - return engine.NewSequential(prims), nil } @@ -237,7 +235,7 @@ func transformFkCascade(ctx *plancontext.PlanningContext, fkc *operators.FkCasca } // Go over the children and convert them to Primitives too. - var children []*engine.FkChild + children := make([]*engine.FkChild, 0, len(fkc.Children)) for _, child := range fkc.Children { childLP, err := transformToPrimitive(ctx, child.Op) if err != nil { @@ -305,7 +303,7 @@ func transformFkVerify(ctx *plancontext.PlanningContext, fkv *operators.FkVerify ctx.SemTable = nil // Go over the children and convert them to Primitives too. - var verify []*engine.Verify + verify := make([]*engine.Verify, 0, len(fkv.Verify)) for _, v := range fkv.Verify { lp, err := transformToPrimitive(ctx, v.Op) if err != nil { @@ -332,9 +330,7 @@ func transformAggregator(ctx *plancontext.PlanningContext, op *operators.Aggrega return nil, err } - var aggregates []*engine.AggregateParams - var groupByKeys []*engine.GroupByParams - + aggregates := make([]*engine.AggregateParams, 0, len(op.Aggregations)) for _, aggr := range op.Aggregations { switch aggr.OpCode { case opcode.AggregateUnassigned: @@ -370,6 +366,7 @@ func transformAggregator(ctx *plancontext.PlanningContext, op *operators.Aggrega aggregates = append(aggregates, aggrParam) } + groupByKeys := make([]*engine.GroupByParams, 0, len(op.Grouping)) for _, groupBy := range op.Grouping { typ, _ := ctx.TypeForExpr(groupBy.Inner) groupByKeys = append(groupByKeys, &engine.GroupByParams{ @@ -459,8 +456,8 @@ func transformProjection(ctx *plancontext.PlanningContext, op *operators.Project return nil, err } - var evalengineExprs []evalengine.Expr - var columnNames []string + evalengineExprs := make([]evalengine.Expr, 0, len(ap)) + columnNames := make([]string, 0, len(ap)) for _, pe := range ap { ee, err := getEvalEngineExpr(ctx, pe) if err != nil { @@ -890,7 +887,7 @@ func getAllTableNames(op *operators.Route) ([]string, error) { if err != nil { return nil, err } - var tableNames []string + tableNames := make([]string, 0, len(tableNameMap)) for name := range tableNameMap { tableNames = append(tableNames, name) } diff --git a/go/vt/vtgate/planbuilder/operators/aggregator.go b/go/vt/vtgate/planbuilder/operators/aggregator.go index fe3e06d70e0..9d8598ed63d 100644 --- a/go/vt/vtgate/planbuilder/operators/aggregator.go +++ b/go/vt/vtgate/planbuilder/operators/aggregator.go @@ -343,7 +343,7 @@ func (a *Aggregator) ShortDescription() string { return fmt.Sprintf("%s%s", org, strings.Join(columns, ", ")) } - var grouping []string + grouping := make([]string, 0, len(a.Grouping)) for _, gb := range a.Grouping { grouping = append(grouping, sqlparser.String(gb.Inner)) } diff --git a/go/vt/vtgate/planbuilder/operators/delete.go b/go/vt/vtgate/planbuilder/operators/delete.go index 56f0e7d44d7..c5caf558e02 100644 --- a/go/vt/vtgate/planbuilder/operators/delete.go +++ b/go/vt/vtgate/planbuilder/operators/delete.go @@ -123,12 +123,11 @@ func createDeleteWithInputOp(ctx *plancontext.PlanningContext, del *sqlparser.De Lock: sqlparser.ForUpdateLock, } - var delOps []dmlOp + delOps := make([]dmlOp, 0, len(ctx.SemTable.DMLTargets.Constituents())) for _, target := range ctx.SemTable.DMLTargets.Constituents() { op := createDeleteOpWithTarget(ctx, target, del.Ignore) delOps = append(delOps, op) } - delOps = sortDmlOps(delOps) // now map the operator and column list. @@ -264,7 +263,7 @@ func createDeleteOperator(ctx *plancontext.PlanningContext, del *sqlparser.Delet } func generateOwnedVindexQuery(del *sqlparser.Delete, table TargetTable, ksidCols []sqlparser.IdentifierCI) *sqlparser.Select { - var selExprs []sqlparser.SelectExpr + selExprs := make([]sqlparser.SelectExpr, 0) for _, col := range ksidCols { colName := makeColName(col, table, sqlparser.MultiTable(del.TableExprs)) selExprs = append(selExprs, aeWrap(colName)) @@ -293,13 +292,12 @@ func makeColName(col sqlparser.IdentifierCI, table TargetTable, isMultiTbl bool) func addOrdering(ctx *plancontext.PlanningContext, op Operator, orderBy sqlparser.OrderBy) Operator { es := &expressionSet{} - var order []OrderBy + order := make([]OrderBy, 0, len(orderBy)) for _, ord := range orderBy { if sqlparser.IsNull(ord.Expr) || !es.add(ctx, ord.Expr) { // ORDER BY null, or expression repeated can safely be ignored continue } - order = append(order, OrderBy{ Inner: sqlparser.Clone(ord), SimplifiedExpr: ord.Expr, @@ -341,8 +339,8 @@ func updateQueryGraphWithSource(ctx *plancontext.PlanningContext, input Operator } func createFkCascadeOpForDelete(ctx *plancontext.PlanningContext, parentOp Operator, delStmt *sqlparser.Delete, childFks []vindexes.ChildFKInfo, deletedTbl *vindexes.BaseTable) Operator { - var fkChildren []*FkChild var selectExprs []sqlparser.SelectExpr + fkChildren := make([]*FkChild, 0, len(childFks)) tblName := delStmt.Targets[0] for _, fk := range childFks { // Any RESTRICT type foreign keys that arrive here, diff --git a/go/vt/vtgate/planbuilder/operators/fk_cascade.go b/go/vt/vtgate/planbuilder/operators/fk_cascade.go index 0aff5b3bea2..765627140e8 100644 --- a/go/vt/vtgate/planbuilder/operators/fk_cascade.go +++ b/go/vt/vtgate/planbuilder/operators/fk_cascade.go @@ -50,7 +50,7 @@ var _ Operator = (*FkCascade)(nil) // Inputs implements the Operator interface func (fkc *FkCascade) Inputs() []Operator { - var inputs []Operator + inputs := make([]Operator, 0, 2+len(fkc.Children)) inputs = append(inputs, fkc.Parent) inputs = append(inputs, fkc.Selection) for _, child := range fkc.Children { diff --git a/go/vt/vtgate/planbuilder/operators/horizon_expanding.go b/go/vt/vtgate/planbuilder/operators/horizon_expanding.go index 12a6e62b4b1..e8e3ebcfb49 100644 --- a/go/vt/vtgate/planbuilder/operators/horizon_expanding.go +++ b/go/vt/vtgate/planbuilder/operators/horizon_expanding.go @@ -118,10 +118,10 @@ func expandSelectHorizon(ctx *plancontext.PlanningContext, horizon *Horizon, sel } func expandOrderBy(ctx *plancontext.PlanningContext, op Operator, qp *QueryProjection, derived string) Operator { - var newOrder []OrderBy sqc := &SubQueryBuilder{} proj, ok := op.(*Projection) + newOrder := make([]OrderBy, 0, len(qp.OrderExprs)) for _, expr := range qp.OrderExprs { // Attempt to extract any subqueries within the expression newExpr, subqs := sqc.pullOutValueSubqueries(ctx, expr.SimplifiedExpr, TableID(op), false) @@ -345,8 +345,7 @@ func createProjectionWithoutAggr(ctx *plancontext.PlanningContext, qp *QueryProj } func newStarProjection(src Operator, qp *QueryProjection) *Projection { - var cols []sqlparser.SelectExpr - + cols := make([]sqlparser.SelectExpr, 0, len(qp.SelectExprs)) for _, expr := range qp.SelectExprs { _ = sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) { _, isSubQ := node.(*sqlparser.Subquery) diff --git a/go/vt/vtgate/planbuilder/operators/keys.go b/go/vt/vtgate/planbuilder/operators/keys.go index 851d5adb441..6919da57591 100644 --- a/go/vt/vtgate/planbuilder/operators/keys.go +++ b/go/vt/vtgate/planbuilder/operators/keys.go @@ -252,14 +252,13 @@ func GetVExplainKeys(ctx *plancontext.PlanningContext, stmt sqlparser.Statement) } func getUniqueJoinPredicates(ctx *plancontext.PlanningContext, joinPredicates []joinPredicate) []JoinPredicate { - var result []JoinPredicate + result := make([]JoinPredicate, 0, len(joinPredicates)) for _, predicate := range joinPredicates { lhs := createColumn(ctx, predicate.lhs) rhs := createColumn(ctx, predicate.rhs) if lhs == nil || rhs == nil { continue } - result = append(result, newJoinPredicate(*lhs, *rhs, predicate.uses)) } diff --git a/go/vt/vtgate/planbuilder/operators/ordering.go b/go/vt/vtgate/planbuilder/operators/ordering.go index 367cb3c75b1..3c1c0c434cb 100644 --- a/go/vt/vtgate/planbuilder/operators/ordering.go +++ b/go/vt/vtgate/planbuilder/operators/ordering.go @@ -81,8 +81,7 @@ func (o *Ordering) GetOrdering(*plancontext.PlanningContext) []OrderBy { } func (o *Ordering) planOffsets(ctx *plancontext.PlanningContext) Operator { - var weightStrings []*OrderBy - + weightStrings := make([]*OrderBy, 0, len(o.Order)) for _, order := range o.Order { offset := o.Source.AddColumn(ctx, true, false, aeWrap(order.SimplifiedExpr)) o.Offset = append(o.Offset, offset) diff --git a/go/vt/vtgate/planbuilder/operators/queryprojection.go b/go/vt/vtgate/planbuilder/operators/queryprojection.go index 957d6e39321..a9237c6517d 100644 --- a/go/vt/vtgate/planbuilder/operators/queryprojection.go +++ b/go/vt/vtgate/planbuilder/operators/queryprojection.go @@ -639,7 +639,7 @@ func (qp *QueryProjection) useGroupingOverDistinct(ctx *plancontext.PlanningCont if !qp.orderByOverlapWithSelectExpr(ctx) { return false } - var gbs []GroupBy + gbs := make([]GroupBy, 0, len(qp.SelectExprs)) for idx, selExpr := range qp.SelectExprs { ae, err := selExpr.GetAliasedExpr() if err != nil { diff --git a/go/vt/vtgate/planbuilder/operators/sharded_routing.go b/go/vt/vtgate/planbuilder/operators/sharded_routing.go index d43f115f443..21bdeadf031 100644 --- a/go/vt/vtgate/planbuilder/operators/sharded_routing.go +++ b/go/vt/vtgate/planbuilder/operators/sharded_routing.go @@ -486,7 +486,7 @@ func (tr *ShardedRouting) processMultiColumnVindex( return newVindexFound } - var newOption []*VindexOption + newOption := make([]*VindexOption, 0, len(v.Options)) for _, op := range v.Options { if op.Ready { continue diff --git a/go/vt/vtgate/planbuilder/operators/subquery_builder.go b/go/vt/vtgate/planbuilder/operators/subquery_builder.go index d9c29d936ab..5b1bb067191 100644 --- a/go/vt/vtgate/planbuilder/operators/subquery_builder.go +++ b/go/vt/vtgate/planbuilder/operators/subquery_builder.go @@ -343,8 +343,8 @@ func (sqb *SubQueryBuilder) pullOutValueSubqueries( if sqe == nil { return nil, nil } - var newSubqs []*SubQuery + newSubqs := make([]*SubQuery, 0, len(sqe.subq)) for idx, subq := range sqe.subq { sqInner := createSubquery(ctx, original, subq, outerID, original, sqe.cols[idx], sqe.pullOutCode[idx], true) newSubqs = append(newSubqs, sqInner) diff --git a/go/vt/vtgate/planbuilder/operators/table.go b/go/vt/vtgate/planbuilder/operators/table.go index 2cc561497f7..900d7511c15 100644 --- a/go/vt/vtgate/planbuilder/operators/table.go +++ b/go/vt/vtgate/planbuilder/operators/table.go @@ -43,7 +43,7 @@ type ( // Clone implements the Operator interface func (to *Table) Clone([]Operator) Operator { - var columns []*sqlparser.ColName + columns := make([]*sqlparser.ColName, 0, len(to.Columns)) for _, name := range to.Columns { columns = append(columns, sqlparser.Clone(name)) } diff --git a/go/vt/vtgate/planbuilder/operators/union_merging.go b/go/vt/vtgate/planbuilder/operators/union_merging.go index cd8acdab9d3..41c00861d6c 100644 --- a/go/vt/vtgate/planbuilder/operators/union_merging.go +++ b/go/vt/vtgate/planbuilder/operators/union_merging.go @@ -249,10 +249,9 @@ func compactUnion(u *Union) *ApplyResult { } } - var newSources []Operator - var newSelects [][]sqlparser.SelectExpr - merged := false - + var merged bool + newSources := make([]Operator, 0, len(u.Sources)) + newSelects := make([][]sqlparser.SelectExpr, 0, len(u.Sources)) for idx, source := range u.Sources { other, ok := source.(*Union) diff --git a/go/vt/vtgate/planbuilder/operators/update.go b/go/vt/vtgate/planbuilder/operators/update.go index 54c3f280319..12b492581e9 100644 --- a/go/vt/vtgate/planbuilder/operators/update.go +++ b/go/vt/vtgate/planbuilder/operators/update.go @@ -163,7 +163,7 @@ func createUpdateWithInputOp(ctx *plancontext.PlanningContext, upd *sqlparser.Up // Prepare the update expressions list ueMap := prepareUpdateExpressionList(ctx, upd) - var updOps []dmlOp + updOps := make([]dmlOp, 0, len(ctx.SemTable.DMLTargets.Constituents())) for _, target := range ctx.SemTable.DMLTargets.Constituents() { op := createUpdateOpWithTarget(ctx, upd, target, ueMap[target]) updOps = append(updOps, op) @@ -464,9 +464,8 @@ func createFKCascadeOp(ctx *plancontext.PlanningContext, parentOp Operator, updS return parentOp } - var fkChildren []*FkChild var selectExprs []sqlparser.SelectExpr - + fkChildren := make([]*FkChild, 0, len(childFks)) for _, fk := range childFks { // We should have already filtered out update restrict foreign keys. if fk.OnUpdate.IsRestrict() { @@ -774,11 +773,11 @@ func createFKVerifyOp( return childOp } - var Verify []*VerifyOp + verify := make([]*VerifyOp, 0, len(parentFks)+len(restrictChildFks)) // This validates that new values exists on the parent table. for _, fk := range parentFks { op := createFkVerifyOpForParentFKForUpdate(ctx, updatedTable, updStmt, fk) - Verify = append(Verify, &VerifyOp{ + verify = append(verify, &VerifyOp{ Op: op, Typ: engine.ParentVerify, }) @@ -786,15 +785,14 @@ func createFKVerifyOp( // This validates that the old values don't exist on the child table. for _, fk := range restrictChildFks { op := createFkVerifyOpForChildFKForUpdate(ctx, updatedTable, updStmt, fk) - - Verify = append(Verify, &VerifyOp{ + verify = append(verify, &VerifyOp{ Op: op, Typ: engine.ChildVerify, }) } return &FkVerify{ - Verify: Verify, + Verify: verify, Input: childOp, } } diff --git a/go/vt/vtgate/planbuilder/operators/upsert.go b/go/vt/vtgate/planbuilder/operators/upsert.go index 90cee8a5607..35778a34d99 100644 --- a/go/vt/vtgate/planbuilder/operators/upsert.go +++ b/go/vt/vtgate/planbuilder/operators/upsert.go @@ -54,7 +54,7 @@ func (u *Upsert) setInputs(inputs []Operator) { } func (u *Upsert) Inputs() []Operator { - var inputs []Operator + inputs := make([]Operator, 0, len(u.Sources)) for _, source := range u.Sources { inputs = append(inputs, source.Insert, source.Update) } diff --git a/go/vt/vtgate/planbuilder/show.go b/go/vt/vtgate/planbuilder/show.go index b6289d96d3b..da83dfd88e0 100644 --- a/go/vt/vtgate/planbuilder/show.go +++ b/go/vt/vtgate/planbuilder/show.go @@ -651,7 +651,7 @@ func buildEnginesPlan() (engine.Primitive, error) { func buildVschemaKeyspacesPlan(vschema plancontext.VSchema) (engine.Primitive, error) { vs := vschema.GetVSchema() - var rows [][]sqltypes.Value + rows := make([][]sqltypes.Value, 0, len(vs.Keyspaces)) for ksName, ks := range vs.Keyspaces { var row []sqltypes.Value row = append(row, sqltypes.NewVarChar(ksName)) @@ -680,7 +680,7 @@ func buildVschemaTablesPlan(vschema plancontext.VSchema) (engine.Primitive, erro return nil, vterrors.VT05003(ks.Name) } - var tables []string + tables := make([]string, 0, len(schemaKs.Tables)) for name := range schemaKs.Tables { tables = append(tables, name) } diff --git a/go/vt/vtgate/planbuilder/single_sharded_shortcut.go b/go/vt/vtgate/planbuilder/single_sharded_shortcut.go index 9188ff13552..27d682620b9 100644 --- a/go/vt/vtgate/planbuilder/single_sharded_shortcut.go +++ b/go/vt/vtgate/planbuilder/single_sharded_shortcut.go @@ -77,12 +77,12 @@ func getTableNames(semTable *semantics.SemTable) ([]sqlparser.TableName, error) } } } - var keys []string + keys := make([]string, 0, len(tableNameMap)) for k := range tableNameMap { keys = append(keys, k) } sort.Strings(keys) - var tableNames []sqlparser.TableName + tableNames := make([]sqlparser.TableName, 0, len(keys)) for _, k := range keys { tableNames = append(tableNames, tableNameMap[k]) } diff --git a/go/vt/vtgate/planbuilder/vexplain.go b/go/vt/vtgate/planbuilder/vexplain.go index 89f4bd2403c..7cac5966a8b 100644 --- a/go/vt/vtgate/planbuilder/vexplain.go +++ b/go/vt/vtgate/planbuilder/vexplain.go @@ -166,7 +166,7 @@ func explainPlan(explain *sqlparser.ExplainStmt, reservedVars *sqlparser.Reserve // Remove keyspace qualifier from columns and tables. sqlparser.RemoveKeyspace(explain.Statement) - var tables []string + tables := make([]string, 0, len(ctx.SemTable.Tables)) for _, table := range ctx.SemTable.Tables { name, err := table.Name() if err != nil { diff --git a/go/vt/vtgate/schema/tracker.go b/go/vt/vtgate/schema/tracker.go index 7661e702d93..4f5972ce6cb 100644 --- a/go/vt/vtgate/schema/tracker.go +++ b/go/vt/vtgate/schema/tracker.go @@ -409,7 +409,7 @@ func getForeignKeys(tblSpec *sqlparser.TableSpec) []*sqlparser.ForeignKeyDefinit if tblSpec.Constraints == nil { return nil } - var fks []*sqlparser.ForeignKeyDefinition + fks := make([]*sqlparser.ForeignKeyDefinition, 0, len(tblSpec.Constraints)) for _, constraint := range tblSpec.Constraints { fkDef, ok := constraint.Details.(*sqlparser.ForeignKeyDefinition) if !ok { diff --git a/go/vt/vtgate/semantics/early_rewriter.go b/go/vt/vtgate/semantics/early_rewriter.go index 7152a2d55bc..5e64e2eaec1 100644 --- a/go/vt/vtgate/semantics/early_rewriter.go +++ b/go/vt/vtgate/semantics/early_rewriter.go @@ -861,7 +861,7 @@ func handleComparisonExpr(cursor *sqlparser.Cursor, node *sqlparser.ComparisonEx if !lftOK || !rgtOK || len(lft) != len(rgt) || node.Operator != sqlparser.EqualOp { return nil } - var predicates []sqlparser.Expr + predicates := make([]sqlparser.Expr, 0, len(lft)) for i, l := range lft { r := rgt[i] predicates = append(predicates, &sqlparser.ComparisonExpr{ @@ -1021,7 +1021,7 @@ func findTablesWithColumn(b *binder, join *sqlparser.JoinTableExpr, column sqlpa if leftTableInfo == nil || rightTableInfo == nil { return nil, ShardedError{Inner: vterrors.VT09015()} } - var tableNames []sqlparser.TableName + tableNames := make([]sqlparser.TableName, 0, len(leftTableInfo)) for _, info := range leftTableInfo { nm, err := info.Name() if err != nil { diff --git a/go/vt/vtgate/semantics/real_table.go b/go/vt/vtgate/semantics/real_table.go index 3c6e8a5e56d..9a16c10e031 100644 --- a/go/vt/vtgate/semantics/real_table.go +++ b/go/vt/vtgate/semantics/real_table.go @@ -152,7 +152,7 @@ func (r *RealTable) authoritative() bool { } func extractSelectExprsFromCTE(selectExprs []sqlparser.SelectExpr) []ColumnInfo { - var ci []ColumnInfo + ci := make([]ColumnInfo, 0, len(selectExprs)) for _, expr := range selectExprs { ae, ok := expr.(*sqlparser.AliasedExpr) if !ok { diff --git a/go/vt/vtgate/semantics/table_collector.go b/go/vt/vtgate/semantics/table_collector.go index 1b3f4752721..03574c09464 100644 --- a/go/vt/vtgate/semantics/table_collector.go +++ b/go/vt/vtgate/semantics/table_collector.go @@ -231,9 +231,10 @@ func (tc *tableCollector) handleDefaultColumns(origTableInfo TableInfo) ([]strin if !origTableInfo.authoritative() { return nil, nil, vterrors.VT09015() } - var colNames []string - var types []evalengine.Type - for _, column := range origTableInfo.getColumns(true /* ignoreInvisibleCol */) { + cols := origTableInfo.getColumns(true /* ignoreInvisibleCol */) + colNames := make([]string, 0, len(cols)) + types := make([]evalengine.Type, 0, len(cols)) + for _, column := range cols { colNames = append(colNames, column.Name) types = append(types, column.Type) } @@ -242,9 +243,9 @@ func (tc *tableCollector) handleDefaultColumns(origTableInfo TableInfo) ([]strin // handleInsertColumns have explicit column list on the insert statement and no column list on the row alias func (tc *tableCollector) handleInsertColumns(ins *sqlparser.Insert, origTableInfo TableInfo) ([]string, []evalengine.Type) { - var colNames []string - var types []evalengine.Type origCols := origTableInfo.getColumns(false /* ignoreInvisbleCol */) + colNames := make([]string, 0, len(ins.Columns)) + types := make([]evalengine.Type, 0, len(ins.Columns)) for2: for _, column := range ins.Columns { colNames = append(colNames, column.String()) @@ -268,8 +269,8 @@ func (tc *tableCollector) handleRowAliasColumns(origTableInfo TableInfo, rowAlia if len(rowAlias.Columns) != len(origCols) { return nil, nil, vterrors.VT03033() } - var colNames []string - var types []evalengine.Type + colNames := make([]string, 0, len(rowAlias.Columns)) + types := make([]evalengine.Type, 0, len(rowAlias.Columns)) for idx, column := range rowAlias.Columns { colNames = append(colNames, column.String()) types = append(types, origCols[idx].Type) diff --git a/go/vt/vtgate/vindexes/lookup_internal.go b/go/vt/vtgate/vindexes/lookup_internal.go index 6293209f31f..19520fc7b40 100644 --- a/go/vt/vtgate/vindexes/lookup_internal.go +++ b/go/vt/vtgate/vindexes/lookup_internal.go @@ -91,8 +91,9 @@ type lookupInternal struct { func (lkp *lookupInternal) Init(lookupQueryParams map[string]string, autocommit, upsert, multiShardAutocommit bool) error { lkp.Table = lookupQueryParams[lookupInternalParamTable] lkp.To = lookupQueryParams[lookupInternalParamTo] - var fromColumns []string - for _, from := range strings.Split(lookupQueryParams[lookupInternalParamFrom], ",") { + splitParams := strings.Split(lookupQueryParams[lookupInternalParamFrom], ",") + fromColumns := make([]string, 0, len(splitParams)) + for _, from := range splitParams { fromColumns = append(fromColumns, strings.TrimSpace(from)) } lkp.FromColumns = fromColumns diff --git a/go/vt/vtorc/inst/instance_dao.go b/go/vt/vtorc/inst/instance_dao.go index 8b1899b6068..efc6e76f402 100644 --- a/go/vt/vtorc/inst/instance_dao.go +++ b/go/vt/vtorc/inst/instance_dao.go @@ -891,7 +891,7 @@ func mkInsertForInstances(instances []*Instance, instanceWasActuallyFound bool, values = append(values, "DATETIME('now')") } - var args []any + args := make([]any, 0) for _, instance := range instances { // number of columns minus 2 as last_checked and last_attempted_check // updated with NOW() @@ -1194,7 +1194,7 @@ func GetDatabaseState() (string, error) { Rows []sqlutils.RowMap } - var dbState []tableState + dbState := make([]tableState, 0, len(db.TableNames)) for _, tableName := range db.TableNames { ts := tableState{ TableName: tableName, diff --git a/go/vt/vttablet/sandboxconn/sandboxconn.go b/go/vt/vttablet/sandboxconn/sandboxconn.go index e6a13199204..76a84bbd1ed 100644 --- a/go/vt/vttablet/sandboxconn/sandboxconn.go +++ b/go/vt/vttablet/sandboxconn/sandboxconn.go @@ -203,7 +203,7 @@ func (sbc *SandboxConn) GetFinalQueries() ([]string, error) { sbc.queriesMu.Lock() defer sbc.queriesMu.Unlock() } - var queries []string + queries := make([]string, 0, len(sbc.Queries)) for _, q := range sbc.Queries { stmt, err := sbc.parser.Parse(q.Sql) if err != nil { diff --git a/go/vt/vttablet/tabletmanager/vdiff/utils.go b/go/vt/vttablet/tabletmanager/vdiff/utils.go index e56df52c5cc..d1086cbaa25 100644 --- a/go/vt/vttablet/tabletmanager/vdiff/utils.go +++ b/go/vt/vttablet/tabletmanager/vdiff/utils.go @@ -62,7 +62,7 @@ func encodeString(in string) string { } func pkColsToGroupByParams(pkCols []int, collationEnv *collations.Environment) []*engine.GroupByParams { - var res []*engine.GroupByParams + res := make([]*engine.GroupByParams, 0, len(pkCols)) for _, col := range pkCols { res = append(res, &engine.GroupByParams{KeyCol: col, WeightStringCol: -1, CollationEnv: collationEnv}) } diff --git a/go/vt/vttablet/tabletmanager/vreplication/engine.go b/go/vt/vttablet/tabletmanager/vreplication/engine.go index fae0ba0796f..7b2301a16f1 100644 --- a/go/vt/vttablet/tabletmanager/vreplication/engine.go +++ b/go/vt/vttablet/tabletmanager/vreplication/engine.go @@ -685,7 +685,7 @@ func (vre *Engine) transitionJournal(je *journalEvent) { log.Errorf("transitionJournal: %v", err) return } - var newids []int32 + newids := make([]int32, 0, len(shardGTIDs)) for _, shard := range shardGTIDs { sgtid := je.shardGTIDs[shard] bls := vre.controllers[refid].source.CloneVT() diff --git a/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go b/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go index 95e4c98dda9..d7c31765385 100644 --- a/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go +++ b/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go @@ -149,7 +149,7 @@ func (rp *ReplicatorPlan) buildFromFields(tableName string, lastpk *sqltypes.Res // MarshalJSON performs a custom JSON Marshalling. func (rp *ReplicatorPlan) MarshalJSON() ([]byte, error) { - var targets []string + targets := make([]string, 0, len(rp.TargetTables)) for k := range rp.TargetTables { targets = append(targets, k) } diff --git a/go/vt/vttablet/tabletmanager/vreplication/table_plan_builder.go b/go/vt/vttablet/tabletmanager/vreplication/table_plan_builder.go index 6517d93c792..71d5fc9a6e1 100644 --- a/go/vt/vttablet/tabletmanager/vreplication/table_plan_builder.go +++ b/go/vt/vttablet/tabletmanager/vreplication/table_plan_builder.go @@ -939,8 +939,8 @@ func (tpb *tablePlanBuilder) generatePKConstraint(buf *sqlparser.TrackedBuffer, charSet string collation string } - var charSetCollations []*charSetCollation separator := "(" + charSetCollations := make([]*charSetCollation, 0, len(tpb.lastpk.Fields)) for _, pkname := range tpb.lastpk.Fields { charSet, collation := tpb.getCharsetAndCollation(pkname.Name) charSetCollations = append(charSetCollations, &charSetCollation{charSet: charSet, collation: collation}) diff --git a/go/vt/vttablet/tabletserver/planbuilder/permission.go b/go/vt/vttablet/tabletserver/planbuilder/permission.go index 03f926e0679..0b1320ae01d 100644 --- a/go/vt/vttablet/tabletserver/planbuilder/permission.go +++ b/go/vt/vttablet/tabletserver/planbuilder/permission.go @@ -122,7 +122,7 @@ func buildSubqueryPermissions(stmt sqlparser.Statement, role tableacl.Role, perm // gatherCTEs gathers the CTEs from the WITH clause. func gatherCTEs(with *sqlparser.With) []sqlparser.IdentifierCS { - var ctes []sqlparser.IdentifierCS + ctes := make([]sqlparser.IdentifierCS, 0, len(with.CTEs)) for _, cte := range with.CTEs { ctes = append(ctes, cte.ID) } diff --git a/go/vt/vttablet/tabletserver/schema/db.go b/go/vt/vttablet/tabletserver/schema/db.go index 7b328c518d2..4929ce2e612 100644 --- a/go/vt/vttablet/tabletserver/schema/db.go +++ b/go/vt/vttablet/tabletserver/schema/db.go @@ -135,7 +135,7 @@ func reloadTablesDataInDB(ctx context.Context, conn *connpool.Conn, tables []*Ta bv := map[string]*querypb.BindVariable{"tableNames": tablesBV} // Get the create statements for all the tables that are modified. - var createStatements []string + createStatements := make([]string, 0, len(tables)) for _, table := range tables { cs, err := getCreateStatement(ctx, conn, sqlparser.String(table.Name)) if err != nil { @@ -220,7 +220,7 @@ func reloadViewsDataInDB(ctx context.Context, conn *connpool.Conn, views []*Tabl bv := map[string]*querypb.BindVariable{"viewNames": viewsBV} // Get the create statements for all the views that are modified. - var createStatements []string + createStatements := make([]string, 0, len(views)) for _, view := range views { cs, err := getCreateStatement(ctx, conn, sqlparser.String(view.Name)) if err != nil { diff --git a/go/vt/vttablet/tabletserver/schema/engine.go b/go/vt/vttablet/tabletserver/schema/engine.go index 31646744c24..ac1a9646866 100644 --- a/go/vt/vttablet/tabletserver/schema/engine.go +++ b/go/vt/vttablet/tabletserver/schema/engine.go @@ -982,7 +982,7 @@ func (se *Engine) RegisterNotifier(name string, f notifier, runNotifier bool) { defer se.notifierMu.Unlock() se.notifiers[name] = f - var created []*Table + created := make([]*Table, 0, len(se.tables)) for _, table := range se.tables { created = append(created, table) } @@ -1136,7 +1136,7 @@ func (se *Engine) Environment() *vtenv.Environment { } func extractNamesFromTablesList(tables []*Table) []string { - var tableNames []string + tableNames := make([]string, 0, len(tables)) for _, table := range tables { tableNames = append(tableNames, table.Name.String()) } diff --git a/go/vt/vttablet/tabletserver/vstreamer/copy.go b/go/vt/vttablet/tabletserver/vstreamer/copy.go index daeb4349b90..57a53ca450d 100644 --- a/go/vt/vttablet/tabletserver/vstreamer/copy.go +++ b/go/vt/vttablet/tabletserver/vstreamer/copy.go @@ -130,7 +130,7 @@ func (uvs *uvstreamer) sendFieldEvent(ctx context.Context, gtid string, fieldEve // send one RowEvent per row, followed by a LastPK (merged in VTGate with vgtid) func (uvs *uvstreamer) sendEventsForRows(ctx context.Context, tableName string, rows *binlogdatapb.VStreamRowsResponse, qr *querypb.QueryResult) error { - var evs []*binlogdatapb.VEvent + evs := make([]*binlogdatapb.VEvent, 0, len(rows.Rows)) for _, row := range rows.Rows { ev := &binlogdatapb.VEvent{ Type: binlogdatapb.VEventType_ROW, diff --git a/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go b/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go index 2cbb59acb02..523817c7b7c 100644 --- a/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go +++ b/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go @@ -889,8 +889,8 @@ func (vs *vstreamer) buildTablePlan(id uint64, tm *mysql.TableMap) (*binlogdatap } func (vs *vstreamer) buildTableColumns(tm *mysql.TableMap) ([]*querypb.Field, error) { - var fields []*querypb.Field var txtFieldIdx int + fields := make([]*querypb.Field, 0, len(tm.Types)) for i, typ := range tm.Types { t, err := sqltypes.MySQLToType(typ, 0) if err != nil { diff --git a/go/vt/wrangler/materializer.go b/go/vt/wrangler/materializer.go index 42f710a2bce..9ca1ed02002 100644 --- a/go/vt/wrangler/materializer.go +++ b/go/vt/wrangler/materializer.go @@ -419,7 +419,7 @@ func (wr *Wrangler) getKeyspaceTables(ctx context.Context, ks string, ts *topo.S } log.Infof("got table schemas from source primary %v.", primary) - var sourceTables []string + sourceTables := make([]string, 0, len(schema.TableDefinitions)) for _, td := range schema.TableDefinitions { sourceTables = append(sourceTables, td.Name) } @@ -680,7 +680,7 @@ func (wr *Wrangler) prepareCreateLookup(ctx context.Context, keyspace string, sp // Unreachable return nil, nil, nil, fmt.Errorf("schema looks incorrect: %s, expecting at least four lines", tableSchema.TableDefinitions[0].Schema) } - var modified []string + modified := make([]string, 0) modified = append(modified, strings.Replace(lines[0], sourceTableName, targetTableName, 1)) for i := range sourceVindexColumns { line, err := generateColDef(lines, sourceVindexColumns[i], vindexFromCols[i]) @@ -1606,7 +1606,7 @@ func (mz *materializer) filterSourceShards(targetShard *topo.ShardInfo) []*topo. return mz.sourceShards } // Use intersecting source shards. - var filteredSourceShards []*topo.ShardInfo + filteredSourceShards := make([]*topo.ShardInfo, 0, len(mz.sourceShards)) for _, sourceShard := range mz.sourceShards { if !key.KeyRangeIntersect(sourceShard.KeyRange, targetShard.KeyRange) { continue diff --git a/go/vt/wrangler/switcher_dry_run.go b/go/vt/wrangler/switcher_dry_run.go index 1391230bc77..2b9b8f4f432 100644 --- a/go/vt/wrangler/switcher_dry_run.go +++ b/go/vt/wrangler/switcher_dry_run.go @@ -83,7 +83,7 @@ func (dr *switcherDryRun) switchTableReads(ctx context.Context, cells []string, if direction == workflow.DirectionBackward { ks = dr.ts.SourceKeyspaceName() } - var tabletTypes []string + tabletTypes := make([]string, 0, len(servedTypes)) for _, servedType := range servedTypes { tabletTypes = append(tabletTypes, servedType.String()) } @@ -110,14 +110,13 @@ func (dr *switcherDryRun) allowTargetWrites(ctx context.Context) error { func (dr *switcherDryRun) changeRouting(ctx context.Context) error { dr.drLog.Log(fmt.Sprintf("Switch routing from keyspace %s to keyspace %s", dr.ts.SourceKeyspaceName(), dr.ts.TargetKeyspaceName())) - var deleteLogs, addLogs []string if dr.ts.MigrationType() == binlogdatapb.MigrationType_TABLES { tables := strings.Join(dr.ts.Tables(), ",") dr.drLog.Log(fmt.Sprintf("Routing rules for tables [%s] will be updated", tables)) return nil } - deleteLogs = nil - addLogs = nil + deleteLogs := make([]string, 0, len(dr.ts.Sources())) + addLogs := make([]string, 0, len(dr.ts.Targets())) for _, source := range dr.ts.Sources() { deleteLogs = append(deleteLogs, fmt.Sprintf("\tShard %s, Tablet %d", source.GetShard().ShardName(), source.GetShard().PrimaryAlias.Uid)) } diff --git a/go/vt/wrangler/traffic_switcher.go b/go/vt/wrangler/traffic_switcher.go index dcebe8c16c9..ca32a950ffe 100644 --- a/go/vt/wrangler/traffic_switcher.go +++ b/go/vt/wrangler/traffic_switcher.go @@ -1011,7 +1011,8 @@ func (wr *Wrangler) buildTrafficSwitcher(ctx context.Context, targetKeyspace, wo } func (ts *trafficSwitcher) getSourceAndTargetShardsNames() ([]string, []string) { - var sourceShards, targetShards []string + sourceShards := make([]string, 0, len(ts.SourceShards())) + targetShards := make([]string, 0, len(ts.TargetShards())) for _, si := range ts.SourceShards() { sourceShards = append(sourceShards, si.ShardName()) } diff --git a/go/vt/wrangler/vdiff.go b/go/vt/wrangler/vdiff.go index 345053078a9..cb301e66ffe 100644 --- a/go/vt/wrangler/vdiff.go +++ b/go/vt/wrangler/vdiff.go @@ -783,7 +783,7 @@ func (df *vdiff) buildTablePlan(table *tabletmanagerdatapb.TableDefinition, quer } func pkColsToGroupByParams(pkCols []int, collationEnv *collations.Environment) []*engine.GroupByParams { - var res []*engine.GroupByParams + res := make([]*engine.GroupByParams, 0, len(pkCols)) for _, col := range pkCols { res = append(res, &engine.GroupByParams{KeyCol: col, WeightStringCol: -1, Type: evalengine.Type{}, CollationEnv: collationEnv}) } diff --git a/go/vt/wrangler/vexec.go b/go/vt/wrangler/vexec.go index 55dd59b48ea..4be675a03d9 100644 --- a/go/vt/wrangler/vexec.go +++ b/go/vt/wrangler/vexec.go @@ -100,12 +100,12 @@ func (wr *Wrangler) QueryResultForRowsAffected(results map[*topo.TabletInfo]*sql Name: "RowsAffected", Type: sqltypes.Uint64, }} - var row2 []sqltypes.Value + row2 := make([]sqltypes.Value, 0, 2) for tablet, result := range results { - row2 = nil row2 = append(row2, sqltypes.NewVarBinary(tablet.AliasString())) row2 = append(row2, sqltypes.NewUint64(result.RowsAffected)) qr.Rows = append(qr.Rows, row2) + row2 = row2[:0] // reset the slice } return qr } @@ -296,8 +296,8 @@ func (vx *vexec) getPrimaries(shards []string) error { return err } - var allPrimaries []*topo.TabletInfo var primary *topo.TabletInfo + allPrimaries := make([]*topo.TabletInfo, 0, len(shards)) for _, shard := range shards { if primary, err = vx.getPrimaryForShard(shard); err != nil { return err diff --git a/go/vt/wrangler/vexec_test.go b/go/vt/wrangler/vexec_test.go index 89cdc991ad2..f5f25b7c8fd 100644 --- a/go/vt/wrangler/vexec_test.go +++ b/go/vt/wrangler/vexec_test.go @@ -67,7 +67,7 @@ func TestVExec(t *testing.T) { primaries := vx.primaries require.NotNil(t, primaries) require.Equal(t, len(primaries), 2) - var shards []string + shards := make([]string, 0, len(primaries)) for _, primary := range primaries { shards = append(shards, primary.Shard) } @@ -247,7 +247,7 @@ func TestWorkflowListStreams(t *testing.T) { require.Nil(t, err) // convert map to list and sort it for comparison - var gotResults []string + gotResults := make([]string, 0, len(results)) for key, result := range results { gotResults = append(gotResults, fmt.Sprintf("%s:%v", key.String(), result)) } diff --git a/go/vt/wrangler/workflow.go b/go/vt/wrangler/workflow.go index fc16257b3dc..d3bbcf8dd77 100644 --- a/go/vt/wrangler/workflow.go +++ b/go/vt/wrangler/workflow.go @@ -633,7 +633,7 @@ func (vrw *VReplicationWorkflow) GetCopyProgress() (*CopyProgress, error) { if len(tables) == 0 { return nil, nil } - var tableList []string + tableList := make([]string, 0, len(tables)) targetRowCounts := make(map[string]int64) sourceRowCounts := make(map[string]int64) targetTableSizes := make(map[string]int64)