From be0bb2497959bc4c1169ac1111cb63b0c8af301a Mon Sep 17 00:00:00 2001 From: Stas Maksimov Date: Thu, 26 Oct 2023 16:28:04 +0100 Subject: [PATCH] gofmt --- examples/local/vstream_client.go | 4 +- go/acl/acl.go | 4 +- go/cache/ristretto/policy.go | 3 +- go/cmd/tools.go | 2 +- go/cmd/vtbackup/plugin_cephbackupstorage.go | 2 +- go/cmd/vtbackup/plugin_filebackupstorage.go | 2 +- go/cmd/vtbackup/plugin_gcsbackupstorage.go | 2 +- go/cmd/vtbackup/plugin_s3backupstorage.go | 2 +- go/cmd/vtbackup/vtbackup.go | 36 ++++---- go/cmd/vtctldclient/command/doc.go | 1 + go/flagutil/sets.go | 4 +- go/internal/flag/flag.go | 1 + go/internal/flag/usage.go | 2 +- go/mysql/binlog_event_common.go | 87 +++++++++--------- go/mysql/binlog_event_filepos.go | 7 +- go/mysql/binlog_event_json.go | 4 +- go/mysql/binlog_event_mariadb.go | 9 +- go/mysql/binlog_event_mysql56.go | 9 +- go/mysql/binlog_event_rbr.go | 43 ++++----- go/mysql/fakesqldb/server.go | 4 +- go/mysql/flavor_mysqlgr_test.go | 2 +- go/mysql/ldapauthserver/auth_server_ldap.go | 2 +- go/mysql/mariadb_gtid.go | 2 +- go/mysql/mysql56_gtid_set.go | 17 ++-- go/mysql/query_test.go | 2 +- go/mysql/vault/auth_server_vault.go | 3 +- go/netutil/netutil.go | 7 +- go/pools/numbered.go | 6 +- go/sqltypes/testing.go | 38 ++++---- go/sqltypes/type.go | 20 ++--- go/test/endtoend/docker/vttestserver.go | 2 +- go/test/endtoend/migration/migration_test.go | 37 ++++---- go/test/endtoend/reparent/utils/utils.go | 2 +- .../tabletmanager/tablegc/tablegc_test.go | 2 +- go/test/endtoend/vault/vault_test.go | 3 +- .../vtctldweb/vtctld_web_main_test.go | 2 +- .../endtoend/vtgate/prefixfanout/main_test.go | 4 +- go/test/stress/stress.go | 5 +- go/test/utils/diff.go | 22 ++--- go/testfiles/ports.go | 4 - go/tools/asthelpergen/integration/types.go | 2 +- go/tools/sizegen/integration/types.go | 2 +- go/vt/binlog/binlog_connection.go | 1 + go/vt/concurrency/error_group.go | 15 ++-- go/vt/discovery/legacy_healthcheck.go | 13 +-- go/vt/discovery/legacy_replicationlag.go | 8 +- go/vt/discovery/replicationlag.go | 8 +- go/vt/events/status.go | 10 +-- go/vt/grpcoptionaltls/conn_wrapper.go | 4 +- go/vt/grpcoptionaltls/optionaltls.go | 4 +- go/vt/grpcoptionaltls/server_test.go | 4 +- go/vt/grpcoptionaltls/tls_detector.go | 4 +- go/vt/mysqlctl/builtinbackupengine_test.go | 3 +- go/vt/mysqlctl/mycnf_flag.go | 16 ++-- go/vt/mysqlctl/schema.go | 6 +- go/vt/orchestrator/collection/collection.go | 10 +-- go/vt/orchestrator/inst/instance_binlog.go | 3 - go/vt/orchestrator/inst/instance_key.go | 1 - go/vt/orchestrator/logic/orchestrator.go | 2 +- go/vt/orchestrator/os/unixcheck_test.go | 20 ++--- go/vt/proto/vtrpc/vtrpc.pb.go | 4 +- go/vt/schemadiff/table.go | 8 +- go/vt/schemadiff/view.go | 1 - go/vt/schemamanager/local_controller.go | 44 ++++----- go/vt/schemamanager/tablet_executor.go | 4 +- go/vt/sqlparser/analyzer.go | 8 +- go/vt/sqlparser/bind_var_needs.go | 12 +-- go/vt/sqlparser/comments.go | 2 +- go/vt/sqlparser/constants.go | 2 +- go/vt/sqlparser/goyacc/goyacc.go | 78 ---------------- go/vt/sqlparser/parsed_query.go | 3 +- go/vt/sqlparser/parser.go | 5 +- go/vt/sqlparser/precedence.go | 4 +- go/vt/sqlparser/random_expr.go | 17 ++-- go/vt/sqlparser/rewriter_api.go | 1 - go/vt/tableacl/tableacl.go | 20 ++--- go/vt/throttler/throttler.go | 3 +- go/vt/topo/conn.go | 49 +++++----- go/vt/topo/helpers/tee.go | 7 +- .../clientset/versioned/fake/register.go | 14 +-- .../clientset/versioned/scheme/register.go | 14 +-- go/vt/topo/locks.go | 21 ++--- go/vt/topo/server.go | 28 +++--- go/vt/topo/shard.go | 8 +- go/vt/topo/stats_conn_test.go | 18 ++-- go/vt/topo/topotests/srv_vschema_test.go | 2 +- go/vt/topo/wildcards.go | 18 ++-- go/vt/topo/zk2topo/election.go | 8 +- go/vt/topo/zk2topo/server.go | 16 ++-- go/vt/topo/zk2topo/zk_conn.go | 12 +-- go/vt/topotools/tablet.go | 13 ++- go/vt/topotools/utils.go | 10 +-- go/vt/vitessdriver/driver.go | 2 +- go/vt/vitessdriver/time.go | 10 +-- go/vt/vtadmin/cache/cache.go | 13 ++- go/vt/vtadmin/cluster/config.go | 14 +-- .../cluster/discovery/discovery_json.go | 18 ++-- .../discovery/discovery_static_file.go | 18 ++-- go/vt/vtadmin/cluster/dynamic/cluster.go | 19 ++-- go/vt/vtadmin/cluster/file_config.go | 19 ++-- go/vt/vtadmin/grpcserver/server.go | 4 +- go/vt/vtadmin/http/handlers/trace.go | 10 +-- go/vt/vtadmin/http/replication.go | 6 +- go/vt/vtadmin/http/tablets.go | 4 +- go/vt/vtadmin/rbac/authorization.go | 30 +++---- go/vt/vtadmin/testutil/tablets.go | 3 +- go/vt/vtadmin/vtsql/fakevtsql/doc.go | 32 +++---- .../testutil/test_tmclient.go | 7 +- go/vt/vtctl/internal/grpcshim/bidi_stream.go | 89 +++++++++---------- go/vt/vtctl/workflow/doc.go | 5 ++ go/vt/vtctl/workflow/vexec/query_planner.go | 2 +- go/vt/vterrors/stack.go | 24 ++--- go/vt/vterrors/vterrors.go | 49 +++++----- go/vt/vtgate/engine/lock.go | 2 +- go/vt/vtgate/engine/online_ddl.go | 2 +- go/vt/vtgate/engine/revert_migration.go | 2 +- go/vt/vtgate/engine/send.go | 2 +- go/vt/vtgate/engine/vschema_ddl.go | 2 +- go/vt/vtgate/evalengine/comparisons.go | 2 +- go/vt/vtgate/evalengine/evalengine.go | 6 +- .../evalengine/integration/comparison_test.go | 16 ++-- .../evalengine/internal/decimal/decimal.go | 82 +++++++++-------- .../evalengine/internal/decimal/scan.go | 12 ++- go/vt/vtgate/executor_vschema_ddl_test.go | 2 +- go/vt/vtgate/grpcvtgateservice/no_test.go | 4 + go/vt/vtgate/planbuilder/ordered_aggregate.go | 31 +++---- .../vtgate/planbuilder/sql_calc_found_rows.go | 2 +- go/vt/vtgate/vindexes/cfc.go | 20 ++--- go/vt/vtgate/vindexes/consistent_lookup.go | 14 +-- go/vt/vtgate/vindexes/lookup.go | 24 ++--- go/vt/vtgate/vindexes/lookup_hash.go | 24 ++--- .../vindexes/lookup_unicodeloosemd5_hash.go | 24 ++--- go/vt/vttablet/grpctmclient/cached_client.go | 24 ++--- go/vt/vttablet/grpctmclient/client.go | 6 +- go/vt/vttablet/onlineddl/vrepl/unique_key.go | 6 +- go/vt/vttablet/sandboxconn/sandboxconn.go | 2 +- .../vttablet/tabletmanager/rpc_replication.go | 8 +- go/vt/vttablet/tabletmanager/rpc_server.go | 1 - go/vt/vttablet/tabletmanager/tm_state_test.go | 4 +- .../tabletmanager/vdiff/controller.go | 4 +- go/vt/vttablet/tabletmanager/vdiff/doc.go | 2 - .../tabletmanager/vreplication/engine.go | 2 + .../vreplication/shard_sorter.go | 10 +-- .../tabletmanager/vreplication/vplayer.go | 61 +++++++------ .../tabletmanager/vreplication/vreplicator.go | 41 ++++----- .../tabletserver/stateful_connection_pool.go | 2 +- go/vt/vttablet/tabletserver/tabletserver.go | 13 +-- go/vt/vttablet/tabletserver/tx/api.go | 2 +- go/vt/vttablet/tabletserver/tx_pool.go | 2 +- .../txserializer/tx_serializer.go | 18 ++-- .../tabletserver/txthrottler/tx_throttler.go | 29 +++--- .../tabletserver/vstreamer/vstreamer.go | 26 +++--- go/vt/vttablet/tabletservermock/controller.go | 2 +- go/vt/vttablet/vexec/vexec.go | 34 +++---- go/vt/vttime/doc.go | 11 ++- go/vt/wrangler/materializer.go | 1 - go/vt/zkctl/zkconf.go | 10 +-- tools/coverage-go/mysqlctl_test.go | 2 +- tools/coverage-go/vtctl_test.go | 2 +- tools/coverage-go/vtctld_test.go | 2 +- tools/coverage-go/vtgate_test.go | 2 +- 161 files changed, 992 insertions(+), 988 deletions(-) diff --git a/examples/local/vstream_client.go b/examples/local/vstream_client.go index be74f1976a3..98d2129f898 100644 --- a/examples/local/vstream_client.go +++ b/examples/local/vstream_client.go @@ -33,8 +33,8 @@ import ( ) /* - This is a sample client for streaming using the vstream API. It is setup to work with the local example and you can - either stream from the unsharded commerce keyspace or the customer keyspace after the sharding step. + This is a sample client for streaming using the vstream API. It is setup to work with the local example and you can + either stream from the unsharded commerce keyspace or the customer keyspace after the sharding step. */ func main() { ctx := context.Background() diff --git a/go/acl/acl.go b/go/acl/acl.go index 0d2c070d469..1f60548dc7b 100644 --- a/go/acl/acl.go +++ b/go/acl/acl.go @@ -28,9 +28,9 @@ limitations under the License. // // For convenience, there are two other built-in policies that also do NOT do // any authentication, but allow you to globally disable some roles entirely: -// * `deny-all` disallows all roles for everyone. Note that access is still +// - `deny-all` disallows all roles for everyone. Note that access is still // allowed to endpoints that are considered "public" (no ACL check at all). -// * `read-only` allows anyone to act as DEBUGGING or MONITORING, but no one +// - `read-only` allows anyone to act as DEBUGGING or MONITORING, but no one // is allowed to act as ADMIN. It also disallows any other custom roles that // are requested. package acl diff --git a/go/cache/ristretto/policy.go b/go/cache/ristretto/policy.go index 38ffbf6d3d6..84cc008cb99 100644 --- a/go/cache/ristretto/policy.go +++ b/go/cache/ristretto/policy.go @@ -34,7 +34,8 @@ const ( // policy is the interface encapsulating eviction/admission behavior. // // TODO: remove this interface and just rename defaultPolicy to policy, as we -// are probably only going to use/implement/maintain one policy. +// +// are probably only going to use/implement/maintain one policy. type policy interface { ringConsumer // Add attempts to Add the key-cost pair to the Policy. It returns a slice diff --git a/go/cmd/tools.go b/go/cmd/tools.go index c039a52932c..9449331c570 100644 --- a/go/cmd/tools.go +++ b/go/cmd/tools.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/cmd/vtbackup/plugin_cephbackupstorage.go b/go/cmd/vtbackup/plugin_cephbackupstorage.go index 1e96b47981d..819cb108126 100644 --- a/go/cmd/vtbackup/plugin_cephbackupstorage.go +++ b/go/cmd/vtbackup/plugin_cephbackupstorage.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/cmd/vtbackup/plugin_filebackupstorage.go b/go/cmd/vtbackup/plugin_filebackupstorage.go index f0cc0add3f1..31417781026 100644 --- a/go/cmd/vtbackup/plugin_filebackupstorage.go +++ b/go/cmd/vtbackup/plugin_filebackupstorage.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/cmd/vtbackup/plugin_gcsbackupstorage.go b/go/cmd/vtbackup/plugin_gcsbackupstorage.go index 43946b7643a..2319d0aa7fe 100644 --- a/go/cmd/vtbackup/plugin_gcsbackupstorage.go +++ b/go/cmd/vtbackup/plugin_gcsbackupstorage.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/cmd/vtbackup/plugin_s3backupstorage.go b/go/cmd/vtbackup/plugin_s3backupstorage.go index 30100d85f70..917352f2469 100644 --- a/go/cmd/vtbackup/plugin_s3backupstorage.go +++ b/go/cmd/vtbackup/plugin_s3backupstorage.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/cmd/vtbackup/vtbackup.go b/go/cmd/vtbackup/vtbackup.go index b7dedd2eb20..41e55fad31e 100644 --- a/go/cmd/vtbackup/vtbackup.go +++ b/go/cmd/vtbackup/vtbackup.go @@ -22,26 +22,26 @@ When run periodically for each shard, vtbackup can ensure these configurable pol * Old backups for the shard are removed. Whatever system launches vtbackup is responsible for the following: -* Running vtbackup with similar flags that would be used for a vttablet and - mysqlctld in the target shard to be backed up. -* Provisioning as much disk space for vtbackup as would be given to vttablet. - The data directory MUST be empty at startup. Do NOT reuse a persistent disk. -* Running vtbackup periodically for each shard, for each backup storage location. -* Ensuring that at most one instance runs at a time for a given pair of shard - and backup storage location. -* Retrying vtbackup if it fails. -* Alerting human operators if the failure is persistent. + - Running vtbackup with similar flags that would be used for a vttablet and + mysqlctld in the target shard to be backed up. + - Provisioning as much disk space for vtbackup as would be given to vttablet. + The data directory MUST be empty at startup. Do NOT reuse a persistent disk. + - Running vtbackup periodically for each shard, for each backup storage location. + - Ensuring that at most one instance runs at a time for a given pair of shard + and backup storage location. + - Retrying vtbackup if it fails. + - Alerting human operators if the failure is persistent. The process vtbackup follows to take a new backup is as follows: -1. Restore from the most recent backup. -2. Start a mysqld instance (but no vttablet) from the restored data. -3. Instruct mysqld to connect to the current shard primary and replicate any - transactions that are new since the last backup. -4. Ask the primary for its current replication position and set that as the goal - for catching up on replication before taking the backup, so the goalposts - don't move. -5. Wait until replication is caught up to the goal position or beyond. -6. Stop mysqld and take a new backup. + 1. Restore from the most recent backup. + 2. Start a mysqld instance (but no vttablet) from the restored data. + 3. Instruct mysqld to connect to the current shard primary and replicate any + transactions that are new since the last backup. + 4. Ask the primary for its current replication position and set that as the goal + for catching up on replication before taking the backup, so the goalposts + don't move. + 5. Wait until replication is caught up to the goal position or beyond. + 6. Stop mysqld and take a new backup. Aside from additional replication load while vtbackup's mysqld catches up on new transactions, the shard should be otherwise unaffected. Existing tablets diff --git a/go/cmd/vtctldclient/command/doc.go b/go/cmd/vtctldclient/command/doc.go index b83db0ef0a4..967c14be313 100644 --- a/go/cmd/vtctldclient/command/doc.go +++ b/go/cmd/vtctldclient/command/doc.go @@ -43,6 +43,7 @@ exception here, not the rule). Commands should also prevent individual flag names from polluting the package namespace. A good pattern we have found is to do the following: + package command // (imports ...) diff --git a/go/flagutil/sets.go b/go/flagutil/sets.go index cfe21481f42..ea2549d98bd 100644 --- a/go/flagutil/sets.go +++ b/go/flagutil/sets.go @@ -34,8 +34,8 @@ var ( // // For example, defining the following: // -// var x flagutil.StringSetFlag -// flag.Var(&x, "foo", "") +// var x flagutil.StringSetFlag +// flag.Var(&x, "foo", "") // // And then specifying "-foo x -foo y -foo x", will result in a set of {x, y}. // diff --git a/go/internal/flag/flag.go b/go/internal/flag/flag.go index 28c8f266ee2..9f4fe2f46c8 100644 --- a/go/internal/flag/flag.go +++ b/go/internal/flag/flag.go @@ -126,6 +126,7 @@ func warnOnMixedPositionalAndFlagArguments(posargs []string, warningf func(msg s } // From the standard library documentation: +// // > If a Value has an IsBoolFlag() bool method returning true, the // > command-line parser makes -name equivalent to -name=true rather than // > using the next command-line argument. diff --git a/go/internal/flag/usage.go b/go/internal/flag/usage.go index 9cb0632ffa8..2a7f8dc0313 100644 --- a/go/internal/flag/usage.go +++ b/go/internal/flag/usage.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/mysql/binlog_event_common.go b/go/mysql/binlog_event_common.go index 1f875d41e06..25945c5d1b9 100644 --- a/go/mysql/binlog_event_common.go +++ b/go/mysql/binlog_event_common.go @@ -30,23 +30,24 @@ import ( // into flavor-specific event types to pull in common parsing code. // // The default v4 header format is: -// offset : size -// +============================+ -// | timestamp 0 : 4 | -// +----------------------------+ -// | type_code 4 : 1 | -// +----------------------------+ -// | server_id 5 : 4 | -// +----------------------------+ -// | event_length 9 : 4 | -// +----------------------------+ -// | next_position 13 : 4 | -// +----------------------------+ -// | flags 17 : 2 | -// +----------------------------+ -// | extra_headers 19 : x-19 | -// +============================+ -// http://dev.mysql.com/doc/internals/en/event-header-fields.html +// +// offset : size +// +============================+ +// | timestamp 0 : 4 | +// +----------------------------+ +// | type_code 4 : 1 | +// +----------------------------+ +// | server_id 5 : 4 | +// +----------------------------+ +// | event_length 9 : 4 | +// +----------------------------+ +// | next_position 13 : 4 | +// +----------------------------+ +// | flags 17 : 2 | +// +----------------------------+ +// | extra_headers 19 : x-19 | +// +============================+ +// http://dev.mysql.com/doc/internals/en/event-header-fields.html type binlogEvent []byte // dataBytes returns the event bytes without header prefix and without checksum suffix @@ -192,15 +193,16 @@ func (ev binlogEvent) IsCompressed() bool { // Format implements BinlogEvent.Format(). // // Expected format (L = total length of event data): -// # bytes field -// 2 format version -// 50 server version string, 0-padded but not necessarily 0-terminated -// 4 timestamp (same as timestamp header field) -// 1 header length -// p (one byte per packet type) event type header lengths -// Rest was inferred from reading source code: -// 1 checksum algorithm -// 4 checksum +// +// # bytes field +// 2 format version +// 50 server version string, 0-padded but not necessarily 0-terminated +// 4 timestamp (same as timestamp header field) +// 1 header length +// p (one byte per packet type) event type header lengths +// Rest was inferred from reading source code: +// 1 checksum algorithm +// 4 checksum func (ev binlogEvent) Format() (f BinlogFormat, err error) { // FORMAT_DESCRIPTION_EVENT has a fixed header size of 19 // because we have to read it before we know the header_length. @@ -229,15 +231,16 @@ func (ev binlogEvent) Format() (f BinlogFormat, err error) { // Query implements BinlogEvent.Query(). // // Expected format (L = total length of event data): -// # bytes field -// 4 thread_id -// 4 execution time -// 1 length of db_name, not including NULL terminator (X) -// 2 error code -// 2 length of status vars block (Y) -// Y status vars block -// X+1 db_name + NULL terminator -// L-X-1-Y SQL statement (no NULL terminator) +// +// # bytes field +// 4 thread_id +// 4 execution time +// 1 length of db_name, not including NULL terminator (X) +// 2 error code +// 2 length of status vars block (Y) +// Y status vars block +// X+1 db_name + NULL terminator +// L-X-1-Y SQL statement (no NULL terminator) func (ev binlogEvent) Query(f BinlogFormat) (query Query, err error) { const varsPos = 4 + 4 + 1 + 2 + 2 @@ -310,9 +313,10 @@ varsLoop: // IntVar implements BinlogEvent.IntVar(). // // Expected format (L = total length of event data): -// # bytes field -// 1 variable ID -// 8 variable value +// +// # bytes field +// 1 variable ID +// 8 variable value func (ev binlogEvent) IntVar(f BinlogFormat) (byte, uint64, error) { data := ev.Bytes()[f.HeaderLength:] @@ -328,9 +332,10 @@ func (ev binlogEvent) IntVar(f BinlogFormat) (byte, uint64, error) { // Rand implements BinlogEvent.Rand(). // // Expected format (L = total length of event data): -// # bytes field -// 8 seed 1 -// 8 seed 2 +// +// # bytes field +// 8 seed 1 +// 8 seed 2 func (ev binlogEvent) Rand(f BinlogFormat) (seed1 uint64, seed2 uint64, err error) { data := ev.Bytes()[f.HeaderLength:] seed1 = binary.LittleEndian.Uint64(data[0:8]) diff --git a/go/mysql/binlog_event_filepos.go b/go/mysql/binlog_event_filepos.go index a6345468d1f..f68e4a58fcd 100644 --- a/go/mysql/binlog_event_filepos.go +++ b/go/mysql/binlog_event_filepos.go @@ -84,9 +84,10 @@ func (ev *filePosBinlogEvent) nextPosition(f BinlogFormat) int { // rotate implements BinlogEvent.Rotate(). // // Expected format (L = total length of event data): -// # bytes field -// 8 position -// 8:L file +// +// # bytes field +// 8 position +// 8:L file func (ev *filePosBinlogEvent) rotate(f BinlogFormat) (int, string) { data := ev.Bytes()[f.HeaderLength:] pos := binary.LittleEndian.Uint64(data[0:8]) diff --git a/go/mysql/binlog_event_json.go b/go/mysql/binlog_event_json.go index e630738a0b6..82b53311c0f 100644 --- a/go/mysql/binlog_event_json.go +++ b/go/mysql/binlog_event_json.go @@ -44,8 +44,8 @@ https://github.com/noplay/python-mysql-replication/blob/175df28cc8b536a68522ff9b */ -//region debug-only -//TODO remove once the json refactor is tested live +// region debug-only +// TODO remove once the json refactor is tested live var jsonDebug = false func jlog(tpl string, vals ...any) { diff --git a/go/mysql/binlog_event_mariadb.go b/go/mysql/binlog_event_mariadb.go index e21096b51d6..d2cdd6ac18f 100644 --- a/go/mysql/binlog_event_mariadb.go +++ b/go/mysql/binlog_event_mariadb.go @@ -54,10 +54,11 @@ func (ev mariadbBinlogEvent) IsGTID() bool { // GTID implements BinlogEvent.GTID(). // // Expected format: -// # bytes field -// 8 sequence number -// 4 domain ID -// 1 flags2 +// +// # bytes field +// 8 sequence number +// 4 domain ID +// 1 flags2 func (ev mariadbBinlogEvent) GTID(f BinlogFormat) (GTID, bool, error) { const FLStandalone = 1 diff --git a/go/mysql/binlog_event_mysql56.go b/go/mysql/binlog_event_mysql56.go index 4234496bf25..b4c4e3c0bca 100644 --- a/go/mysql/binlog_event_mysql56.go +++ b/go/mysql/binlog_event_mysql56.go @@ -54,10 +54,11 @@ func (ev mysql56BinlogEvent) IsGTID() bool { // GTID implements BinlogEvent.GTID(). // // Expected format: -// # bytes field -// 1 flags -// 16 SID (server UUID) -// 8 GNO (sequence number, signed int) +// +// # bytes field +// 1 flags +// 16 SID (server UUID) +// 8 GNO (sequence number, signed int) func (ev mysql56BinlogEvent) GTID(f BinlogFormat) (GTID, bool, error) { data := ev.Bytes()[f.HeaderLength:] var sid SID diff --git a/go/mysql/binlog_event_rbr.go b/go/mysql/binlog_event_rbr.go index 3403be27579..ed415f27c01 100644 --- a/go/mysql/binlog_event_rbr.go +++ b/go/mysql/binlog_event_rbr.go @@ -38,19 +38,20 @@ var ZeroTimestamp = []byte("0000-00-00 00:00:00") // TableMap implements BinlogEvent.TableMap(). // // Expected format (L = total length of event data): -// # bytes field -// 4/6 table id -// 2 flags -// 1 schema name length sl -// sl schema name -// 1 [00] -// 1 table name length tl -// tl table name -// 1 [00] -// column count cc (var-len encoded) -// cc column-def, one byte per column -// column-meta-def (var-len encoded string) -// n NULL-bitmask, length: (cc + 7) / 8 +// +// # bytes field +// 4/6 table id +// 2 flags +// 1 schema name length sl +// sl schema name +// 1 [00] +// 1 table name length tl +// tl table name +// 1 [00] +// column count cc (var-len encoded) +// cc column-def, one byte per column +// column-meta-def (var-len encoded string) +// n NULL-bitmask, length: (cc + 7) / 8 func (ev binlogEvent) TableMap(f BinlogFormat) (*TableMap, error) { data := ev.Bytes()[f.HeaderLength:] @@ -955,13 +956,15 @@ func CellValue(data []byte, pos int, typ byte, metadata uint16, field *querypb.F // Rows implements BinlogEvent.TableMap(). // // Expected format (L = total length of event data): -// # bytes field -// 4/6 table id -// 2 flags -// -- if version == 2 -// 2 extra data length edl -// edl extra data -// -- endif +// +// # bytes field +// 4/6 table id +// 2 flags +// -- if version == 2 +// 2 extra data length edl +// edl extra data +// -- endif +// // number of columns (var-len encoded) // identify bitmap // data bitmap diff --git a/go/mysql/fakesqldb/server.go b/go/mysql/fakesqldb/server.go index 2b0c5725485..6feadb36b66 100644 --- a/go/mysql/fakesqldb/server.go +++ b/go/mysql/fakesqldb/server.go @@ -582,12 +582,12 @@ func (db *DB) GetQueryCalledNum(query string) int { return num } -//QueryLog returns the query log in a semicomma separated string +// QueryLog returns the query log in a semicomma separated string func (db *DB) QueryLog() string { return strings.Join(db.querylog, ";") } -//ResetQueryLog resets the query log +// ResetQueryLog resets the query log func (db *DB) ResetQueryLog() { db.querylog = nil } diff --git a/go/mysql/flavor_mysqlgr_test.go b/go/mysql/flavor_mysqlgr_test.go index 4b7661f145b..fcc5765a18f 100644 --- a/go/mysql/flavor_mysqlgr_test.go +++ b/go/mysql/flavor_mysqlgr_test.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/mysql/ldapauthserver/auth_server_ldap.go b/go/mysql/ldapauthserver/auth_server_ldap.go index b15c750fb75..3d28c265b41 100644 --- a/go/mysql/ldapauthserver/auth_server_ldap.go +++ b/go/mysql/ldapauthserver/auth_server_ldap.go @@ -136,7 +136,7 @@ func (asl *AuthServerLdap) validate(username, password string) (mysql.Getter, er return &LdapUserData{asl: asl, groups: groups, username: username, lastUpdated: time.Now(), updating: false}, nil } -//this needs to be passed an already connected client...should check for this +// this needs to be passed an already connected client...should check for this func (asl *AuthServerLdap) getGroups(username string) ([]string, error) { err := asl.Client.Bind(asl.User, asl.Password) if err != nil { diff --git a/go/mysql/mariadb_gtid.go b/go/mysql/mariadb_gtid.go index 8ff68a0b988..713ef2c72b4 100644 --- a/go/mysql/mariadb_gtid.go +++ b/go/mysql/mariadb_gtid.go @@ -237,7 +237,7 @@ func (gtidSet MariadbGTIDSet) Union(other GTIDSet) GTIDSet { return newSet } -//Last returns the last gtid +// Last returns the last gtid func (gtidSet MariadbGTIDSet) Last() string { // Sort domains so the string format is deterministic. domains := make([]uint32, 0, len(gtidSet)) diff --git a/go/mysql/mysql56_gtid_set.go b/go/mysql/mysql56_gtid_set.go index 071e0d929b7..77446eb8788 100644 --- a/go/mysql/mysql56_gtid_set.go +++ b/go/mysql/mysql56_gtid_set.go @@ -587,14 +587,19 @@ func (set Mysql56GTIDSet) Difference(other Mysql56GTIDSet) Mysql56GTIDSet { // This is the reverse of the SIDBlock method. // // Expected format: -// # bytes field -// 8 nSIDs +// +// # bytes field +// 8 nSIDs +// // (nSIDs times) -// 16 SID -// 8 nIntervals +// +// 16 SID +// 8 nIntervals +// // (nIntervals times) -// 8 start -// 8 end +// +// 8 start +// 8 end func NewMysql56GTIDSetFromSIDBlock(data []byte) (Mysql56GTIDSet, error) { buf := bytes.NewReader(data) var set Mysql56GTIDSet = make(map[SID][]interval) diff --git a/go/mysql/query_test.go b/go/mysql/query_test.go index b2809a428bc..6dc7ee1dc73 100644 --- a/go/mysql/query_test.go +++ b/go/mysql/query_test.go @@ -790,7 +790,7 @@ func checkQueryInternal(t *testing.T, query string, sConn, cConn *Conn, result * } } -//nolint +// nolint func writeResult(conn *Conn, result *sqltypes.Result) error { if len(result.Fields) == 0 { return conn.writeOKPacket(&PacketOK{ diff --git a/go/mysql/vault/auth_server_vault.go b/go/mysql/vault/auth_server_vault.go index 53df7fd2914..b3e56ae6f30 100644 --- a/go/mysql/vault/auth_server_vault.go +++ b/go/mysql/vault/auth_server_vault.go @@ -271,7 +271,8 @@ func (a *AuthServerVault) close() { } // We ignore most errors here, to allow us to retry cleanly -// or ignore the cases where the input is not passed by file, but via env +// +// or ignore the cases where the input is not passed by file, but via env func readFromFile(filePath string) (string, error) { if filePath == "" { return "", nil diff --git a/go/netutil/netutil.go b/go/netutil/netutil.go index f3213b8f633..54e53e85226 100644 --- a/go/netutil/netutil.go +++ b/go/netutil/netutil.go @@ -207,9 +207,10 @@ func dnsLookup(host string) ([]net.IP, error) { } // DNSTracker is a closure that persists state for -// tracking changes in the DNS resolution of a target dns name -// returns true if the DNS name resolution has changed -// If there is a lookup problem, we pretend nothing has changed +// +// tracking changes in the DNS resolution of a target dns name +// returns true if the DNS name resolution has changed +// If there is a lookup problem, we pretend nothing has changed func DNSTracker(host string) func() (bool, error) { dnsName := host var addrs []net.IP diff --git a/go/pools/numbered.go b/go/pools/numbered.go index 4dba73aa2de..233fe5149ba 100644 --- a/go/pools/numbered.go +++ b/go/pools/numbered.go @@ -47,7 +47,7 @@ type unregistered struct { timeUnregistered time.Time } -//NewNumbered creates a new numbered +// NewNumbered creates a new numbered func NewNumbered() *Numbered { n := &Numbered{ resources: make(map[int64]*numberedWrapper), @@ -218,12 +218,12 @@ func (nu *Numbered) WaitForEmpty() { } } -//StatsJSON returns stats in JSON format +// StatsJSON returns stats in JSON format func (nu *Numbered) StatsJSON() string { return fmt.Sprintf("{\"Size\": %v}", nu.Size()) } -//Size returns the current size +// Size returns the current size func (nu *Numbered) Size() int64 { nu.mu.Lock() defer nu.mu.Unlock() diff --git a/go/sqltypes/testing.go b/go/sqltypes/testing.go index 83c991ba073..50daed076a0 100644 --- a/go/sqltypes/testing.go +++ b/go/sqltypes/testing.go @@ -29,10 +29,12 @@ import ( // reduced and readability improved. // MakeTestFields builds a []*querypb.Field for testing. -// fields := sqltypes.MakeTestFields( -// "a|b", -// "int64|varchar", -// ) +// +// fields := sqltypes.MakeTestFields( +// "a|b", +// "int64|varchar", +// ) +// // The field types are as defined in querypb and are case // insensitive. Column delimiters must be used only to sepearate // strings and not at the beginning or the end. @@ -50,11 +52,13 @@ func MakeTestFields(names, types string) []*querypb.Field { } // MakeTestResult builds a *sqltypes.Result object for testing. -// result := sqltypes.MakeTestResult( -// fields, -// " 1|a", -// "10|abcd", -// ) +// +// result := sqltypes.MakeTestResult( +// fields, +// " 1|a", +// "10|abcd", +// ) +// // The field type values are set as the types for the rows built. // Spaces are trimmed from row values. "null" is treated as NULL. func MakeTestResult(fields []*querypb.Field, rows ...string) *Result { @@ -77,13 +81,15 @@ func MakeTestResult(fields []*querypb.Field, rows ...string) *Result { } // MakeTestStreamingResults builds a list of results for streaming. -// results := sqltypes.MakeStreamingResults( -// fields, -// "1|a", -// "2|b", -// "---", -// "c|c", -// ) +// +// results := sqltypes.MakeStreamingResults( +// fields, +// "1|a", +// "2|b", +// "---", +// "c|c", +// ) +// // The first result contains only the fields. Subsequent results // are built using the field types. Every input that starts with a "-" // is treated as streaming delimiter for one result. A final diff --git a/go/sqltypes/type.go b/go/sqltypes/type.go index 7cce371b541..e4fba97a636 100644 --- a/go/sqltypes/type.go +++ b/go/sqltypes/type.go @@ -109,16 +109,16 @@ func IsNull(t querypb.Type) bool { // Use the synonyms only to refer to the type in Value. For proto variables, use the querypb.Type constants instead. // The following is a complete listing of types that match each classification function in this API: // -// IsSigned(): INT8, INT16, INT24, INT32, INT64 -// IsFloat(): FLOAT32, FLOAT64 -// IsUnsigned(): UINT8, UINT16, UINT24, UINT32, UINT64, YEAR -// IsIntegral(): INT8, UINT8, INT16, UINT16, INT24, UINT24, INT32, UINT32, INT64, UINT64, YEAR -// IsText(): TEXT, VARCHAR, CHAR, HEXNUM, HEXVAL -// IsNumber(): INT8, UINT8, INT16, UINT16, INT24, UINT24, INT32, UINT32, INT64, UINT64, FLOAT32, FLOAT64, YEAR, DECIMAL -// IsQuoted(): TIMESTAMP, DATE, TIME, DATETIME, TEXT, BLOB, VARCHAR, VARBINARY, CHAR, BINARY, ENUM, SET, GEOMETRY, JSON -// IsBinary(): BLOB, VARBINARY, BINARY -// IsDate(): TIMESTAMP, DATE, TIME, DATETIME -// IsNull(): NULL_TYPE +// IsSigned(): INT8, INT16, INT24, INT32, INT64 +// IsFloat(): FLOAT32, FLOAT64 +// IsUnsigned(): UINT8, UINT16, UINT24, UINT32, UINT64, YEAR +// IsIntegral(): INT8, UINT8, INT16, UINT16, INT24, UINT24, INT32, UINT32, INT64, UINT64, YEAR +// IsText(): TEXT, VARCHAR, CHAR, HEXNUM, HEXVAL +// IsNumber(): INT8, UINT8, INT16, UINT16, INT24, UINT24, INT32, UINT32, INT64, UINT64, FLOAT32, FLOAT64, YEAR, DECIMAL +// IsQuoted(): TIMESTAMP, DATE, TIME, DATETIME, TEXT, BLOB, VARCHAR, VARBINARY, CHAR, BINARY, ENUM, SET, GEOMETRY, JSON +// IsBinary(): BLOB, VARBINARY, BINARY +// IsDate(): TIMESTAMP, DATE, TIME, DATETIME +// IsNull(): NULL_TYPE // // TODO(sougou): provide a categorization function // that returns enums, which will allow for cleaner diff --git a/go/test/endtoend/docker/vttestserver.go b/go/test/endtoend/docker/vttestserver.go index e6bc93d4e6c..7f24134a28f 100644 --- a/go/test/endtoend/docker/vttestserver.go +++ b/go/test/endtoend/docker/vttestserver.go @@ -132,7 +132,7 @@ func convertToStringSlice(intSlice []int) []string { return stringSlice } -//makeVttestserverDockerImages creates the vttestserver docker images for both MySQL57 and MySQL80 +// makeVttestserverDockerImages creates the vttestserver docker images for both MySQL57 and MySQL80 func makeVttestserverDockerImages() error { mainVitessPath := path.Join(os.Getenv("PWD"), "../../../..") dockerFilePath := path.Join(mainVitessPath, "docker/vttestserver/Dockerfile.mysql57") diff --git a/go/test/endtoend/migration/migration_test.go b/go/test/endtoend/migration/migration_test.go index cd2c21efefd..f0b91e2d6df 100644 --- a/go/test/endtoend/migration/migration_test.go +++ b/go/test/endtoend/migration/migration_test.go @@ -110,21 +110,22 @@ We create a new "commerce" keyspace, which will be the target. The commerce keys take a yaml config that defines these external sources. it will look like this: externalConnections: - product: - socket: /home/sougou/dev/src/vitess.io/vitess/vtdataroot/vtroot_15201/vt_0000000622/mysql.sock - dbName: vt_product - app: - user: vt_app - dba: - user: vt_dba - customer: - flavor: FilePos - socket: /home/sougou/dev/src/vitess.io/vitess/vtdataroot/vtroot_15201/vt_0000000620/mysql.sock - dbName: vt_customer - app: - user: vt_app - dba: - user: vt_dba + + product: + socket: /home/sougou/dev/src/vitess.io/vitess/vtdataroot/vtroot_15201/vt_0000000622/mysql.sock + dbName: vt_product + app: + user: vt_app + dba: + user: vt_dba + customer: + flavor: FilePos + socket: /home/sougou/dev/src/vitess.io/vitess/vtdataroot/vtroot_15201/vt_0000000620/mysql.sock + dbName: vt_customer + app: + user: vt_app + dba: + user: vt_dba We then execute the following vreplication inserts to initiate the import. The test uses three streams although only two are required. This is to show that there can exist multiple @@ -132,9 +133,9 @@ streams from the same source. The main difference between an external source vs source is that the source proto contains an "external_mysql" field instead of keyspace and shard. That field is the key into the externalConnections section of the input yaml. -VReplicationExec: insert into _vt.vreplication (workflow, db_name, source, pos, max_tps, max_replication_lag, tablet_types, time_updated, transaction_timestamp, state) values('product', 'vt_commerce', 'filter: > external_mysql:\"product\" ', '', 9999, 9999, 'primary', 0, 0, 'Running') -VReplicationExec: insert into _vt.vreplication (workflow, db_name, source, pos, max_tps, max_replication_lag, tablet_types, time_updated, transaction_timestamp, state) values('customer', 'vt_commerce', 'filter: > external_mysql:\"customer\" ', '', 9999, 9999, 'primary', 0, 0, 'Running') -VReplicationExec: insert into _vt.vreplication (workflow, db_name, source, pos, max_tps, max_replication_lag, tablet_types, time_updated, transaction_timestamp, state) values('orders', 'vt_commerce', 'filter: > external_mysql:\"customer\" ', '', 9999, 9999, 'primary', 0, 0, 'Running') +VReplicationExec: insert into _vt.vreplication (workflow, db_name, source, pos, max_tps, max_replication_lag, tablet_types, time_updated, transaction_timestamp, state) values('product', 'vt_commerce', 'filter: > external_mysql:\"product\" ', ”, 9999, 9999, 'primary', 0, 0, 'Running') +VReplicationExec: insert into _vt.vreplication (workflow, db_name, source, pos, max_tps, max_replication_lag, tablet_types, time_updated, transaction_timestamp, state) values('customer', 'vt_commerce', 'filter: > external_mysql:\"customer\" ', ”, 9999, 9999, 'primary', 0, 0, 'Running') +VReplicationExec: insert into _vt.vreplication (workflow, db_name, source, pos, max_tps, max_replication_lag, tablet_types, time_updated, transaction_timestamp, state) values('orders', 'vt_commerce', 'filter: > external_mysql:\"customer\" ', ”, 9999, 9999, 'primary', 0, 0, 'Running') */ func TestMigration(t *testing.T) { yamlFile := startCluster(t) diff --git a/go/test/endtoend/reparent/utils/utils.go b/go/test/endtoend/reparent/utils/utils.go index 105d4e5599f..384d5d26aad 100644 --- a/go/test/endtoend/reparent/utils/utils.go +++ b/go/test/endtoend/reparent/utils/utils.go @@ -327,7 +327,7 @@ func setupShardLegacy(ctx context.Context, t *testing.T, clusterInstance *cluste //endregion -//region database queries +// region database queries func getMysqlConnParam(tablet *cluster.Vttablet) mysql.ConnParams { connParams := mysql.ConnParams{ Uname: username, diff --git a/go/test/endtoend/tabletmanager/tablegc/tablegc_test.go b/go/test/endtoend/tabletmanager/tablegc/tablegc_test.go index d1d3e02acc0..e40c63b52cb 100644 --- a/go/test/endtoend/tabletmanager/tablegc/tablegc_test.go +++ b/go/test/endtoend/tabletmanager/tablegc/tablegc_test.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/test/endtoend/vault/vault_test.go b/go/test/endtoend/vault/vault_test.go index eb5549308e6..6f5e53c6481 100644 --- a/go/test/endtoend/vault/vault_test.go +++ b/go/test/endtoend/vault/vault_test.go @@ -214,7 +214,8 @@ func setupVaultServer(t *testing.T, vs *VaultServer) (string, string) { } // Setup cluster object and start topo -// We need this before vault, because we re-use the port reservation code +// +// We need this before vault, because we re-use the port reservation code func initializeClusterEarly(t *testing.T) { clusterInstance = cluster.NewCluster(cell, hostname) diff --git a/go/test/endtoend/vtctldweb/vtctld_web_main_test.go b/go/test/endtoend/vtctldweb/vtctld_web_main_test.go index d8a37050420..40b0bbd7c7a 100644 --- a/go/test/endtoend/vtctldweb/vtctld_web_main_test.go +++ b/go/test/endtoend/vtctldweb/vtctld_web_main_test.go @@ -37,7 +37,7 @@ import ( "vitess.io/vitess/go/vt/vttest" ) -//nolint +// nolint var ( localCluster *vttest.LocalCluster hostname = "localhost" //nolint diff --git a/go/test/endtoend/vtgate/prefixfanout/main_test.go b/go/test/endtoend/vtgate/prefixfanout/main_test.go index f42f556ea7e..b7d315854c2 100644 --- a/go/test/endtoend/vtgate/prefixfanout/main_test.go +++ b/go/test/endtoend/vtgate/prefixfanout/main_test.go @@ -3,7 +3,9 @@ Copyright 2021 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/go/test/stress/stress.go b/go/test/stress/stress.go index 130fe0c382e..1346e3afa55 100644 --- a/go/test/stress/stress.go +++ b/go/test/stress/stress.go @@ -222,9 +222,8 @@ func (s *Stresser) SetConn(conn *mysql.ConnParams) *Stresser { // // This method returns a pointer to its Stresser to allow chained function call, like: // -// s := stress.New(t, cfg).Start() -// s.Stop() -// +// s := stress.New(t, cfg).Start() +// s.Stop() func (s *Stresser) Start() *Stresser { if s.cfg.PrintLogs { s.t.Log("Starting load testing ...") diff --git a/go/test/utils/diff.go b/go/test/utils/diff.go index 1f988dcbbb9..416c2bf6ac9 100644 --- a/go/test/utils/diff.go +++ b/go/test/utils/diff.go @@ -33,16 +33,18 @@ import ( // Top declaration: // // var mustMatch = testutils.MustMatchFn( -// []any{ // types with unexported fields -// type1{}, -// type2{}, -// ... -// typeN{}, -// }, -// []string{ // ignored fields -// ".id", // id numbers are unstable -// ".createAt", // created dates might not be interesting to compare -// }, +// +// []any{ // types with unexported fields +// type1{}, +// type2{}, +// ... +// typeN{}, +// }, +// []string{ // ignored fields +// ".id", // id numbers are unstable +// ".createAt", // created dates might not be interesting to compare +// }, +// // ) // // In Test*() function: diff --git a/go/testfiles/ports.go b/go/testfiles/ports.go index 7f2f64ac7df..b6e0800d23f 100644 --- a/go/testfiles/ports.go +++ b/go/testfiles/ports.go @@ -27,10 +27,8 @@ import ( // // We also use it to allocate Zookeeper server IDs. -// // Port definitions. Unit tests may run at the same time, // so they should not use the same ports. -// var ( // vtPortStart is the starting port for all tests. vtPortStart = getPortStart() @@ -48,10 +46,8 @@ var ( GoVtTopoConsultopoPort = GoVtTopoZk2topoPort + 3 ) -// // Zookeeper server ID definitions. Unit tests may run at the // same time, so they can't use the same Zookeeper server IDs. -// var ( // GoVtTopoZk2topoZkID is used by the go/vt/topo/zk2topo package. GoVtTopoZk2topoZkID = 1 diff --git a/go/tools/asthelpergen/integration/types.go b/go/tools/asthelpergen/integration/types.go index 4f39792bd79..0fe2d7fee50 100644 --- a/go/tools/asthelpergen/integration/types.go +++ b/go/tools/asthelpergen/integration/types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -//nolint +// nolint package integration import ( diff --git a/go/tools/sizegen/integration/types.go b/go/tools/sizegen/integration/types.go index c05b08cfd07..ff2a676b998 100644 --- a/go/tools/sizegen/integration/types.go +++ b/go/tools/sizegen/integration/types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -//nolint +// nolint package integration type A struct { diff --git a/go/vt/binlog/binlog_connection.go b/go/vt/binlog/binlog_connection.go index 2681875b14a..126e13399d8 100644 --- a/go/vt/binlog/binlog_connection.go +++ b/go/vt/binlog/binlog_connection.go @@ -41,6 +41,7 @@ var ( // connecting for replication. Each such connection must identify itself to // mysqld with a server ID that is unique both among other BinlogConnections and // among actual replicas in the topology. +// //revive:disable because I'm not trying to refactor the entire code base right now type BinlogConnection struct { *mysql.Conn diff --git a/go/vt/concurrency/error_group.go b/go/vt/concurrency/error_group.go index 4e1c1cd1ce0..08ab1c474de 100644 --- a/go/vt/concurrency/error_group.go +++ b/go/vt/concurrency/error_group.go @@ -43,7 +43,7 @@ import "context" // NumGoroutines: len(args), // NumRequiredSuccess: 5, // need at least 5 to respond with nil error before cancelling the rest // NumAllowedErrors: 1, // if more than 1 responds with non-nil error, cancel the rest -// NumErrorsToWaitFor: 1, // if there is 1 response that we must wait for, before cancelling the rest +// NumErrorsToWaitFor: 1, // if there is 1 response that we must wait for, before cancelling the rest // } // errRec := errgroup.Wait(errgroupCancel, errCh) // @@ -73,13 +73,14 @@ type Error struct { // Error channel, and are cancellable by the given cancel function. // // Wait will cancel any outstanding goroutines when the following condition is met: -// * At least NumErrorsToWaitFor results with MustWaitFor set have been consumed -// on the error channel AND one of the following two - -// (1) More than NumAllowedErrors non-nil results have been consumed on the -// error channel. // -// (2) At least NumRequiredSuccesses nil results have been consumed on the error -// channel. +// - At least NumErrorsToWaitFor results with MustWaitFor set have been consumed +// on the error channel AND one of the following two - +// (1) More than NumAllowedErrors non-nil results have been consumed on the +// error channel. +// +// (2) At least NumRequiredSuccesses nil results have been consumed on the error +// channel. // // After the cancellation condition is triggered, Wait will continue to consume // results off the Error channel so as to not permanently block any of those diff --git a/go/vt/discovery/legacy_healthcheck.go b/go/vt/discovery/legacy_healthcheck.go index 3154736f60d..81284640331 100644 --- a/go/vt/discovery/legacy_healthcheck.go +++ b/go/vt/discovery/legacy_healthcheck.go @@ -378,12 +378,15 @@ func NewLegacyDefaultHealthCheck() LegacyHealthCheck { // NewLegacyHealthCheck creates a new LegacyHealthCheck object. // Parameters: // retryDelay. -// The duration to wait before retrying to connect (e.g. after a failed connection -// attempt). +// +// The duration to wait before retrying to connect (e.g. after a failed connection +// attempt). +// // healthCheckTimeout. -// The duration for which we consider a health check response to be 'fresh'. If we don't get -// a health check response from a tablet for more than this duration, we consider the tablet -// not healthy. +// +// The duration for which we consider a health check response to be 'fresh'. If we don't get +// a health check response from a tablet for more than this duration, we consider the tablet +// not healthy. func NewLegacyHealthCheck(retryDelay, healthCheckTimeout time.Duration) LegacyHealthCheck { hc := &LegacyHealthCheckImpl{ addrToHealth: make(map[string]*legacyTabletHealth), diff --git a/go/vt/discovery/legacy_replicationlag.go b/go/vt/discovery/legacy_replicationlag.go index 31dd5eaa4e8..20ab94def65 100644 --- a/go/vt/discovery/legacy_replicationlag.go +++ b/go/vt/discovery/legacy_replicationlag.go @@ -54,10 +54,10 @@ func LegacyIsReplicationLagVeryHigh(tabletStats *LegacyTabletStats) bool { // lags of (30m, 35m, 40m, 45m) return all. // // One thing to know about this code: vttablet also has a couple flags that impact the logic here: -// * unhealthy_threshold: if replication lag is higher than this, a tablet will be reported as unhealthy. -// The default for this is 2h, same as the discovery_high_replication_lag_minimum_serving here. -// * degraded_threshold: this is only used by vttablet for display. It should match -// discovery_low_replication_lag here, so the vttablet status display matches what vtgate will do of it. +// - unhealthy_threshold: if replication lag is higher than this, a tablet will be reported as unhealthy. +// The default for this is 2h, same as the discovery_high_replication_lag_minimum_serving here. +// - degraded_threshold: this is only used by vttablet for display. It should match +// discovery_low_replication_lag here, so the vttablet status display matches what vtgate will do of it. func FilterLegacyStatsByReplicationLag(tabletStatsList []*LegacyTabletStats) []*LegacyTabletStats { if !*legacyReplicationLagAlgorithm { return filterLegacyStatsByLag(tabletStatsList) diff --git a/go/vt/discovery/replicationlag.go b/go/vt/discovery/replicationlag.go index ea9e903a9b5..b98496ff291 100644 --- a/go/vt/discovery/replicationlag.go +++ b/go/vt/discovery/replicationlag.go @@ -94,10 +94,10 @@ func IsReplicationLagVeryHigh(tabletHealth *TabletHealth) bool { // lags of (30m, 35m, 40m, 45m) return all. // // One thing to know about this code: vttablet also has a couple flags that impact the logic here: -// * unhealthy_threshold: if replication lag is higher than this, a tablet will be reported as unhealthy. -// The default for this is 2h, same as the discovery_high_replication_lag_minimum_serving here. -// * degraded_threshold: this is only used by vttablet for display. It should match -// discovery_low_replication_lag here, so the vttablet status display matches what vtgate will do of it. +// - unhealthy_threshold: if replication lag is higher than this, a tablet will be reported as unhealthy. +// The default for this is 2h, same as the discovery_high_replication_lag_minimum_serving here. +// - degraded_threshold: this is only used by vttablet for display. It should match +// discovery_low_replication_lag here, so the vttablet status display matches what vtgate will do of it. func FilterStatsByReplicationLag(tabletHealthList []*TabletHealth) []*TabletHealth { if !*legacyReplicationLagAlgorithm { return filterStatsByLag(tabletHealthList) diff --git a/go/vt/events/status.go b/go/vt/events/status.go index 25384ff6b5b..49d261f5adb 100644 --- a/go/vt/events/status.go +++ b/go/vt/events/status.go @@ -29,11 +29,11 @@ import ( // // For example: // -// type MyEvent struct { -// StatusUpdater -// } -// ev := &MyEvent{} -// event.DispatchUpdate(ev, "new status") +// type MyEvent struct { +// StatusUpdater +// } +// ev := &MyEvent{} +// event.DispatchUpdate(ev, "new status") type StatusUpdater struct { Status string diff --git a/go/vt/grpcoptionaltls/conn_wrapper.go b/go/vt/grpcoptionaltls/conn_wrapper.go index 5659a9170f3..883a531dcff 100755 --- a/go/vt/grpcoptionaltls/conn_wrapper.go +++ b/go/vt/grpcoptionaltls/conn_wrapper.go @@ -3,7 +3,9 @@ Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/go/vt/grpcoptionaltls/optionaltls.go b/go/vt/grpcoptionaltls/optionaltls.go index d4e37ed3208..0833544785c 100755 --- a/go/vt/grpcoptionaltls/optionaltls.go +++ b/go/vt/grpcoptionaltls/optionaltls.go @@ -3,7 +3,9 @@ Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/go/vt/grpcoptionaltls/server_test.go b/go/vt/grpcoptionaltls/server_test.go index 7e3efc1c3af..a457010b7b0 100755 --- a/go/vt/grpcoptionaltls/server_test.go +++ b/go/vt/grpcoptionaltls/server_test.go @@ -3,7 +3,9 @@ Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/go/vt/grpcoptionaltls/tls_detector.go b/go/vt/grpcoptionaltls/tls_detector.go index beff6bfd740..19d22f187dd 100755 --- a/go/vt/grpcoptionaltls/tls_detector.go +++ b/go/vt/grpcoptionaltls/tls_detector.go @@ -3,7 +3,9 @@ Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/go/vt/mysqlctl/builtinbackupengine_test.go b/go/vt/mysqlctl/builtinbackupengine_test.go index 92f6cc7feaf..09a194f597f 100644 --- a/go/vt/mysqlctl/builtinbackupengine_test.go +++ b/go/vt/mysqlctl/builtinbackupengine_test.go @@ -149,7 +149,8 @@ func TestExecuteBackup(t *testing.T) { // needInnoDBRedoLogSubdir indicates whether we need to create a redo log subdirectory. // Starting with MySQL 8.0.30, the InnoDB redo logs are stored in a subdirectory of the // (/. by default) called "#innodb_redo". See: -// https://dev.mysql.com/doc/refman/8.0/en/innodb-redo-log.html#innodb-modifying-redo-log-capacity +// +// https://dev.mysql.com/doc/refman/8.0/en/innodb-redo-log.html#innodb-modifying-redo-log-capacity func needInnoDBRedoLogSubdir() (needIt bool, err error) { mysqldVersionStr, err := mysqlctl.GetVersionString() if err != nil { diff --git a/go/vt/mysqlctl/mycnf_flag.go b/go/vt/mysqlctl/mycnf_flag.go index f4c01f5cd5d..0264d879eae 100644 --- a/go/vt/mysqlctl/mycnf_flag.go +++ b/go/vt/mysqlctl/mycnf_flag.go @@ -78,14 +78,14 @@ func RegisterFlags() { // NewMycnfFromFlags creates a Mycnf object from the command line flags. // // Multiple modes are supported: -// - at least mycnf_server_id is set on the command line -// --> then we read all parameters from the command line, and not from -// any my.cnf file. -// - mycnf_server_id is not passed in, but mycnf-file is passed in -// --> then we read that mycnf file -// - mycnf_server_id and mycnf-file are not passed in: -// --> then we use the default location of the my.cnf file for the -// provided uid and read that my.cnf file. +// - at least mycnf_server_id is set on the command line +// --> then we read all parameters from the command line, and not from +// any my.cnf file. +// - mycnf_server_id is not passed in, but mycnf-file is passed in +// --> then we read that mycnf file +// - mycnf_server_id and mycnf-file are not passed in: +// --> then we use the default location of the my.cnf file for the +// provided uid and read that my.cnf file. // // RegisterCommandLineFlags should have been called before calling // this, otherwise we'll panic. diff --git a/go/vt/mysqlctl/schema.go b/go/vt/mysqlctl/schema.go index 2c3deb423ed..fa2bdc8608b 100644 --- a/go/vt/mysqlctl/schema.go +++ b/go/vt/mysqlctl/schema.go @@ -551,7 +551,9 @@ func (mysqld *Mysqld) ApplySchemaChange(ctx context.Context, dbName string, chan // are available it will attempt to choose the most efficient // one based on the column data types and the number of columns // in the index. See here for the data type storage sizes: -// https://dev.mysql.com/doc/refman/en/storage-requirements.html +// +// https://dev.mysql.com/doc/refman/en/storage-requirements.html +// // If this function is used on a table that DOES have a // defined PRIMARY KEY then it may return the columns for // that index if it is likely the most efficient one amongst @@ -617,7 +619,7 @@ func (mysqld *Mysqld) GetPrimaryKeyEquivalentColumns(ctx context.Context, dbName return cols, err } -//tableDefinitions is a sortable collection of table definitions +// tableDefinitions is a sortable collection of table definitions type tableDefinitions []*tabletmanagerdatapb.TableDefinition func (t tableDefinitions) Len() int { diff --git a/go/vt/orchestrator/collection/collection.go b/go/vt/orchestrator/collection/collection.go index cb27c697d7f..5098bd5d569 100644 --- a/go/vt/orchestrator/collection/collection.go +++ b/go/vt/orchestrator/collection/collection.go @@ -15,7 +15,6 @@ */ /* - Package collection holds routines for collecting "high frequency" metrics and handling their auto-expiry based on a configured retention time. This becomes more interesting as the number of MySQL servers @@ -31,10 +30,10 @@ data or the raw data for custom analysis over the period requested. This is expected to be used for the following types of metric: -* discovery metrics (time to poll a MySQL server and collect status) -* queue metrics (statistics within the discovery queue itself) -* query metrics (statistics on the number of queries made to the - backend MySQL database) + - discovery metrics (time to poll a MySQL server and collect status) + - queue metrics (statistics within the discovery queue itself) + - query metrics (statistics on the number of queries made to the + backend MySQL database) Orchestrator code can just add a new metric without worrying about removing it later, and other code which serves API requests can @@ -57,7 +56,6 @@ orchestrator run out of memory eventually. Current code uses DiscoveryCollectionRetentionSeconds as the time to keep metric data. - */ package collection diff --git a/go/vt/orchestrator/inst/instance_binlog.go b/go/vt/orchestrator/inst/instance_binlog.go index b832af6a20c..adf0d4041fe 100644 --- a/go/vt/orchestrator/inst/instance_binlog.go +++ b/go/vt/orchestrator/inst/instance_binlog.go @@ -43,12 +43,10 @@ type BinlogEvent struct { Info string } -// func (binlogEvent *BinlogEvent) NextBinlogCoordinates() BinlogCoordinates { return BinlogCoordinates{LogFile: binlogEvent.Coordinates.LogFile, LogPos: binlogEvent.NextEventPos, Type: binlogEvent.Coordinates.Type} } -// func (binlogEvent *BinlogEvent) NormalizeInfo() { for reg, replace := range eventInfoTransformations { binlogEvent.Info = reg.ReplaceAllString(binlogEvent.Info, replace) @@ -68,7 +66,6 @@ func (binlogEvent *BinlogEvent) EqualsIgnoreCoordinates(other *BinlogEvent) bool const maxEmptyEventsEvents int = 10 -// type BinlogEventCursor struct { cachedEvents []BinlogEvent currentEventIndex int diff --git a/go/vt/orchestrator/inst/instance_key.go b/go/vt/orchestrator/inst/instance_key.go index 2194bacc152..b8b3b6ec4af 100644 --- a/go/vt/orchestrator/inst/instance_key.go +++ b/go/vt/orchestrator/inst/instance_key.go @@ -106,7 +106,6 @@ func NewRawInstanceKeyStrings(hostname string, port string) (*InstanceKey, error return newInstanceKeyStrings(hostname, port, false) } -// func (instanceKey *InstanceKey) ResolveHostname() (*InstanceKey, error) { if !instanceKey.IsValid() { return instanceKey, nil diff --git a/go/vt/orchestrator/logic/orchestrator.go b/go/vt/orchestrator/logic/orchestrator.go index d3e8efd6390..4e36072b37e 100644 --- a/go/vt/orchestrator/logic/orchestrator.go +++ b/go/vt/orchestrator/logic/orchestrator.go @@ -383,7 +383,7 @@ func injectSeeds(seedOnce *sync.Once) { // ContinuousDiscovery starts an asynchronuous infinite discovery process where instances are // periodically investigated and their status captured, and long since unseen instances are // purged and forgotten. -//nolint SA1015: using time.Tick leaks the underlying ticker +// nolint SA1015: using time.Tick leaks the underlying ticker func ContinuousDiscovery() { log.Infof("continuous discovery: setting up") continuousDiscoveryStartTime := time.Now() diff --git a/go/vt/orchestrator/os/unixcheck_test.go b/go/vt/orchestrator/os/unixcheck_test.go index 0121f3c503d..375cbf4778f 100644 --- a/go/vt/orchestrator/os/unixcheck_test.go +++ b/go/vt/orchestrator/os/unixcheck_test.go @@ -1,17 +1,17 @@ /* - Copyright 2017 Simon Mudd, courtesy Booking.com +Copyright 2017 Simon Mudd, courtesy Booking.com - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. */ package os diff --git a/go/vt/proto/vtrpc/vtrpc.pb.go b/go/vt/proto/vtrpc/vtrpc.pb.go index 79e2a6d8e25..37c2583246c 100644 --- a/go/vt/proto/vtrpc/vtrpc.pb.go +++ b/go/vt/proto/vtrpc/vtrpc.pb.go @@ -39,7 +39,9 @@ const ( // Code represents canonical error codes. The names, numbers and comments // must match the ones defined by grpc (0-16): -// https://godoc.org/google.golang.org/grpc/codes. +// +// https://godoc.org/google.golang.org/grpc/codes. +// // 17+ are custom codes type Code int32 diff --git a/go/vt/schemadiff/table.go b/go/vt/schemadiff/table.go index 9bc79524f3d..647b922a78b 100644 --- a/go/vt/schemadiff/table.go +++ b/go/vt/schemadiff/table.go @@ -108,7 +108,6 @@ func (d *AlterTableEntityDiff) addSubsequentDiff(diff *AlterTableEntityDiff) { } } -// type CreateTableEntityDiff struct { createTable *sqlparser.CreateTable } @@ -164,7 +163,6 @@ func (d *CreateTableEntityDiff) SubsequentDiff() EntityDiff { func (d *CreateTableEntityDiff) SetSubsequentDiff(EntityDiff) { } -// type DropTableEntityDiff struct { from *CreateTableEntity dropTable *sqlparser.DropTable @@ -1673,9 +1671,9 @@ func (c *CreateTableEntity) Apply(diff EntityDiff) (Entity, error) { // postApplyNormalize runs at the end of apply() and to reorganize/edit things that // a MySQL will do implicitly: -// - edit or remove keys if referenced columns are dropped -// - drop check constraints for a single specific column if that column -// is the only referenced column in that check constraint. +// - edit or remove keys if referenced columns are dropped +// - drop check constraints for a single specific column if that column +// is the only referenced column in that check constraint. func (c *CreateTableEntity) postApplyNormalize() error { // reduce or remove keys based on existing column list // (a column may have been removed)postApplyNormalize diff --git a/go/vt/schemadiff/view.go b/go/vt/schemadiff/view.go index f01138ea448..baa25635cb2 100644 --- a/go/vt/schemadiff/view.go +++ b/go/vt/schemadiff/view.go @@ -22,7 +22,6 @@ import ( "vitess.io/vitess/go/vt/sqlparser" ) -// type AlterViewEntityDiff struct { from *CreateViewEntity to *CreateViewEntity diff --git a/go/vt/schemamanager/local_controller.go b/go/vt/schemamanager/local_controller.go index 8a6fa650e89..b95bb1398bf 100644 --- a/go/vt/schemamanager/local_controller.go +++ b/go/vt/schemamanager/local_controller.go @@ -30,27 +30,29 @@ import ( // LocalController listens to the specified schema change dir and applies schema changes. // schema change dir lay out -// | -// |----keyspace_01 -// |----input -// |---- create_test_table.sql -// |---- alter_test_table_02.sql -// |---- ... -// |----complete // contains completed schema changes in yyyy/MM/dd -// |----2015 -// |----01 -// |----01 -// |--- create_table_table_02.sql -// |----log // contains detailed execution information about schema changes -// |----2015 -// |----01 -// |----01 -// |--- create_table_table_02.sql -// |----error // contains failed schema changes -// |----2015 -// |----01 -// |----01 -// |--- create_table_table_03.sql +// +// | +// |----keyspace_01 +// |----input +// |---- create_test_table.sql +// |---- alter_test_table_02.sql +// |---- ... +// |----complete // contains completed schema changes in yyyy/MM/dd +// |----2015 +// |----01 +// |----01 +// |--- create_table_table_02.sql +// |----log // contains detailed execution information about schema changes +// |----2015 +// |----01 +// |----01 +// |--- create_table_table_02.sql +// |----error // contains failed schema changes +// |----2015 +// |----01 +// |----01 +// |--- create_table_table_03.sql +// // Schema Change Files: ${keyspace}/input/*.sql // Error Files: ${keyspace}/error/${YYYY}/${MM}/${DD}/*.sql // Log Files: ${keyspace}/log/${YYYY}/${MM}/${DD}/*.sql diff --git a/go/vt/schemamanager/tablet_executor.go b/go/vt/schemamanager/tablet_executor.go index 771bbad5816..dc9a871dd19 100644 --- a/go/vt/schemamanager/tablet_executor.go +++ b/go/vt/schemamanager/tablet_executor.go @@ -216,8 +216,8 @@ func (exec *TabletExecutor) isOnlineSchemaDDL(stmt sqlparser.Statement) (isOnlin // a schema change that satisfies any following condition is considered // to be a big schema change and will be rejected. -// 1. Alter more than 100,000 rows. -// 2. Change a table with more than 2,000,000 rows (Drops are fine). +// 1. Alter more than 100,000 rows. +// 2. Change a table with more than 2,000,000 rows (Drops are fine). func (exec *TabletExecutor) detectBigSchemaChanges(ctx context.Context, parsedDDLs []sqlparser.DDLStatement) (bool, error) { // We want to avoid any overhead if possible. If all DDLs are online schema changes, then we want to // skip GetSchema altogether. diff --git a/go/vt/sqlparser/analyzer.go b/go/vt/sqlparser/analyzer.go index abf74a80e48..635023ff258 100644 --- a/go/vt/sqlparser/analyzer.go +++ b/go/vt/sqlparser/analyzer.go @@ -60,7 +60,7 @@ const ( StmtShowMigrationLogs ) -//ASTToStatementType returns a StatementType from an AST stmt +// ASTToStatementType returns a StatementType from an AST stmt func ASTToStatementType(stmt Statement) StatementType { switch stmt.(type) { case *Select, *Union: @@ -116,7 +116,7 @@ func ASTToStatementType(stmt Statement) StatementType { } } -//CanNormalize takes Statement and returns if the statement can be normalized. +// CanNormalize takes Statement and returns if the statement can be normalized. func CanNormalize(stmt Statement) bool { switch stmt.(type) { case *Select, *Union, *Insert, *Update, *Delete, *Set, *CallProc, *Stream: // TODO: we could merge this logic into ASTrewriter @@ -308,7 +308,7 @@ func IsDML(sql string) bool { return false } -//IsDMLStatement returns true if the query is an INSERT, UPDATE or DELETE statement. +// IsDMLStatement returns true if the query is an INSERT, UPDATE or DELETE statement. func IsDMLStatement(stmt Statement) bool { switch stmt.(type) { case *Insert, *Update, *Delete: @@ -447,7 +447,7 @@ func IsSimpleTuple(node Expr) bool { return false } -//IsLockingFunc returns true for all functions that are used to work with mysql advisory locks +// IsLockingFunc returns true for all functions that are used to work with mysql advisory locks func IsLockingFunc(node Expr) bool { switch node.(type) { case *LockingFunc: diff --git a/go/vt/sqlparser/bind_var_needs.go b/go/vt/sqlparser/bind_var_needs.go index 5d542ad47ab..1b26919ca03 100644 --- a/go/vt/sqlparser/bind_var_needs.go +++ b/go/vt/sqlparser/bind_var_needs.go @@ -25,34 +25,34 @@ type BindVarNeeds struct { otherRewrites bool } -//MergeWith adds bind vars needs coming from sub scopes +// MergeWith adds bind vars needs coming from sub scopes func (bvn *BindVarNeeds) MergeWith(other *BindVarNeeds) { bvn.NeedFunctionResult = append(bvn.NeedFunctionResult, other.NeedFunctionResult...) bvn.NeedSystemVariable = append(bvn.NeedSystemVariable, other.NeedSystemVariable...) bvn.NeedUserDefinedVariables = append(bvn.NeedUserDefinedVariables, other.NeedUserDefinedVariables...) } -//AddFuncResult adds a function bindvar need +// AddFuncResult adds a function bindvar need func (bvn *BindVarNeeds) AddFuncResult(name string) { bvn.NeedFunctionResult = append(bvn.NeedFunctionResult, name) } -//AddSysVar adds a system variable bindvar need +// AddSysVar adds a system variable bindvar need func (bvn *BindVarNeeds) AddSysVar(name string) { bvn.NeedSystemVariable = append(bvn.NeedSystemVariable, name) } -//AddUserDefVar adds a user defined variable bindvar need +// AddUserDefVar adds a user defined variable bindvar need func (bvn *BindVarNeeds) AddUserDefVar(name string) { bvn.NeedUserDefinedVariables = append(bvn.NeedUserDefinedVariables, name) } -//NeedsFuncResult says if a function result needs to be provided +// NeedsFuncResult says if a function result needs to be provided func (bvn *BindVarNeeds) NeedsFuncResult(name string) bool { return contains(bvn.NeedFunctionResult, name) } -//NeedsSysVar says if a function result needs to be provided +// NeedsSysVar says if a function result needs to be provided func (bvn *BindVarNeeds) NeedsSysVar(name string) bool { return contains(bvn.NeedSystemVariable, name) } diff --git a/go/vt/sqlparser/comments.go b/go/vt/sqlparser/comments.go index 739532fd6ca..26e11fc4792 100644 --- a/go/vt/sqlparser/comments.go +++ b/go/vt/sqlparser/comments.go @@ -207,7 +207,7 @@ type CommentDirectives map[string]string // Directives parses the comment list for any execution directives // of the form: // -// /*vt+ OPTION_ONE=1 OPTION_TWO OPTION_THREE=abcd */ +// /*vt+ OPTION_ONE=1 OPTION_TWO OPTION_THREE=abcd */ // // It returns the map of the directive values or nil if there aren't any. func (c *ParsedComments) Directives() CommentDirectives { diff --git a/go/vt/sqlparser/constants.go b/go/vt/sqlparser/constants.go index b3da02fb1b7..6066ec08d9f 100644 --- a/go/vt/sqlparser/constants.go +++ b/go/vt/sqlparser/constants.go @@ -408,7 +408,7 @@ const ( ReadWrite ) -//Constants for Enum type - IsolationLevel +// Constants for Enum type - IsolationLevel const ( ReadUncommitted IsolationLevel = iota ReadCommitted diff --git a/go/vt/sqlparser/goyacc/goyacc.go b/go/vt/sqlparser/goyacc/goyacc.go index 16837149d9d..98974adc385 100644 --- a/go/vt/sqlparser/goyacc/goyacc.go +++ b/go/vt/sqlparser/goyacc/goyacc.go @@ -761,9 +761,7 @@ outer: } } -// // allocate enough room to hold another production -// func moreprod() { n := len(prdptr) if nprod >= n { @@ -782,10 +780,8 @@ func moreprod() { } } -// // define s to be a terminal if nt==0 // or a nonterminal if nt==1 -// func defin(nt int, s string) int { val := 0 if nt != 0 { @@ -1026,9 +1022,7 @@ func getword(c rune) { ungetrune(finput, c) } -// // determine the type of a symbol -// func fdtype(t int) (int, string) { var v int var s string @@ -1112,9 +1106,7 @@ func typeinfo() { } } -// // copy the union declaration to the output, and the define file if present -// func parsetypes(union bool) { var member, typ bytes.Buffer state := startUnion @@ -1170,10 +1162,8 @@ out: } } -// // saves code between %{ and %} // adds an import for __fmt__ the first time -// func cpycode() { lno := lineno @@ -1206,11 +1196,9 @@ func cpycode() { errorf("eof before %%}") } -// // emits code saved up from between %{ and %} // called by cpycode // adds an import for __yyfmt__ after the package clause -// func emitcode(code []rune, lineno int) { for i, line := range lines(code) { writecode(line) @@ -1227,9 +1215,7 @@ func emitcode(code []rune, lineno int) { } } -// // does this line look like a package clause? not perfect: might be confused by early comments. -// func isPackageClause(line []rune) bool { line = skipspace(line) @@ -1271,9 +1257,7 @@ func isPackageClause(line []rune) bool { return false } -// // skip initial spaces -// func skipspace(line []rune) []rune { for len(line) > 0 { if line[0] != ' ' && line[0] != '\t' { @@ -1284,9 +1268,7 @@ func skipspace(line []rune) []rune { return line } -// // break code into lines -// func lines(code []rune) [][]rune { l := make([][]rune, 0, 100) for len(code) > 0 { @@ -1303,19 +1285,15 @@ func lines(code []rune) [][]rune { return l } -// // writes code to ftable -// func writecode(code []rune) { for _, r := range code { ftable.WriteRune(r) } } -// // skip over comments // skipcom is called after reading a '/' -// func skipcom() int { c := getrune(finput) if c == '/' { @@ -1429,9 +1407,7 @@ loop: fcode.Write(buf.Bytes()) } -// // copy action to the next ; or closing } -// func cpyact(fcode *bytes.Buffer, curprod []int, max int, unionType *string) { if !lflag { fmt.Fprintf(fcode, "\n//line %v:%v", infile, lineno) @@ -1648,9 +1624,7 @@ func openup() { } -// // return a pointer to the name of symbol i -// func symnam(i int) string { var s string @@ -1662,20 +1636,16 @@ func symnam(i int) string { return s } -// // set elements 0 through n-1 to c -// func aryfil(v []int, n, c int) { for i := 0; i < n; i++ { v[i] = c } } -// // compute an array with the beginnings of productions yielding given nonterminals // The array pres points to these lists // the array pyield has the lists: the total size is only NPROD+1 -// func cpres() { pres = make([][][]int, nnonter+1) curres := make([][]int, nprod) @@ -1713,10 +1683,8 @@ func cpres() { } } -// // mark nonterminals which derive the empty string // also, look for nonterminals which don't derive any token strings -// func cempty() { var i, p, np int var prd []int @@ -1799,9 +1767,7 @@ again: } } -// // compute an array with the first of nonterminals -// func cpfir() { var s, n, p, np, ch, i int var curres [][]int @@ -1867,9 +1833,7 @@ func cpfir() { } } -// // generate the states -// func stagen() { // initialize nstate = 0 @@ -1959,9 +1923,7 @@ func stagen() { } } -// // generate the closure of state i -// func closure(i int) { zzclose++ @@ -2091,9 +2053,7 @@ func closure(i int) { } } -// // sorts last state,and sees if it equals earlier ones. returns state number -// func state(c int) int { zzstate++ p1 := pstate[nstate] @@ -2206,9 +2166,7 @@ func putitem(p Pitem, set Lkset) { pstate[nstate+1] = j } -// // creates output string for item pointed to by pp -// func writem(pp Pitem) string { var i int @@ -2242,9 +2200,7 @@ func writem(pp Pitem) string { return q } -// // pack state i from temp1 into amem -// func apack(p []int, n int) int { // // we don't need to worry about checking because @@ -2309,9 +2265,7 @@ nextk: return 0 } -// // print the output for the states -// func output() { var c, u, v int @@ -2399,12 +2353,10 @@ func output() { fmt.Fprintf(ftable, "const %sPrivate = %v\n", prefix, PRIVATE) } -// // decide a shift/reduce conflict by precedence. // r is a rule number, t a token number // the conflict is in state s // temp1[t] is changed to reflect the action -// func precftn(r, t, s int) { var action int @@ -2435,10 +2387,8 @@ func precftn(r, t, s int) { } } -// // output state i // temp1 has the actions, lastred the default -// func wract(i int) { var p, p1 int @@ -2526,9 +2476,7 @@ func wract(i int) { optst[i] = os } -// // writes state i -// func wrstate(i int) { var j0, j1, u int var pp, qq int @@ -2598,9 +2546,7 @@ func wrstate(i int) { } } -// // output the gotos for the nontermninals -// func go2out() { for i := 1; i <= nnonter; i++ { go2gen(i) @@ -2663,9 +2609,7 @@ func go2out() { } } -// // output the gotos for nonterminal c -// func go2gen(c int) { var i, cc, p, q int @@ -2717,12 +2661,10 @@ func go2gen(c int) { } } -// // in order to free up the mem and amem arrays for the optimizer, // and still be able to output yyr1, etc., after the sizes of // the action array is known, we hide the nonterminals // derived by productions in levprd. -// func hideprod() { nred := 0 levprd[0] = 0 @@ -2836,9 +2778,7 @@ func callopt() { osummary() } -// // finds the next i -// func nxti() int { max := 0 maxi := 0 @@ -2975,10 +2915,8 @@ nextn: errorf("Error; failure to place state %v", i) } -// // this version is for limbo // write out the optimized parser -// func aoutput() { ftable.WriteRune('\n') fmt.Fprintf(ftable, "const %sLast = %v\n", prefix, maxa+1) @@ -2987,9 +2925,7 @@ func aoutput() { arout("Pgo", pgo, nnonter+1) } -// // put out other arrays, copy the parsers -// func others() { var i, j int @@ -3189,9 +3125,7 @@ func arout(s string, v []int, n int) { fmt.Fprintf(ftable, "\n}\n") } -// // output the summary on y.output -// func summary() { if foutput != nil { fmt.Fprintf(foutput, "\n%v terminals, %v nonterminals\n", ntokens, nnonter+1) @@ -3219,9 +3153,7 @@ func summary() { } } -// // write optimizer summary -// func osummary() { if foutput == nil { return @@ -3238,9 +3170,7 @@ func osummary() { fmt.Fprintf(foutput, "maximum spread: %v, maximum offset: %v\n", maxspr, maxoff) } -// // copies and protects "'s in q -// func chcopy(q string) string { s := "" i := 0 @@ -3265,10 +3195,8 @@ func setbit(set Lkset, bit int) { set[bit>>5] |= (1 << uint(bit&31)) } func mkset() Lkset { return make([]int, tbitset) } -// // set a to the union of a and b // return 1 if b is not a subset of a, 0 otherwise -// func setunion(a, b []int) int { sub := 0 for i := 0; i < tbitset; i++ { @@ -3296,9 +3224,7 @@ func prlook(p Lkset) { fmt.Fprintf(foutput, "}") } -// // utility routines -// var peekrune rune func isdigit(c rune) bool { return c >= '0' && c <= '9' } @@ -3307,10 +3233,8 @@ func isword(c rune) bool { return c >= 0xa0 || c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') } -// // return 1 if 2 arrays are equal // return 0 if not equal -// func aryeq(a []int, b []int) int { n := len(a) if len(b) != n { @@ -3375,9 +3299,7 @@ func create(s string) *bufio.Writer { return bufio.NewWriter(fo) } -// // write out error comment -// func lerrorf(lineno int, s string, v ...any) { nerrors++ fmt.Fprintf(stderr, s, v...) diff --git a/go/vt/sqlparser/parsed_query.go b/go/vt/sqlparser/parsed_query.go index 174a7df23fc..feeb34ce676 100644 --- a/go/vt/sqlparser/parsed_query.go +++ b/go/vt/sqlparser/parsed_query.go @@ -203,7 +203,8 @@ func FetchBindVar(name string, bindVariables map[string]*querypb.BindVariable) ( // ParseAndBind is a one step sweep that binds variables to an input query, in order of placeholders. // It is useful when one doesn't have any parser-variables, just bind variables. // Example: -// query, err := ParseAndBind("select * from tbl where name=%a", sqltypes.StringBindVariable("it's me")) +// +// query, err := ParseAndBind("select * from tbl where name=%a", sqltypes.StringBindVariable("it's me")) func ParseAndBind(in string, binds ...*querypb.BindVariable) (query string, err error) { vars := make([]any, len(binds)) for i := range binds { diff --git a/go/vt/sqlparser/parser.go b/go/vt/sqlparser/parser.go index 338b3b58e97..68cc54b6da4 100644 --- a/go/vt/sqlparser/parser.go +++ b/go/vt/sqlparser/parser.go @@ -51,8 +51,9 @@ var MySQLVersion = "50709" // default version if nothing else is stated // // N.B: Parser pooling means that you CANNOT take references directly to parse stack variables (e.g. // $$ = &$4) in sql.y rules. You must instead add an intermediate reference like so: -// showCollationFilterOpt := $4 -// $$ = &Show{Type: string($2), ShowCollationFilterOpt: &showCollationFilterOpt} +// +// showCollationFilterOpt := $4 +// $$ = &Show{Type: string($2), ShowCollationFilterOpt: &showCollationFilterOpt} func yyParsePooled(yylex yyLexer) int { parser := parserPool.Get().(*yyParserImpl) defer func() { diff --git a/go/vt/sqlparser/precedence.go b/go/vt/sqlparser/precedence.go index f21f0df7328..d63a56b62ef 100644 --- a/go/vt/sqlparser/precedence.go +++ b/go/vt/sqlparser/precedence.go @@ -43,8 +43,8 @@ const ( // precedenceFor returns the precedence of an expression. // -// * NOTE: If you change anything here, update sql.y to keep them consistent. -// Also make sure to add the new constructs to random_expr.go so we have test coverage for the new expressions * +// - NOTE: If you change anything here, update sql.y to keep them consistent. +// Also make sure to add the new constructs to random_expr.go so we have test coverage for the new expressions * func precedenceFor(in Expr) Precendence { switch node := in.(type) { case *OrExpr: diff --git a/go/vt/sqlparser/random_expr.go b/go/vt/sqlparser/random_expr.go index 5bcff24616a..e2725f37a37 100644 --- a/go/vt/sqlparser/random_expr.go +++ b/go/vt/sqlparser/random_expr.go @@ -54,14 +54,15 @@ func (g *generator) atMaxDepth() bool { return g.depth >= g.maxDepth } -/* Creates a random expression. It builds an expression tree using the following constructs: - - true/false - - AND/OR/NOT - - string literalrs, numeric literals (-/+ 1000) - - =, >, <, >=, <=, <=>, != - - &, |, ^, +, -, *, /, div, %, <<, >> - - IN, BETWEEN and CASE - - IS NULL, IS NOT NULL, IS TRUE, IS NOT TRUE, IS FALSE, IS NOT FALSE +/* + Creates a random expression. It builds an expression tree using the following constructs: + - true/false + - AND/OR/NOT + - string literalrs, numeric literals (-/+ 1000) + - =, >, <, >=, <=, <=>, != + - &, |, ^, +, -, *, /, div, %, <<, >> + - IN, BETWEEN and CASE + - IS NULL, IS NOT NULL, IS TRUE, IS NOT TRUE, IS FALSE, IS NOT FALSE Note: It's important to update this method so that it produces all expressions that need precedence checking. It's currently missing function calls and string operators diff --git a/go/vt/sqlparser/rewriter_api.go b/go/vt/sqlparser/rewriter_api.go index 7398b4739e8..8444ba8f068 100644 --- a/go/vt/sqlparser/rewriter_api.go +++ b/go/vt/sqlparser/rewriter_api.go @@ -33,7 +33,6 @@ package sqlparser // // Only fields that refer to AST nodes are considered children; // i.e., fields of basic types (strings, []byte, etc.) are ignored. -// func Rewrite(node SQLNode, pre, post ApplyFunc) (result SQLNode) { parent := &RootNode{node} diff --git a/go/vt/tableacl/tableacl.go b/go/vt/tableacl/tableacl.go index 5d834582c57..4f83edf18e7 100644 --- a/go/vt/tableacl/tableacl.go +++ b/go/vt/tableacl/tableacl.go @@ -88,16 +88,16 @@ var currentTableACL tableACL // The config file can be binary-proto-encoded, or json-encoded. // In the json case, it looks like this: // -// { -// "table_groups": [ -// { -// "table_names_or_prefixes": ["name1"], -// "readers": ["client1"], -// "writers": ["client1"], -// "admins": ["client1"] -// } -// ] -// } +// { +// "table_groups": [ +// { +// "table_names_or_prefixes": ["name1"], +// "readers": ["client1"], +// "writers": ["client1"], +// "admins": ["client1"] +// } +// ] +// } func Init(configFile string, aclCB func()) error { return currentTableACL.init(configFile, aclCB) } diff --git a/go/vt/throttler/throttler.go b/go/vt/throttler/throttler.go index 0c94bcb29c6..4af500ce46c 100644 --- a/go/vt/throttler/throttler.go +++ b/go/vt/throttler/throttler.go @@ -71,7 +71,8 @@ const ( // Calls of Throttle() and ThreadFinished() take threadID as parameter which is // in the range [0, threadCount). (threadCount is set in NewThrottler().) // NOTE: Trottle() and ThreadFinished() assume that *per thread* calls to them -// are serialized and must not happen concurrently. +// +// are serialized and must not happen concurrently. type Throttler struct { // name describes the Throttler instance and is used e.g. in the webinterface. name string diff --git a/go/vt/topo/conn.go b/go/vt/topo/conn.go index cf75617ef45..22eaa870c91 100644 --- a/go/vt/topo/conn.go +++ b/go/vt/topo/conn.go @@ -293,32 +293,33 @@ type KVInfo struct { // // mp := server.NewLeaderParticipation("vtctld", "hostname:8080") // job := NewJob() -// go func() { -// for { -// ctx, err := mp.WaitForLeadership() -// switch err { -// case nil: -// job.RunUntilContextDone(ctx) -// case topo.ErrInterrupted: -// return -// default: -// log.Errorf("Got error while waiting for primary, will retry in 5s: %v", err) -// time.Sleep(5 * time.Second) -// } -// } -// }() // -// http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { -// if job.Running() { -// job.WriteStatus(w, r) -// } else { -// http.Redirect(w, r, mp.GetCurrentLeaderID(context.Background()), http.StatusFound) -// } -// }) +// go func() { +// for { +// ctx, err := mp.WaitForLeadership() +// switch err { +// case nil: +// job.RunUntilContextDone(ctx) +// case topo.ErrInterrupted: +// return +// default: +// log.Errorf("Got error while waiting for primary, will retry in 5s: %v", err) +// time.Sleep(5 * time.Second) +// } +// } +// }() // -// servenv.OnTermSync(func() { -// mp.Stop() -// }) +// http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { +// if job.Running() { +// job.WriteStatus(w, r) +// } else { +// http.Redirect(w, r, mp.GetCurrentLeaderID(context.Background()), http.StatusFound) +// } +// }) +// +// servenv.OnTermSync(func() { +// mp.Stop() +// }) type LeaderParticipation interface { // WaitForLeadership makes the current process a candidate // for election, and waits until this process is the primary. diff --git a/go/vt/topo/helpers/tee.go b/go/vt/topo/helpers/tee.go index abec09d0713..32c597cec79 100644 --- a/go/vt/topo/helpers/tee.go +++ b/go/vt/topo/helpers/tee.go @@ -29,10 +29,11 @@ import ( // when needed. It is meant to be used during transitions from one // topo.Server to another. // -// - primary: we read everything from it, and write to it. We also create +// - primary: we read everything from it, and write to it. We also create // LeaderParticipation from it. -// - secondary: we write to it as well, but we usually don't fail. -// - we lock primary/secondary if reverseLockOrder is False, +// - secondary: we write to it as well, but we usually don't fail. +// - we lock primary/secondary if reverseLockOrder is False, +// // or secondary/primary if reverseLockOrder is True. type TeeFactory struct { primary *topo.Server diff --git a/go/vt/topo/k8stopo/client/clientset/versioned/fake/register.go b/go/vt/topo/k8stopo/client/clientset/versioned/fake/register.go index 5b425fd4603..fea362af64c 100644 --- a/go/vt/topo/k8stopo/client/clientset/versioned/fake/register.go +++ b/go/vt/topo/k8stopo/client/clientset/versioned/fake/register.go @@ -38,14 +38,14 @@ var localSchemeBuilder = runtime.SchemeBuilder{ // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) +// import ( +// "k8s.io/client-go/kubernetes" +// clientsetscheme "k8s.io/client-go/kubernetes/scheme" +// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" +// ) // -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) +// kclientset, _ := kubernetes.NewForConfig(c) +// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. diff --git a/go/vt/topo/k8stopo/client/clientset/versioned/scheme/register.go b/go/vt/topo/k8stopo/client/clientset/versioned/scheme/register.go index 1d8b48578cc..7a9084ecb67 100644 --- a/go/vt/topo/k8stopo/client/clientset/versioned/scheme/register.go +++ b/go/vt/topo/k8stopo/client/clientset/versioned/scheme/register.go @@ -38,14 +38,14 @@ var localSchemeBuilder = runtime.SchemeBuilder{ // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: // -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) +// import ( +// "k8s.io/client-go/kubernetes" +// clientsetscheme "k8s.io/client-go/kubernetes/scheme" +// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" +// ) // -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) +// kclientset, _ := kubernetes.NewForConfig(c) +// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) // // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. diff --git a/go/vt/topo/locks.go b/go/vt/topo/locks.go index ad43a873198..cda93c33192 100644 --- a/go/vt/topo/locks.go +++ b/go/vt/topo/locks.go @@ -122,13 +122,14 @@ var locksKey locksKeyType // * changing a keyspace sharding info fields (is this one necessary?) // * changing a keyspace 'ServedFrom' field (is this one necessary?) // * resharding operations: -// * horizontal resharding: includes changing the shard's 'ServedType', +// - horizontal resharding: includes changing the shard's 'ServedType', // as well as the associated horizontal resharding operations. -// * vertical resharding: includes changing the keyspace 'ServedFrom' +// - vertical resharding: includes changing the keyspace 'ServedFrom' // field, as well as the associated vertical resharding operations. -// * 'vtctl SetShardIsPrimaryServing' emergency operations -// * 'vtctl SetShardTabletControl' emergency operations -// * 'vtctl SourceShardAdd' and 'vtctl SourceShardDelete' emergency operations +// - 'vtctl SetShardIsPrimaryServing' emergency operations +// - 'vtctl SetShardTabletControl' emergency operations +// - 'vtctl SourceShardAdd' and 'vtctl SourceShardDelete' emergency operations +// // * keyspace-wide schema changes func (ts *Server) LockKeyspace(ctx context.Context, keyspace, action string) (context.Context, func(*error), error) { i, ok := ctx.Value(locksKey).(*locksInfo) @@ -286,12 +287,12 @@ func (l *Lock) unlockKeyspace(ctx context.Context, ts *Server, keyspace string, // UpdateShardFields, which is not locking the shard object. The // current list of actions that lock a shard are: // * all Vitess-controlled re-parenting operations: -// * InitShardPrimary -// * PlannedReparentShard -// * EmergencyReparentShard -// * operations that we don't want to conflict with re-parenting: -// * DeleteTablet when it's the shard's current primary +// - InitShardPrimary +// - PlannedReparentShard +// - EmergencyReparentShard // +// * operations that we don't want to conflict with re-parenting: +// - DeleteTablet when it's the shard's current primary func (ts *Server) LockShard(ctx context.Context, keyspace, shard, action string) (context.Context, func(*error), error) { i, ok := ctx.Value(locksKey).(*locksInfo) if !ok { diff --git a/go/vt/topo/server.go b/go/vt/topo/server.go index 4d783379443..67a2b2f0e55 100644 --- a/go/vt/topo/server.go +++ b/go/vt/topo/server.go @@ -33,12 +33,12 @@ time (using helpers/tee.go). This is to facilitate migrations between topo servers. There are two test sub-packages associated with this code: -- test/ contains a test suite that is run against all of our implementations. - It just performs a bunch of common topo server activities (create, list, - delete various objects, ...). If a topo implementation passes all these - tests, it most likely will work as expected in a real deployment. -- topotests/ contains tests that use a memorytopo to test the code in this - package. + - test/ contains a test suite that is run against all of our implementations. + It just performs a bunch of common topo server activities (create, list, + delete various objects, ...). If a topo implementation passes all these + tests, it most likely will work as expected in a real deployment. + - topotests/ contains tests that use a memorytopo to test the code in this + package. */ package topo @@ -113,14 +113,14 @@ type Factory interface { } // Server is the main topo.Server object. We support two ways of creating one: -// 1. From an implementation, server address, and root path. -// This uses a plugin mechanism, and we have implementations for -// etcd, zookeeper and consul. -// 2. Specific implementations may have higher level creation methods -// (in which case they may provide a more complex Factory). -// We support memorytopo (for tests and processes that only need an -// in-memory server), and tee (a helper implementation to transition -// between one server implementation and another). +// 1. From an implementation, server address, and root path. +// This uses a plugin mechanism, and we have implementations for +// etcd, zookeeper and consul. +// 2. Specific implementations may have higher level creation methods +// (in which case they may provide a more complex Factory). +// We support memorytopo (for tests and processes that only need an +// in-memory server), and tee (a helper implementation to transition +// between one server implementation and another). type Server struct { // globalCell is the main connection to the global topo service. // It is created once at construction time. diff --git a/go/vt/topo/shard.go b/go/vt/topo/shard.go index d1da7c94256..2f3d7ad49ff 100644 --- a/go/vt/topo/shard.go +++ b/go/vt/topo/shard.go @@ -389,10 +389,10 @@ func (si *ShardInfo) GetTabletControl(tabletType topodatapb.TabletType) *topodat // UpdateSourceDeniedTables will add or remove the listed tables // in the shard record's TabletControl structures. Note we don't // support a lot of the corner cases: -// - only support one table list per shard. If we encounter a different -// table list that the provided one, we error out. -// - we don't support DisableQueryService at the same time as DeniedTables, -// because it's not used in the same context (vertical vs horizontal sharding) +// - only support one table list per shard. If we encounter a different +// table list that the provided one, we error out. +// - we don't support DisableQueryService at the same time as DeniedTables, +// because it's not used in the same context (vertical vs horizontal sharding) // // This function should be called while holding the keyspace lock. func (si *ShardInfo) UpdateSourceDeniedTables(ctx context.Context, tabletType topodatapb.TabletType, cells []string, remove bool, tables []string) error { diff --git a/go/vt/topo/stats_conn_test.go b/go/vt/topo/stats_conn_test.go index bffc47f81df..1c7f962e966 100644 --- a/go/vt/topo/stats_conn_test.go +++ b/go/vt/topo/stats_conn_test.go @@ -133,7 +133,7 @@ func (st *fakeConn) IsReadOnly() bool { return st.readOnly } -//TestStatsConnTopoListDir emits stats on ListDir +// TestStatsConnTopoListDir emits stats on ListDir func TestStatsConnTopoListDir(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -160,7 +160,7 @@ func TestStatsConnTopoListDir(t *testing.T) { } } -//TestStatsConnTopoCreate emits stats on Create +// TestStatsConnTopoCreate emits stats on Create func TestStatsConnTopoCreate(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -187,7 +187,7 @@ func TestStatsConnTopoCreate(t *testing.T) { } } -//TestStatsConnTopoUpdate emits stats on Update +// TestStatsConnTopoUpdate emits stats on Update func TestStatsConnTopoUpdate(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -214,7 +214,7 @@ func TestStatsConnTopoUpdate(t *testing.T) { } } -//TestStatsConnTopoGet emits stats on Get +// TestStatsConnTopoGet emits stats on Get func TestStatsConnTopoGet(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -241,7 +241,7 @@ func TestStatsConnTopoGet(t *testing.T) { } } -//TestStatsConnTopoDelete emits stats on Delete +// TestStatsConnTopoDelete emits stats on Delete func TestStatsConnTopoDelete(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -268,7 +268,7 @@ func TestStatsConnTopoDelete(t *testing.T) { } } -//TestStatsConnTopoLock emits stats on Lock +// TestStatsConnTopoLock emits stats on Lock func TestStatsConnTopoLock(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -295,7 +295,7 @@ func TestStatsConnTopoLock(t *testing.T) { } } -//TestStatsConnTopoWatch emits stats on Watch +// TestStatsConnTopoWatch emits stats on Watch func TestStatsConnTopoWatch(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -309,7 +309,7 @@ func TestStatsConnTopoWatch(t *testing.T) { } -//TestStatsConnTopoNewLeaderParticipation emits stats on NewLeaderParticipation +// TestStatsConnTopoNewLeaderParticipation emits stats on NewLeaderParticipation func TestStatsConnTopoNewLeaderParticipation(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) @@ -351,7 +351,7 @@ func TestStatsConnTopoNewLeaderParticipation(t *testing.T) { } } -//TestStatsConnTopoClose emits stats on Close +// TestStatsConnTopoClose emits stats on Close func TestStatsConnTopoClose(t *testing.T) { conn := &fakeConn{} statsConn := NewStatsConn("global", conn) diff --git a/go/vt/topo/topotests/srv_vschema_test.go b/go/vt/topo/topotests/srv_vschema_test.go index a0e63c59e50..22f4457a5eb 100644 --- a/go/vt/topo/topotests/srv_vschema_test.go +++ b/go/vt/topo/topotests/srv_vschema_test.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/go/vt/topo/wildcards.go b/go/vt/topo/wildcards.go index aad2f255a47..c2921be1d19 100644 --- a/go/vt/topo/wildcards.go +++ b/go/vt/topo/wildcards.go @@ -31,10 +31,10 @@ import ( ) // ResolveKeyspaceWildcard will resolve keyspace wildcards. -// - If the param is not a wildcard, it will just be returned (if the keyspace -// doesn't exist, it is still returned). -// - If the param is a wildcard, it will get all keyspaces and returns -// the ones which match the wildcard (which may be an empty list). +// - If the param is not a wildcard, it will just be returned (if the keyspace +// doesn't exist, it is still returned). +// - If the param is a wildcard, it will get all keyspaces and returns +// the ones which match the wildcard (which may be an empty list). func (ts *Server) ResolveKeyspaceWildcard(ctx context.Context, param string) ([]string, error) { if !fileutil.HasWildcard(param) { return []string{param}, nil @@ -67,11 +67,11 @@ type KeyspaceShard struct { // ResolveShardWildcard will resolve shard wildcards. Both keyspace and shard // names can use wildcard. Errors talking to the topology server are returned. // ErrNoNode is ignored if it's the result of resolving a wildcard. Examples: -// - */* returns all keyspace/shard pairs, or empty list if none. -// - user/* returns all shards in user keyspace (or error if user keyspace -// doesn't exist) -// - us*/* returns all shards in all keyspaces that start with 'us'. If no such -// keyspace exists, list is empty (it is not an error). +// - */* returns all keyspace/shard pairs, or empty list if none. +// - user/* returns all shards in user keyspace (or error if user keyspace +// doesn't exist) +// - us*/* returns all shards in all keyspaces that start with 'us'. If no such +// keyspace exists, list is empty (it is not an error). func (ts *Server) ResolveShardWildcard(ctx context.Context, param string) ([]KeyspaceShard, error) { parts := strings.Split(param, "/") if len(parts) != 2 { diff --git a/go/vt/topo/zk2topo/election.go b/go/vt/topo/zk2topo/election.go index 1ff2f0a9577..deb9134f297 100644 --- a/go/vt/topo/zk2topo/election.go +++ b/go/vt/topo/zk2topo/election.go @@ -131,10 +131,10 @@ func (mp *zkLeaderParticipation) WaitForLeadership() (context.Context, error) { // watchLeadership is the background go routine we run while we are the primary. // We will do two things: -// - watch for changes to the proposal file. If anything happens there, -// it most likely means we lost the ZK session, so we want to stop -// being the primary. -// - wait for mp.stop. +// - watch for changes to the proposal file. If anything happens there, +// it most likely means we lost the ZK session, so we want to stop +// being the primary. +// - wait for mp.stop. func (mp *zkLeaderParticipation) watchLeadership(ctx context.Context, conn *ZkConn, proposal string, cancel context.CancelFunc) { // any interruption of this routine means we're not primary any more. defer cancel() diff --git a/go/vt/topo/zk2topo/server.go b/go/vt/topo/zk2topo/server.go index 6ecf7aeaab4..0809d1358fe 100644 --- a/go/vt/topo/zk2topo/server.go +++ b/go/vt/topo/zk2topo/server.go @@ -46,14 +46,14 @@ func hasObservers(serverAddr string) (string, string, bool) { // Further implementation design note: Zookeeper supports Observers: // https://zookeeper.apache.org/doc/trunk/zookeeperObservers.html // To use them, follow these instructions: -// * setup your observer servers as described in the previous link. -// * specify a second set of servers in serverAddr, after a '|', like: -// global1:port1,global2:port2|observer1:port1,observer2:port2 -// * if HasGlobalReadOnlyCell detects that the serverAddr has both lists, -// it returns true. -// * the Create method below also splits the values, and if -// cell is GlobalCell, use the left side, if cell is GlobalReadOnlyCell, -// use the right side. +// - setup your observer servers as described in the previous link. +// - specify a second set of servers in serverAddr, after a '|', like: +// global1:port1,global2:port2|observer1:port1,observer2:port2 +// - if HasGlobalReadOnlyCell detects that the serverAddr has both lists, +// it returns true. +// - the Create method below also splits the values, and if +// cell is GlobalCell, use the left side, if cell is GlobalReadOnlyCell, +// use the right side. func (f Factory) HasGlobalReadOnlyCell(serverAddr, root string) bool { _, _, ok := hasObservers(serverAddr) return ok diff --git a/go/vt/topo/zk2topo/zk_conn.go b/go/vt/topo/zk2topo/zk_conn.go index 7c124035b55..95e9d778b96 100644 --- a/go/vt/topo/zk2topo/zk_conn.go +++ b/go/vt/topo/zk2topo/zk_conn.go @@ -73,12 +73,12 @@ func ZkTime(t time.Time) int64 { // ZkConn is a wrapper class on top of a zk.Conn. // It will do a few things for us: -// - add the context parameter. However, we do not enforce its deadlines -// necessarily. -// - enforce a max concurrency of access to Zookeeper. We just don't -// want to make too many calls concurrently, to not take too many resources. -// - retry some calls to Zookeeper. If we were disconnected from the -// server, we want to try connecting again before failing. +// - add the context parameter. However, we do not enforce its deadlines +// necessarily. +// - enforce a max concurrency of access to Zookeeper. We just don't +// want to make too many calls concurrently, to not take too many resources. +// - retry some calls to Zookeeper. If we were disconnected from the +// server, we want to try connecting again before failing. type ZkConn struct { // addr is set at construction time, and immutable. addr string diff --git a/go/vt/topotools/tablet.go b/go/vt/topotools/tablet.go index 599d2310c29..af6f4b3c3c6 100644 --- a/go/vt/topotools/tablet.go +++ b/go/vt/topotools/tablet.go @@ -18,16 +18,15 @@ limitations under the License. Package topotools contains high level functions based on vt/topo and vt/actionnode. It should not depend on anything else that's higher level. In particular, it cannot depend on: -- vt/wrangler: much higher level, wrangler depends on topotools. -- vt/tabletmanager/initiator: we don't want the various remote - protocol dependencies here. + - vt/wrangler: much higher level, wrangler depends on topotools. + - vt/tabletmanager/initiator: we don't want the various remote + protocol dependencies here. topotools is used by wrangler, so it ends up in all tools using wrangler (vtctl, vtctld, ...). It is also included by vttablet, so it contains: -- most of the logic to create a shard / keyspace (tablet's init code) -- some of the logic to perform a TabletExternallyReparented (RPC call - to primary vttablet to let it know it's the primary). - + - most of the logic to create a shard / keyspace (tablet's init code) + - some of the logic to perform a TabletExternallyReparented (RPC call + to primary vttablet to let it know it's the primary). */ package topotools diff --git a/go/vt/topotools/utils.go b/go/vt/topotools/utils.go index 5dbdf6a22e5..6b618383a1e 100644 --- a/go/vt/topotools/utils.go +++ b/go/vt/topotools/utils.go @@ -84,11 +84,11 @@ func GetAllTabletsAcrossCells(ctx context.Context, ts *topo.Server) ([]*topo.Tab } // SortedTabletMap returns two maps: -// - The replicaMap contains all the non-primary non-scrapped hosts. -// This can be used as a list of replicas to fix up for reparenting -// - The primaryMap contains all the tablets without parents -// (scrapped or not). This can be used to special case -// the old primary, and any tablet in a weird state, left over, ... +// - The replicaMap contains all the non-primary non-scrapped hosts. +// This can be used as a list of replicas to fix up for reparenting +// - The primaryMap contains all the tablets without parents +// (scrapped or not). This can be used to special case +// the old primary, and any tablet in a weird state, left over, ... func SortedTabletMap(tabletMap map[string]*topo.TabletInfo) (map[string]*topo.TabletInfo, map[string]*topo.TabletInfo) { replicaMap := make(map[string]*topo.TabletInfo) primaryMap := make(map[string]*topo.TabletInfo) diff --git a/go/vt/vitessdriver/driver.go b/go/vt/vitessdriver/driver.go index 7f8a50a4956..b525084493c 100644 --- a/go/vt/vitessdriver/driver.go +++ b/go/vt/vitessdriver/driver.go @@ -109,7 +109,7 @@ type drv struct { // // Example for a JSON string: // -// {"protocol": "grpc", "address": "localhost:1111", "target": "@primary"} +// {"protocol": "grpc", "address": "localhost:1111", "target": "@primary"} // // For a description of the available fields, see the Configuration struct. func (d drv) Open(name string) (driver.Conn, error) { diff --git a/go/vt/vitessdriver/time.go b/go/vt/vitessdriver/time.go index aaf34331e87..dc2d4453c31 100644 --- a/go/vt/vitessdriver/time.go +++ b/go/vt/vitessdriver/time.go @@ -35,11 +35,11 @@ var isoTimeLength = len(isoTimeFormat) // parseISOTime pases a time string in MySQL's textual datetime format. // This is very similar to ISO8601, with some differences: // -// - There is no T separator between the date and time sections; -// a space is used instead. -// - There is never a timezone section in the string, as these datetimes -// are not timezone-aware. There isn't a Z value for UTC times for -// the same reason. +// - There is no T separator between the date and time sections; +// a space is used instead. +// - There is never a timezone section in the string, as these datetimes +// are not timezone-aware. There isn't a Z value for UTC times for +// the same reason. // // Note that this function can handle both DATE (which should _always_ have // a length of 10) and DATETIME strings (which have a variable length, 18+ diff --git a/go/vt/vtadmin/cache/cache.go b/go/vt/vtadmin/cache/cache.go index 95e92b5d350..1768ce1f924 100644 --- a/go/vt/vtadmin/cache/cache.go +++ b/go/vt/vtadmin/cache/cache.go @@ -90,13 +90,12 @@ type Config struct { // For example, to create a schema cache that can backfill full payloads (including // size aggregation): // -// var c *cache.Cache[BackfillSchemaRequest, *vtadminpb.Schema] -// c := cache.New(func(ctx context.Context, req BackfillSchemaRequest) (*vtadminpb.Schema, error) { -// // Fetch schema based on fields in `req`. -// // If err is nil, the backfilled schema will be added to the cache. -// return cluster.fetchSchema(ctx, req) -// }) -// +// var c *cache.Cache[BackfillSchemaRequest, *vtadminpb.Schema] +// c := cache.New(func(ctx context.Context, req BackfillSchemaRequest) (*vtadminpb.Schema, error) { +// // Fetch schema based on fields in `req`. +// // If err is nil, the backfilled schema will be added to the cache. +// return cluster.fetchSchema(ctx, req) +// }) type Cache[Key Keyer, Value any] struct { cache *cache.Cache diff --git a/go/vt/vtadmin/cluster/config.go b/go/vt/vtadmin/cluster/config.go index 5dcaf6b57bf..7cda15e8386 100644 --- a/go/vt/vtadmin/cluster/config.go +++ b/go/vt/vtadmin/cluster/config.go @@ -95,13 +95,13 @@ func (cfg *Config) Type() string { return "cluster.Config" } // Set is part of the flag.Value interface. Each flag is parsed according to the // following DSN: // -// id= // ID or shortname of the cluster. -// name= // Name of the cluster. -// discovery= // Name of the discovery implementation -// discovery-.*= // Per-discovery-implementation flags. These are passed to -// // a given discovery implementation's constructor. -// vtsql-.*= // VtSQL-specific flags. Further parsing of these is delegated -// // to the vtsql package. +// id= // ID or shortname of the cluster. +// name= // Name of the cluster. +// discovery= // Name of the discovery implementation +// discovery-.*= // Per-discovery-implementation flags. These are passed to +// // a given discovery implementation's constructor. +// vtsql-.*= // VtSQL-specific flags. Further parsing of these is delegated +// // to the vtsql package. func (cfg *Config) Set(value string) error { if cfg.DiscoveryFlagsByImpl == nil { cfg.DiscoveryFlagsByImpl = map[string]map[string]string{} diff --git a/go/vt/vtadmin/cluster/discovery/discovery_json.go b/go/vt/vtadmin/cluster/discovery/discovery_json.go index 36cbeab455e..3433fb4aece 100644 --- a/go/vt/vtadmin/cluster/discovery/discovery_json.go +++ b/go/vt/vtadmin/cluster/discovery/discovery_json.go @@ -36,15 +36,15 @@ import ( // As an example, here's a minimal JSON file for a single Vitess cluster running locally // (such as the one described in https://vitess.io/docs/get-started/local-docker): // -// { -// "vtgates": [ -// { -// "host": { -// "hostname": "127.0.0.1:15991" -// } -// } -// ] -// } +// { +// "vtgates": [ +// { +// "host": { +// "hostname": "127.0.0.1:15991" +// } +// } +// ] +// } // // For more examples of various static file configurations, see the unit tests. type JSONDiscovery struct { diff --git a/go/vt/vtadmin/cluster/discovery/discovery_static_file.go b/go/vt/vtadmin/cluster/discovery/discovery_static_file.go index a81acfd3b8b..62355f74a5e 100644 --- a/go/vt/vtadmin/cluster/discovery/discovery_static_file.go +++ b/go/vt/vtadmin/cluster/discovery/discovery_static_file.go @@ -31,15 +31,15 @@ import ( // As an example, here's a minimal JSON file for a single Vitess cluster running locally // (such as the one described in https://vitess.io/docs/get-started/local-docker): // -// { -// "vtgates": [ -// { -// "host": { -// "hostname": "127.0.0.1:15991" -// } -// } -// ] -// } +// { +// "vtgates": [ +// { +// "host": { +// "hostname": "127.0.0.1:15991" +// } +// } +// ] +// } // // For more examples of various static file configurations, see the unit tests. type StaticFileDiscovery struct { diff --git a/go/vt/vtadmin/cluster/dynamic/cluster.go b/go/vt/vtadmin/cluster/dynamic/cluster.go index a59706b2aa7..b1fee289b8c 100644 --- a/go/vt/vtadmin/cluster/dynamic/cluster.go +++ b/go/vt/vtadmin/cluster/dynamic/cluster.go @@ -20,16 +20,15 @@ import ( // // Therefore, callers should handle the return values as follows: // -// c, id, err := dynamic.ClusterFromString(ctx, s) -// if id == "" { -// // handle err, do not use `c`. -// } -// if err != nil { -// // log error. if desired, lookup the existing cluster with ID: `id` -// } -// // Use `c` (or existing cluster with ID == `id`) based on the dynamic cluster -// api.WithCluster(c, id).DoAThing() -// +// c, id, err := dynamic.ClusterFromString(ctx, s) +// if id == "" { +// // handle err, do not use `c`. +// } +// if err != nil { +// // log error. if desired, lookup the existing cluster with ID: `id` +// } +// // Use `c` (or existing cluster with ID == `id`) based on the dynamic cluster +// api.WithCluster(c, id).DoAThing() func ClusterFromString(ctx context.Context, s string) (c *cluster.Cluster, id string, err error) { cfg, id, err := cluster.LoadConfig(base64.NewDecoder(base64.StdEncoding, strings.NewReader(s)), "json") if err != nil { diff --git a/go/vt/vtadmin/cluster/file_config.go b/go/vt/vtadmin/cluster/file_config.go index 71fbdeb9150..279150afeea 100644 --- a/go/vt/vtadmin/cluster/file_config.go +++ b/go/vt/vtadmin/cluster/file_config.go @@ -28,15 +28,16 @@ import ( // permitted. // // A valid YAML config looks like: -// defaults: -// discovery: k8s -// clusters: -// clusterID1: -// name: clusterName1 -// discovery-k8s-some-flag: some-val -// clusterID2: -// name: clusterName2 -// discovery: consul +// +// defaults: +// discovery: k8s +// clusters: +// clusterID1: +// name: clusterName1 +// discovery-k8s-some-flag: some-val +// clusterID2: +// name: clusterName2 +// discovery: consul type FileConfig struct { Defaults Config Clusters map[string]Config diff --git a/go/vt/vtadmin/grpcserver/server.go b/go/vt/vtadmin/grpcserver/server.go index c7e58fb072c..87a7bd8eb35 100644 --- a/go/vt/vtadmin/grpcserver/server.go +++ b/go/vt/vtadmin/grpcserver/server.go @@ -100,8 +100,8 @@ type Server struct { // options. // // The underlying gRPC server always has the following interceptors: -// - prometheus -// - recovery: this handles recovering from panics. +// - prometheus +// - recovery: this handles recovering from panics. // // The full list of interceptors is as follows: // - (optional) interceptors defined on the Options struct diff --git a/go/vt/vtadmin/http/handlers/trace.go b/go/vt/vtadmin/http/handlers/trace.go index 6a652b87c9e..7896d1745da 100644 --- a/go/vt/vtadmin/http/handlers/trace.go +++ b/go/vt/vtadmin/http/handlers/trace.go @@ -32,12 +32,12 @@ import ( // the route_uri. To add additional spans, extract the span in your // VTAdminHTTPHandler like: // -// func Handler(ctx context.Context, r Request, api *API) *JSONResponse { -// span, _ := trace.FromContext(ctx) -// span.Annotate("foo", "bar") +// func Handler(ctx context.Context, r Request, api *API) *JSONResponse { +// span, _ := trace.FromContext(ctx) +// span.Annotate("foo", "bar") // -// return NewJSONResponse(api.Something(ctx)) -// } +// return NewJSONResponse(api.Something(ctx)) +// } // // An unnamed route will get a span named "vtadmin:http:". func TraceHandler(next http.Handler) http.Handler { diff --git a/go/vt/vtadmin/http/replication.go b/go/vt/vtadmin/http/replication.go index 3f45b9d0fc7..25436d493f4 100644 --- a/go/vt/vtadmin/http/replication.go +++ b/go/vt/vtadmin/http/replication.go @@ -24,9 +24,9 @@ import ( // GetShardReplicationPositions implements the http wrapper for /shard_replication_positions. // Query params: -// - cluster: repeated, cluster ID -// - keyspace: repeated, keyspace names -// - keyspace_shard: repeated, keyspace shard names +// - cluster: repeated, cluster ID +// - keyspace: repeated, keyspace names +// - keyspace_shard: repeated, keyspace shard names func GetShardReplicationPositions(ctx context.Context, r Request, api *API) *JSONResponse { query := r.URL.Query() diff --git a/go/vt/vtadmin/http/tablets.go b/go/vt/vtadmin/http/tablets.go index 4fedd3287ae..322092d8b97 100644 --- a/go/vt/vtadmin/http/tablets.go +++ b/go/vt/vtadmin/http/tablets.go @@ -108,8 +108,8 @@ func RefreshState(ctx context.Context, r Request, api *API) *JSONResponse { // PUT /tablet/{tablet}/refresh_replication_source. // // Query params: -// - cluster: repeatable, list of cluster IDs to restrict to when searching fo -// a tablet with that alias. +// - cluster: repeatable, list of cluster IDs to restrict to when searching fo +// a tablet with that alias. // // PUT body is unused; this endpoint takes no additional options. func RefreshTabletReplicationSource(ctx context.Context, r Request, api *API) *JSONResponse { diff --git a/go/vt/vtadmin/rbac/authorization.go b/go/vt/vtadmin/rbac/authorization.go index a33a28c4557..ab1592152ad 100644 --- a/go/vt/vtadmin/rbac/authorization.go +++ b/go/vt/vtadmin/rbac/authorization.go @@ -33,21 +33,21 @@ type Authorizer struct { // To get an authorizer that permits all access, including from unauthenticated // actors, provide the following: // -// authz, err := rbac.NewAuthorizer(&rbac.Config{ -// Rules: []*struct { -// Resource string -// Actions []string -// Subjects []string -// Clusters []string -// }{ -// { -// Resource: "*", -// Actions: []string{"*"}, -// Subjects: []string{"*"}, -// Clusters: []string{"*"}, -// }, -// }, -// }) +// authz, err := rbac.NewAuthorizer(&rbac.Config{ +// Rules: []*struct { +// Resource string +// Actions []string +// Subjects []string +// Clusters []string +// }{ +// { +// Resource: "*", +// Actions: []string{"*"}, +// Subjects: []string{"*"}, +// Clusters: []string{"*"}, +// }, +// }, +// }) func NewAuthorizer(cfg *Config) (*Authorizer, error) { if err := cfg.Reify(); err != nil { return nil, err diff --git a/go/vt/vtadmin/testutil/tablets.go b/go/vt/vtadmin/testutil/tablets.go index d4b6e60e024..9402a71847a 100644 --- a/go/vt/vtadmin/testutil/tablets.go +++ b/go/vt/vtadmin/testutil/tablets.go @@ -24,8 +24,7 @@ import ( // TopodataTabletsFromVTAdminTablets returns a slice of topodatapb.Tablet // objects from a slice of vtadminpb.Tablet objects. It is the equivalent of // -// map(func(t *vtadminpb.Tablet) (*topodatapb.Tablet) { return t.Tablet }, tablets) -// +// map(func(t *vtadminpb.Tablet) (*topodatapb.Tablet) { return t.Tablet }, tablets) func TopodataTabletsFromVTAdminTablets(tablets []*vtadminpb.Tablet) []*topodatapb.Tablet { results := make([]*topodatapb.Tablet, len(tablets)) diff --git a/go/vt/vtadmin/vtsql/fakevtsql/doc.go b/go/vt/vtadmin/vtsql/fakevtsql/doc.go index 904e60c5df7..d1d9ad1faca 100644 --- a/go/vt/vtadmin/vtsql/fakevtsql/doc.go +++ b/go/vt/vtadmin/vtsql/fakevtsql/doc.go @@ -20,31 +20,31 @@ limitations under the License. // To use fakevtsql, you will need to create a discovery implementation that // does not error, e.g. with fakediscovery: // -// disco := fakediscovery.New() -// disco.AddTaggedGates(nil, []*vtadminpb.VTGate{Hostname: "gate"}) +// disco := fakediscovery.New() +// disco.AddTaggedGates(nil, []*vtadminpb.VTGate{Hostname: "gate"}) // // Then, you will call vtsql.New(), passing the faked discovery implementation // into the config: // -// db := vtsql.New(&vtsql.Config{ -// Cluster: &vtadminpb.Cluster{Id: "cid", Name: "cluster"}, -// Discovery: disco, -// }) +// db := vtsql.New(&vtsql.Config{ +// Cluster: &vtadminpb.Cluster{Id: "cid", Name: "cluster"}, +// Discovery: disco, +// }) // // Finally, with your instantiated VTGateProxy instance, you can mock out the // DialFunc to always return a fakevtsql.Connector. The Tablets and ShouldErr // attributes of the connector control the behavior: // -// db.DialFunc = func(cfg vitessdriver.Configuration) (*sql.DB, error) { -// return sql.OpenDB(&fakevtsql.Connector{ -// Tablets: mockTablets, -// ShouldErr: shouldErr, -// }) -// } -// cluster := &cluster.Cluster{ -// /* other attributes */ -// DB: db, -// } +// db.DialFunc = func(cfg vitessdriver.Configuration) (*sql.DB, error) { +// return sql.OpenDB(&fakevtsql.Connector{ +// Tablets: mockTablets, +// ShouldErr: shouldErr, +// }) +// } +// cluster := &cluster.Cluster{ +// /* other attributes */ +// DB: db, +// } // // go/vt/vtadmin/api_test.go has several examples of usage. package fakevtsql diff --git a/go/vt/vtctl/grpcvtctldserver/testutil/test_tmclient.go b/go/vt/vtctl/grpcvtctldserver/testutil/test_tmclient.go index 925fd80fc72..6ea3ea04c27 100644 --- a/go/vt/vtctl/grpcvtctldserver/testutil/test_tmclient.go +++ b/go/vt/vtctl/grpcvtctldserver/testutil/test_tmclient.go @@ -81,10 +81,9 @@ var ( // vtctlservicepb.VtctldServer, tests will need to indirect that call through an // extra layer rather than passing the function identifier directly, e.g.: // -// vtctld := testutil.NewVtctldServerWithTabletManagerClient(t, ts, &testutil.TabletManagerClient{ -// ... -// }, func(ts *topo.Server) vtctlservicepb.VtctldServer { return NewVtctldServer(ts) }) -// +// vtctld := testutil.NewVtctldServerWithTabletManagerClient(t, ts, &testutil.TabletManagerClient{ +// ... +// }, func(ts *topo.Server) vtctlservicepb.VtctldServer { return NewVtctldServer(ts) }) func NewVtctldServerWithTabletManagerClient(t testing.TB, ts *topo.Server, tmc tmclient.TabletManagerClient, newVtctldServerFn func(ts *topo.Server) vtctlservicepb.VtctldServer) vtctlservicepb.VtctldServer { tmclientFactoryLock.Lock() defer tmclientFactoryLock.Unlock() diff --git a/go/vt/vtctl/internal/grpcshim/bidi_stream.go b/go/vt/vtctl/internal/grpcshim/bidi_stream.go index 0b7821e4bce..a620cb929aa 100644 --- a/go/vt/vtctl/internal/grpcshim/bidi_stream.go +++ b/go/vt/vtctl/internal/grpcshim/bidi_stream.go @@ -36,56 +36,55 @@ var ErrStreamClosed = errors.New("stream closed for sending") // parameterized Send/Recv methods typically called by gRPC streaming servers // and clients. For example, in the localvtctldclient: // -// type backupStreamAdapter struct { -// *grpcshim.BidiStream -// ch chan *vtctldatapb.BackupResponse -// } +// type backupStreamAdapter struct { +// *grpcshim.BidiStream +// ch chan *vtctldatapb.BackupResponse +// } // -// func (stream *backupStreamAdapter) Recv() (*vtctldatapb.BackupResponse, error) { -// select { -// case <-stream.Context().Done(): -// return nil, stream.Context().Err() -// case <-stream.Closed(): -// // Stream has been closed for future sends. If there are messages that -// // have already been sent, receive them until there are no more. After -// // all sent messages have been received, Recv will return the CloseErr. -// select { -// case msg := <-stream.ch: -// return msg, nil -// default: -// return nil, stream.CloseErr() -// } -// case err := <-stream.ErrCh: -// return nil, err -// case msg := <-stream.ch: -// return msg, nil -// } -// } +// func (stream *backupStreamAdapter) Recv() (*vtctldatapb.BackupResponse, error) { +// select { +// case <-stream.Context().Done(): +// return nil, stream.Context().Err() +// case <-stream.Closed(): +// // Stream has been closed for future sends. If there are messages that +// // have already been sent, receive them until there are no more. After +// // all sent messages have been received, Recv will return the CloseErr. +// select { +// case msg := <-stream.ch: +// return msg, nil +// default: +// return nil, stream.CloseErr() +// } +// case err := <-stream.ErrCh: +// return nil, err +// case msg := <-stream.ch: +// return msg, nil +// } +// } // -// func (stream *backupStreamAdapter) Send(msg *vtctldatapb.BackupResponse) error { -// select { -// case <-stream.Context().Done(): -// return stream.Context().Err() +// func (stream *backupStreamAdapter) Send(msg *vtctldatapb.BackupResponse) error { +// select { +// case <-stream.Context().Done(): +// return stream.Context().Err() // case <-stream.Closed(): // return grpcshim.ErrStreamClosed -// case stream.ch <- msg: -// return nil -// } -// } -// -// // Backup is part of the vtctlservicepb.VtctldClient interface. -// func (client *localVtctldClient) Backup(ctx context.Context, in *vtctldatapb.BackupRequest, opts ...grpc.CallOption) (vtctlservicepb.Vtctld_BackupClient, error) { -// stream := &backupStreamAdapter{ -// BidiStream: grpcshim.NewBidiStream(ctx), -// ch: make(chan *vtctldatapb.BackupResponse, 1), -// } -// go func() { -// err := client.s.Backup(in, stream) -// stream.CloseWithError(err) -// }() -// return stream, nil -// } +// case stream.ch <- msg: +// return nil +// } +// } // +// // Backup is part of the vtctlservicepb.VtctldClient interface. +// func (client *localVtctldClient) Backup(ctx context.Context, in *vtctldatapb.BackupRequest, opts ...grpc.CallOption) (vtctlservicepb.Vtctld_BackupClient, error) { +// stream := &backupStreamAdapter{ +// BidiStream: grpcshim.NewBidiStream(ctx), +// ch: make(chan *vtctldatapb.BackupResponse, 1), +// } +// go func() { +// err := client.s.Backup(in, stream) +// stream.CloseWithError(err) +// }() +// return stream, nil +// } type BidiStream struct { // ErrCh receives errors mid-stream, and should be selected on with the // same priority as stream.ch and stream/send contexts' cancellations in diff --git a/go/vt/vtctl/workflow/doc.go b/go/vt/vtctl/workflow/doc.go index c334470320f..c7ec7c50151 100644 --- a/go/vt/vtctl/workflow/doc.go +++ b/go/vt/vtctl/workflow/doc.go @@ -21,6 +21,7 @@ This is still a very rough sketch, far from a final API, but I want to document some things here as I go: (1) The lines between package workflow and package workflow/vexec are, uh, + blurry at best, and definitely need serious thinking and refinement. Maybe there shouldn't even be two separate packages at all. The reason I have the two packages right now is because I'm operating under the assumption that @@ -30,14 +31,18 @@ some things here as I go: but like I said, the boundaries are blurry, and things that belong in one package are in the other, because I haven't gone back and moved things around. + (2) I'm aiming for this to be a drop-in replacement (more or less) for the + function calls in go/vt/wrangler. However, I'd rather define a better abstraction if it means having to rewrite even significant portions of the existing wrangler code to adapt to it, than make a subpar API in the name of backwards compatibility. I'm not sure if that's a tradeoff I'll even need to consider in the future, but I'm putting a stake in the ground on which side of that tradeoff I intend to fall, should it come to it. + (3) Eventually we'll need to consider how the online schema migration workflows + fit into this. I'm trying to at least be somewhat abstract in the vexec / queryplanner APIs to fit with the QueryParams thing that wrangler uses, which _should_ work, but who knows?? Time will tell. diff --git a/go/vt/vtctl/workflow/vexec/query_planner.go b/go/vt/vtctl/workflow/vexec/query_planner.go index 770d7637bd4..59ade7a1031 100644 --- a/go/vt/vtctl/workflow/vexec/query_planner.go +++ b/go/vt/vtctl/workflow/vexec/query_planner.go @@ -142,7 +142,7 @@ func (planner *VReplicationQueryPlanner) PlanQuery(stmt sqlparser.Statement) (pl // respectively, and (b) db_name and workflow do not appear in the original // query's WHERE clause: // -// WHERE (db_name = {{ .DBName }} AND)? (workflow = {{ .Workflow }} AND)? {{ .OriginalWhere }} +// WHERE (db_name = {{ .DBName }} AND)? (workflow = {{ .Workflow }} AND)? {{ .OriginalWhere }} func (planner *VReplicationQueryPlanner) QueryParams() QueryParams { return QueryParams{ DBName: planner.dbname, diff --git a/go/vt/vterrors/stack.go b/go/vt/vterrors/stack.go index ba9264290da..83efe1b143d 100644 --- a/go/vt/vterrors/stack.go +++ b/go/vt/vterrors/stack.go @@ -57,15 +57,15 @@ func (f Frame) line() int { // Format formats the frame according to the fmt.Formatter interface. // -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d // // Format accepts flags that alter the printing of some verbs, as follows: // -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d +// %+s path of source file relative to the compile time GOPATH +// %+v equivalent to %+s:%d func (f Frame) Format(s fmt.State, verb rune) { switch verb { case 's': @@ -99,15 +99,15 @@ type StackTrace []Frame // Format format the stacktrace according to the fmt.Formatter interface. // -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d // // Format accepts flags that alter the printing of some verbs, as follows: // -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d +// %+s path of source file relative to the compile time GOPATH +// %+v equivalent to %+s:%d func (st StackTrace) Format(s fmt.State, verb rune) { switch verb { case 'v': diff --git a/go/vt/vterrors/vterrors.go b/go/vt/vterrors/vterrors.go index 69e436acb1d..3ddc18bc78b 100644 --- a/go/vt/vterrors/vterrors.go +++ b/go/vt/vterrors/vterrors.go @@ -20,7 +20,7 @@ limitations under the License. // and not fmt.Errorf(). This makes sure that stacktraces are kept and // propagated correctly. // -// New errors should be created using vterrors.New or vterrors.Errorf +// # New errors should be created using vterrors.New or vterrors.Errorf // // Vitess uses canonical error codes for error reporting. This is based // on years of industry experience with error reporting. This idea is @@ -41,7 +41,7 @@ limitations under the License. // using gRPC's error propagation mechanism and decoded back to // the original code on the other end. // -// Retrieving the cause of an error +// # Retrieving the cause of an error // // Using vterrors.Wrap constructs a stack of errors, adding context to the // preceding error, instead of simply building up a string. @@ -49,37 +49,38 @@ limitations under the License. // operation of errors.Wrap to retrieve the original error for inspection. // Any error value which implements this interface // -// type causer interface { -// Cause() error -// } +// type causer interface { +// Cause() error +// } // // can be inspected by vterrors.Cause and vterrors.RootCause. // -// * vterrors.Cause will find the immediate cause if one is available, or nil -// if the error is not a `causer` or if no cause is available. -// * vterrors.RootCause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be -// the original cause. For example: +// - vterrors.Cause will find the immediate cause if one is available, or nil +// if the error is not a `causer` or if no cause is available. +// +// - vterrors.RootCause will recursively retrieve +// the topmost error which does not implement causer, which is assumed to be +// the original cause. For example: // // switch err := errors.RootCause(err).(type) { // case *MyError: -// // handle specifically +// // handle specifically // default: -// // unknown error +// // unknown error // } // // causer interface is not exported by this package, but is considered a part // of stable public API. // -// Formatted printing of errors +// # Formatted printing of errors // // All error values returned from this package implement fmt.Formatter and can // be formatted by the fmt package. The following verbs are supported // -// %s print the error. If the error has a Cause it will be -// printed recursively -// %v extended format. Each Frame of the error's StackTrace will -// be printed in detail. +// %s print the error. If the error has a Cause it will be +// printed recursively +// %v extended format. Each Frame of the error's StackTrace will +// be printed in detail. // // Most but not all of the code in this file was originally copied from // https://github.com/pkg/errors/blob/v0.8.0/errors.go @@ -269,9 +270,9 @@ func panicIfError(_ int, err error) { // An error value has a cause if it implements the following // interface: // -// type causer interface { -// Cause() error -// } +// type causer interface { +// Cause() error +// } // // If the error does not implement Cause, the original error will // be returned. If the error is nil, nil will be returned without further @@ -286,14 +287,14 @@ func RootCause(err error) error { } } -// // Cause will return the immediate cause, if possible. // An error value has a cause if it implements the following // interface: // -// type causer interface { -// Cause() error -// } +// type causer interface { +// Cause() error +// } +// // If the error does not implement Cause, nil will be returned func Cause(err error) error { type causer interface { diff --git a/go/vt/vtgate/engine/lock.go b/go/vt/vtgate/engine/lock.go index cd77c053a63..cc01ba42b8d 100644 --- a/go/vt/vtgate/engine/lock.go +++ b/go/vt/vtgate/engine/lock.go @@ -35,7 +35,7 @@ import ( var _ Primitive = (*Lock)(nil) -//Lock primitive will execute sql containing lock functions +// Lock primitive will execute sql containing lock functions type Lock struct { // Keyspace specifies the keyspace to send the query to. Keyspace *vindexes.Keyspace diff --git a/go/vt/vtgate/engine/online_ddl.go b/go/vt/vtgate/engine/online_ddl.go index 7668e877772..6dd4d7c0183 100644 --- a/go/vt/vtgate/engine/online_ddl.go +++ b/go/vt/vtgate/engine/online_ddl.go @@ -116,7 +116,7 @@ func (v *OnlineDDL) TryStreamExecute(vcursor VCursor, bindVars map[string]*query return callback(results) } -//GetFields implements the Primitive interface +// GetFields implements the Primitive interface func (v *OnlineDDL) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) { return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] GetFields is not reachable") } diff --git a/go/vt/vtgate/engine/revert_migration.go b/go/vt/vtgate/engine/revert_migration.go index 6ceb11df138..6237e313217 100644 --- a/go/vt/vtgate/engine/revert_migration.go +++ b/go/vt/vtgate/engine/revert_migration.go @@ -118,7 +118,7 @@ func (v *RevertMigration) TryStreamExecute(vcursor VCursor, bindVars map[string] return callback(results) } -//GetFields implements the Primitive interface +// GetFields implements the Primitive interface func (v *RevertMigration) GetFields(vcursor VCursor, bindVars map[string]*query.BindVariable) (*sqltypes.Result, error) { return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] GetFields is not reachable") } diff --git a/go/vt/vtgate/engine/send.go b/go/vt/vtgate/engine/send.go index ae50af9d1cd..dec5f7bbb95 100644 --- a/go/vt/vtgate/engine/send.go +++ b/go/vt/vtgate/engine/send.go @@ -58,7 +58,7 @@ type Send struct { // ShardName as key for setting shard name in bind variables map const ShardName = "__vt_shard" -//NeedsTransaction implements the Primitive interface +// NeedsTransaction implements the Primitive interface func (s *Send) NeedsTransaction() bool { return s.IsDML } diff --git a/go/vt/vtgate/engine/vschema_ddl.go b/go/vt/vtgate/engine/vschema_ddl.go index 82747487a6c..3f32600e17e 100644 --- a/go/vt/vtgate/engine/vschema_ddl.go +++ b/go/vt/vtgate/engine/vschema_ddl.go @@ -27,7 +27,7 @@ import ( var _ Primitive = (*AlterVSchema)(nil) -//AlterVSchema operator applies changes to VSchema +// AlterVSchema operator applies changes to VSchema type AlterVSchema struct { Keyspace *vindexes.Keyspace diff --git a/go/vt/vtgate/evalengine/comparisons.go b/go/vt/vtgate/evalengine/comparisons.go index 4dc98974d0e..20abd2ca729 100644 --- a/go/vt/vtgate/evalengine/comparisons.go +++ b/go/vt/vtgate/evalengine/comparisons.go @@ -200,7 +200,7 @@ func evalCompareAll(lVal, rVal *EvalResult, fulleq bool) (int, bool, error) { } // For more details on comparison expression evaluation and type conversion: -// - https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html +// - https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html func evalCompare(lVal, rVal *EvalResult) (comp int, err error) { switch { case evalResultsAreStrings(lVal, rVal): diff --git a/go/vt/vtgate/evalengine/evalengine.go b/go/vt/vtgate/evalengine/evalengine.go index 36405dcddb3..8fe3a01c423 100644 --- a/go/vt/vtgate/evalengine/evalengine.go +++ b/go/vt/vtgate/evalengine/evalengine.go @@ -263,8 +263,8 @@ func matchExprWithAnyDateFormat(expr *EvalResult) (t time.Time, err error) { } // Date comparison based on: -// - https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html -// - https://dev.mysql.com/doc/refman/8.0/en/date-and-time-type-conversion.html +// - https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html +// - https://dev.mysql.com/doc/refman/8.0/en/date-and-time-type-conversion.html func compareDates(l, r *EvalResult) (int, error) { lTime, err := parseDate(l) if err != nil { @@ -315,7 +315,7 @@ func compareGoTimes(lTime, rTime time.Time) (int, error) { } // More on string collations coercibility on MySQL documentation: -// - https://dev.mysql.com/doc/refman/8.0/en/charset-collation-coercibility.html +// - https://dev.mysql.com/doc/refman/8.0/en/charset-collation-coercibility.html func compareStrings(l, r *EvalResult) int { coll, err := mergeCollations(l, r) if err != nil { diff --git a/go/vt/vtgate/evalengine/integration/comparison_test.go b/go/vt/vtgate/evalengine/integration/comparison_test.go index f3c805a4090..b65e7c3586f 100644 --- a/go/vt/vtgate/evalengine/integration/comparison_test.go +++ b/go/vt/vtgate/evalengine/integration/comparison_test.go @@ -641,16 +641,20 @@ func TestCaseExprWithPredicate(t *testing.T) { } // HACK: for CASE comparisons, the expression is supposed to decompose like this: -// CASE a WHEN b THEN bb WHEN c THEN cc ELSE d -// => CASE WHEN a = b THEN bb WHEN a == c THEN cc ELSE d +// +// CASE a WHEN b THEN bb WHEN c THEN cc ELSE d +// => CASE WHEN a = b THEN bb WHEN a == c THEN cc ELSE d +// // See: https://dev.mysql.com/doc/refman/5.7/en/flow-control-functions.html#operator_case // However, MySQL does not seem to be using the real `=` operator for some of these comparisons // namely, numerical comparisons are coerced into an unsigned form when they shouldn't. // Example: -// SELECT -1 = 18446744073709551615 -// => 0 -// SELECT -1 WHEN 18446744073709551615 THEN 1 ELSE 0 END -// => 1 +// +// SELECT -1 = 18446744073709551615 +// => 0 +// SELECT -1 WHEN 18446744073709551615 THEN 1 ELSE 0 END +// => 1 +// // This does not happen for other types, which all follow the behavior of the `=` operator, // so we're going to assume this is a bug for now. func comparisonSkip(a, b string) bool { diff --git a/go/vt/vtgate/evalengine/internal/decimal/decimal.go b/go/vt/vtgate/evalengine/internal/decimal/decimal.go index ee74f0b074b..7cf1c6f277b 100644 --- a/go/vt/vtgate/evalengine/internal/decimal/decimal.go +++ b/go/vt/vtgate/evalengine/internal/decimal/decimal.go @@ -53,16 +53,15 @@ func myBigDigits(digits int32) int32 { // // Example: // -// d1 := decimal.NewFromFloat(2).div(decimal.NewFromFloat(3)) -// d1.String() // output: "0.6666666666666667" -// d2 := decimal.NewFromFloat(2).div(decimal.NewFromFloat(30000)) -// d2.String() // output: "0.0000666666666667" -// d3 := decimal.NewFromFloat(20000).div(decimal.NewFromFloat(3)) -// d3.String() // output: "6666.6666666666666667" -// decimal.divisionPrecision = 3 -// d4 := decimal.NewFromFloat(2).div(decimal.NewFromFloat(3)) -// d4.String() // output: "0.667" -// +// d1 := decimal.NewFromFloat(2).div(decimal.NewFromFloat(3)) +// d1.String() // output: "0.6666666666666667" +// d2 := decimal.NewFromFloat(2).div(decimal.NewFromFloat(30000)) +// d2.String() // output: "0.0000666666666667" +// d3 := decimal.NewFromFloat(20000).div(decimal.NewFromFloat(3)) +// d3.String() // output: "6666.6666666666666667" +// decimal.divisionPrecision = 3 +// d4 := decimal.NewFromFloat(2).div(decimal.NewFromFloat(3)) +// d4.String() // output: "0.667" var divisionPrecision = 16 // Zero constant, to make computations faster. @@ -147,8 +146,8 @@ func New(value int64, exp int32) Decimal { // // Example: // -// NewFromInt(123).String() // output: "123" -// NewFromInt(-10).String() // output: "-10" +// NewFromInt(123).String() // output: "123" +// NewFromInt(-10).String() // output: "-10" func NewFromInt(value int64) Decimal { return Decimal{ value: big.NewInt(value), @@ -236,7 +235,7 @@ func bigPow10(n uint64) *big.Int { // // Example: // -// d := New(12345, -4) +// d := New(12345, -4) // d2 := d.rescale(-1) // d3 := d2.rescale(-4) // println(d1) @@ -248,7 +247,6 @@ func bigPow10(n uint64) *big.Int { // 1.2345 // 1.2 // 1.2000 -// func (d Decimal) rescale(exp int32) Decimal { d.ensureInitialized() @@ -376,9 +374,11 @@ func (d Decimal) div(d2 Decimal) Decimal { // quoRem does division with remainder // d.quoRem(d2,precision) returns quotient q and remainder r such that -// d = d2 * q + r, q an integer multiple of 10^(-precision) -// 0 <= r < abs(d2) * 10 ^(-precision) if d>=0 -// 0 >= r > -abs(d2) * 10 ^(-precision) if d<0 +// +// d = d2 * q + r, q an integer multiple of 10^(-precision) +// 0 <= r < abs(d2) * 10 ^(-precision) if d>=0 +// 0 >= r > -abs(d2) * 10 ^(-precision) if d<0 +// // Note that precision<0 is allowed as input. func (d Decimal) quoRem(d2 Decimal, precision int32) (Decimal, Decimal) { d.ensureInitialized() @@ -421,8 +421,10 @@ func (d Decimal) quoRem(d2 Decimal, precision int32) (Decimal, Decimal) { // divRound divides and rounds to a given precision // i.e. to an integer multiple of 10^(-precision) -// for a positive quotient digit 5 is rounded up, away from 0 -// if the quotient is negative then digit 5 is rounded down, away from 0 +// +// for a positive quotient digit 5 is rounded up, away from 0 +// if the quotient is negative then digit 5 is rounded down, away from 0 +// // Note that precision<0 is allowed as input. func (d Decimal) divRound(d2 Decimal, precision int32) Decimal { // quoRem already checks initialization @@ -492,10 +494,9 @@ func abs(n int32) int32 { // Cmp compares the numbers represented by d and d2 and returns: // -// -1 if d < d2 -// 0 if d == d2 -// +1 if d > d2 -// +// -1 if d < d2 +// 0 if d == d2 +// +1 if d > d2 func (d Decimal) Cmp(d2 Decimal) int { d.ensureInitialized() d2.ensureInitialized() @@ -526,7 +527,6 @@ func (d Decimal) Equal(d2 Decimal) bool { // -1 if d < 0 // 0 if d == 0 // +1 if d > 0 -// func (d Decimal) Sign() int { if d.value == nil { return 0 @@ -571,13 +571,12 @@ func (d Decimal) Float64() (f float64, ok bool) { // // Example: // -// d := New(-12345, -3) -// println(d.String()) +// d := New(-12345, -3) +// println(d.String()) // // Output: // -// -12.345 -// +// -12.345 func (d Decimal) String() string { return string(d.formatFast(0, false, true)) } @@ -587,14 +586,13 @@ func (d Decimal) String() string { // // Example: // -// NewFromFloat(0).StringFixed(2) // output: "0.00" -// NewFromFloat(0).StringFixed(0) // output: "0" -// NewFromFloat(5.45).StringFixed(0) // output: "5" -// NewFromFloat(5.45).StringFixed(1) // output: "5.5" -// NewFromFloat(5.45).StringFixed(2) // output: "5.45" -// NewFromFloat(5.45).StringFixed(3) // output: "5.450" -// NewFromFloat(545).StringFixed(-1) // output: "550" -// +// NewFromFloat(0).StringFixed(2) // output: "0.00" +// NewFromFloat(0).StringFixed(0) // output: "0" +// NewFromFloat(5.45).StringFixed(0) // output: "5" +// NewFromFloat(5.45).StringFixed(1) // output: "5.5" +// NewFromFloat(5.45).StringFixed(2) // output: "5.45" +// NewFromFloat(5.45).StringFixed(3) // output: "5.450" +// NewFromFloat(545).StringFixed(-1) // output: "550" func (d Decimal) StringFixed(places int32) string { // The StringFixed method allows for negative precision, which // MySQL doesn't support, so we cannot round this using the string @@ -616,9 +614,8 @@ func (d Decimal) FormatMySQL(frac int32) []byte { // // Example: // -// NewFromFloat(5.45).Round(1).String() // output: "5.5" -// NewFromFloat(545).Round(-1).String() // output: "550" -// +// NewFromFloat(5.45).Round(1).String() // output: "5.5" +// NewFromFloat(545).Round(-1).String() // output: "550" func (d Decimal) Round(places int32) Decimal { if d.exp == -places { return d @@ -675,9 +672,10 @@ func min(x, y int32) int32 { // largestForm returns the largest decimal that can be represented // with the given amount of integral and fractional digits // Example: -// largestForm(1, 1) => 9.9 -// largestForm(5, 0) => 99999 -// largestForm(0, 5) => 0.99999 +// +// largestForm(1, 1) => 9.9 +// largestForm(5, 0) => 99999 +// largestForm(0, 5) => 0.99999 func largestForm(integral, fractional int32, neg bool) Decimal { // nines is just a very long string of nines; to find the // largest form of a large decimal, we parse as many nines diff --git a/go/vt/vtgate/evalengine/internal/decimal/scan.go b/go/vt/vtgate/evalengine/internal/decimal/scan.go index f3288f4e77c..27144298972 100644 --- a/go/vt/vtgate/evalengine/internal/decimal/scan.go +++ b/go/vt/vtgate/evalengine/internal/decimal/scan.go @@ -143,10 +143,9 @@ func NewFromMySQL(s []byte) (Decimal, error) { // // Example: // -// d, err := NewFromString("-123.45") -// d2, err := NewFromString(".0001") -// d3, err := NewFromString("1.47000") -// +// d, err := NewFromString("-123.45") +// d2, err := NewFromString(".0001") +// d3, err := NewFromString("1.47000") func NewFromString(value string) (Decimal, error) { originalInput := value var intString string @@ -223,9 +222,8 @@ func NewFromString(value string) (Decimal, error) { // // Example: // -// d := RequireFromString("-123.45") -// d2 := RequireFromString(".0001") -// +// d := RequireFromString("-123.45") +// d2 := RequireFromString(".0001") func RequireFromString(value string) Decimal { dec, err := NewFromString(value) if err != nil { diff --git a/go/vt/vtgate/executor_vschema_ddl_test.go b/go/vt/vtgate/executor_vschema_ddl_test.go index 3b41d7c7c78..4c3f4ef24c8 100644 --- a/go/vt/vtgate/executor_vschema_ddl_test.go +++ b/go/vt/vtgate/executor_vschema_ddl_test.go @@ -96,7 +96,7 @@ func waitForVschemaTables(t *testing.T, ks string, tables []string, executor *Ex return nil } -//nolint +// nolint func waitForColVindexes(t *testing.T, ks, table string, names []string, executor *Executor) *vschemapb.SrvVSchema { t.Helper() diff --git a/go/vt/vtgate/grpcvtgateservice/no_test.go b/go/vt/vtgate/grpcvtgateservice/no_test.go index 6500ae8ae93..8475812d756 100644 --- a/go/vt/vtgate/grpcvtgateservice/no_test.go +++ b/go/vt/vtgate/grpcvtgateservice/no_test.go @@ -24,9 +24,13 @@ import ( // is to document this fact. In order to make sure all code paths are // covered, you need to run the coverage tool from the ../grpcvtgatesconn directory // using the following command: +// // go test -coverprofile=c.out -coverpkg ../grpcvtgateservice,. +// // You can then follow it with: +// // go tool cover -html=c.out -o=c.html +// // to see the html output. func TestNothing(t *testing.T) { } diff --git a/go/vt/vtgate/planbuilder/ordered_aggregate.go b/go/vt/vtgate/planbuilder/ordered_aggregate.go index c7380cc16f3..6e5223642b3 100644 --- a/go/vt/vtgate/planbuilder/ordered_aggregate.go +++ b/go/vt/vtgate/planbuilder/ordered_aggregate.go @@ -44,22 +44,23 @@ var _ logicalPlan = (*orderedAggregate)(nil) // will be sent to the scatter route as: // 'select col1, col2, count(*) from t group by col1, col2 order by col1, col2` // The orderAggregate primitive built for this will be: -// &engine.OrderedAggregate { -// // Aggregates has one column. It computes the count -// // using column 2 of the underlying route. -// Aggregates: []AggregateParams{{ -// Opcode: AggregateCount, -// Col: 2, -// }}, // -// // Keys has the two group by values for col1 and col2. -// // The column numbers are from the underlying route. -// // These values will be used to perform the grouping -// // of the ordered results as they come from the underlying -// // route. -// Keys: []int{0, 1}, -// Input: (Scatter Route with the order by request), -// } +// &engine.OrderedAggregate { +// // Aggregates has one column. It computes the count +// // using column 2 of the underlying route. +// Aggregates: []AggregateParams{{ +// Opcode: AggregateCount, +// Col: 2, +// }}, +// +// // Keys has the two group by values for col1 and col2. +// // The column numbers are from the underlying route. +// // These values will be used to perform the grouping +// // of the ordered results as they come from the underlying +// // route. +// Keys: []int{0, 1}, +// Input: (Scatter Route with the order by request), +// } type orderedAggregate struct { resultsBuilder extraDistinct *sqlparser.ColName diff --git a/go/vt/vtgate/planbuilder/sql_calc_found_rows.go b/go/vt/vtgate/planbuilder/sql_calc_found_rows.go index 65dbcb172bc..7d7cdc87d0f 100644 --- a/go/vt/vtgate/planbuilder/sql_calc_found_rows.go +++ b/go/vt/vtgate/planbuilder/sql_calc_found_rows.go @@ -56,7 +56,7 @@ func (s *sqlCalcFoundRows) ContainsTables() semantics.TableSet { return s.LimitQuery.ContainsTables() } -//Primitive implements the logicalPlan interface +// Primitive implements the logicalPlan interface func (s *sqlCalcFoundRows) Primitive() engine.Primitive { countPrim := s.CountQuery.Primitive() rb, ok := countPrim.(*engine.Route) diff --git a/go/vt/vtgate/vindexes/cfc.go b/go/vt/vtgate/vindexes/cfc.go index f7f9953e06d..cb30d30d49e 100644 --- a/go/vt/vtgate/vindexes/cfc.go +++ b/go/vt/vtgate/vindexes/cfc.go @@ -68,17 +68,17 @@ import ( // the behavior is exactly same as other vindex's but just more efficient in // controlling the fanout. // -// The expected format of the vindex definition is +// # The expected format of the vindex definition is // -// "vindexes": { -// "cfc_md5": { -// "type": "cfc", -// "params": { -// "hash": "md5", -// "offsets": "[2,4]" -// } -// } -// } +// "vindexes": { +// "cfc_md5": { +// "type": "cfc", +// "params": { +// "hash": "md5", +// "offsets": "[2,4]" +// } +// } +// } // // 'offsets' only makes sense when hash is used. Offsets should be a sorted // list of positive ints, each of which denotes the byte offset (from the diff --git a/go/vt/vtgate/vindexes/consistent_lookup.go b/go/vt/vtgate/vindexes/consistent_lookup.go index 3706b78e69a..36bcae46000 100644 --- a/go/vt/vtgate/vindexes/consistent_lookup.go +++ b/go/vt/vtgate/vindexes/consistent_lookup.go @@ -56,9 +56,10 @@ type ConsistentLookup struct { // NewConsistentLookup creates a ConsistentLookup vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. func NewConsistentLookup(name string, m map[string]string) (Vindex, error) { clc, err := newCLCommon(name, m) if err != nil { @@ -133,9 +134,10 @@ type ConsistentLookupUnique struct { // NewConsistentLookupUnique creates a ConsistentLookupUnique vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. func NewConsistentLookupUnique(name string, m map[string]string) (Vindex, error) { clc, err := newCLCommon(name, m) if err != nil { diff --git a/go/vt/vtgate/vindexes/lookup.go b/go/vt/vtgate/vindexes/lookup.go index 081b9a9aab7..1865cf1cc7a 100644 --- a/go/vt/vtgate/vindexes/lookup.go +++ b/go/vt/vtgate/vindexes/lookup.go @@ -140,13 +140,15 @@ func (ln *LookupNonUnique) MarshalJSON() ([]byte, error) { // NewLookup creates a LookupNonUnique vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. // // The following fields are optional: -// autocommit: setting this to "true" will cause inserts to upsert and deletes to be ignored. -// write_only: in this mode, Map functions return the full keyrange causing a full scatter. +// +// autocommit: setting this to "true" will cause inserts to upsert and deletes to be ignored. +// write_only: in this mode, Map functions return the full keyrange causing a full scatter. func NewLookup(name string, m map[string]string) (Vindex, error) { lookup := &LookupNonUnique{name: name} @@ -187,13 +189,15 @@ type LookupUnique struct { // NewLookupUnique creates a LookupUnique vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. // // The following fields are optional: -// autocommit: setting this to "true" will cause deletes to be ignored. -// write_only: in this mode, Map functions return the full keyrange causing a full scatter. +// +// autocommit: setting this to "true" will cause deletes to be ignored. +// write_only: in this mode, Map functions return the full keyrange causing a full scatter. func NewLookupUnique(name string, m map[string]string) (Vindex, error) { lu := &LookupUnique{name: name} diff --git a/go/vt/vtgate/vindexes/lookup_hash.go b/go/vt/vtgate/vindexes/lookup_hash.go index df34f841122..e7534d9c0de 100644 --- a/go/vt/vtgate/vindexes/lookup_hash.go +++ b/go/vt/vtgate/vindexes/lookup_hash.go @@ -54,13 +54,15 @@ type LookupHash struct { // NewLookupHash creates a LookupHash vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. // // The following fields are optional: -// autocommit: setting this to "true" will cause inserts to upsert and deletes to be ignored. -// write_only: in this mode, Map functions return the full keyrange causing a full scatter. +// +// autocommit: setting this to "true" will cause inserts to upsert and deletes to be ignored. +// write_only: in this mode, Map functions return the full keyrange causing a full scatter. func NewLookupHash(name string, m map[string]string) (Vindex, error) { lh := &LookupHash{name: name} @@ -218,13 +220,15 @@ type LookupHashUnique struct { // NewLookupHashUnique creates a LookupHashUnique vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. // // The following fields are optional: -// autocommit: setting this to "true" will cause deletes to be ignored. -// write_only: in this mode, Map functions return the full keyrange causing a full scatter. +// +// autocommit: setting this to "true" will cause deletes to be ignored. +// write_only: in this mode, Map functions return the full keyrange causing a full scatter. func NewLookupHashUnique(name string, m map[string]string) (Vindex, error) { lhu := &LookupHashUnique{name: name} diff --git a/go/vt/vtgate/vindexes/lookup_unicodeloosemd5_hash.go b/go/vt/vtgate/vindexes/lookup_unicodeloosemd5_hash.go index 66a8c343799..e9c38d47b58 100644 --- a/go/vt/vtgate/vindexes/lookup_unicodeloosemd5_hash.go +++ b/go/vt/vtgate/vindexes/lookup_unicodeloosemd5_hash.go @@ -55,13 +55,15 @@ type LookupUnicodeLooseMD5Hash struct { // NewLookupUnicodeLooseMD5Hash creates a LookupUnicodeLooseMD5Hash vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. // // The following fields are optional: -// autocommit: setting this to "true" will cause inserts to upsert and deletes to be ignored. -// write_only: in this mode, Map functions return the full keyrange causing a full scatter. +// +// autocommit: setting this to "true" will cause inserts to upsert and deletes to be ignored. +// write_only: in this mode, Map functions return the full keyrange causing a full scatter. func NewLookupUnicodeLooseMD5Hash(name string, m map[string]string) (Vindex, error) { lh := &LookupUnicodeLooseMD5Hash{name: name} @@ -230,13 +232,15 @@ type LookupUnicodeLooseMD5HashUnique struct { // NewLookupUnicodeLooseMD5HashUnique creates a LookupUnicodeLooseMD5HashUnique vindex. // The supplied map has the following required fields: -// table: name of the backing table. It can be qualified by the keyspace. -// from: list of columns in the table that have the 'from' values of the lookup vindex. -// to: The 'to' column name of the table. +// +// table: name of the backing table. It can be qualified by the keyspace. +// from: list of columns in the table that have the 'from' values of the lookup vindex. +// to: The 'to' column name of the table. // // The following fields are optional: -// autocommit: setting this to "true" will cause deletes to be ignored. -// write_only: in this mode, Map functions return the full keyrange causing a full scatter. +// +// autocommit: setting this to "true" will cause deletes to be ignored. +// write_only: in this mode, Map functions return the full keyrange causing a full scatter. func NewLookupUnicodeLooseMD5HashUnique(name string, m map[string]string) (Vindex, error) { lhu := &LookupUnicodeLooseMD5HashUnique{name: name} diff --git a/go/vt/vttablet/grpctmclient/cached_client.go b/go/vt/vttablet/grpctmclient/cached_client.go index 59861796216..9b92b56a504 100644 --- a/go/vt/vttablet/grpctmclient/cached_client.go +++ b/go/vt/vttablet/grpctmclient/cached_client.go @@ -182,18 +182,18 @@ func (dialer *cachedConnDialer) tryFromCache(addr string, locker sync.Locker) (c } // pollOnce is called on each iteration of the polling loop in dial(). It: -// - locks the conns cache for writes -// - attempts to get a connection from the cache. If found, redial() it and exit. -// - peeks at the head of the eviction queue. if the peeked conn has no refs, it -// is unused, and can be evicted to make room for the new connection to addr. -// If the peeked conn has refs, exit. -// - pops the conn we just peeked from the queue, deletes it from the cache, and -// close the underlying ClientConn for that conn. -// - attempt a newdial. if the newdial fails, it will release a slot on the -// connWaitSema, so another dial() call can successfully acquire it to dial -// a new conn. if the newdial succeeds, we will have evicted one conn, but -// added another, so the net change is 0, and no changes to the connWaitSema -// are made. +// - locks the conns cache for writes +// - attempts to get a connection from the cache. If found, redial() it and exit. +// - peeks at the head of the eviction queue. if the peeked conn has no refs, it +// is unused, and can be evicted to make room for the new connection to addr. +// If the peeked conn has refs, exit. +// - pops the conn we just peeked from the queue, deletes it from the cache, and +// close the underlying ClientConn for that conn. +// - attempt a newdial. if the newdial fails, it will release a slot on the +// connWaitSema, so another dial() call can successfully acquire it to dial +// a new conn. if the newdial succeeds, we will have evicted one conn, but +// added another, so the net change is 0, and no changes to the connWaitSema +// are made. // // It returns a TabletManagerClient impl, an io.Closer, a flag to indicate // whether the dial() poll loop should exit, and an error. diff --git a/go/vt/vttablet/grpctmclient/client.go b/go/vt/vttablet/grpctmclient/client.go index aef914df74d..512eb035e64 100644 --- a/go/vt/vttablet/grpctmclient/client.go +++ b/go/vt/vttablet/grpctmclient/client.go @@ -97,7 +97,9 @@ type poolDialer interface { // // In order to more efficiently use the underlying tcp connections, you can // instead use the cachedConnDialer implementation by specifying -// -tablet_manager_protocol "grpc-cached" +// +// -tablet_manager_protocol "grpc-cached" +// // The cachedConnDialer keeps connections to up to -tablet_manager_grpc_connpool_size distinct // tablets open at any given time, for faster per-RPC call time, and less // connection churn. @@ -995,9 +997,7 @@ func (client *Client) PromoteReplica(ctx context.Context, tablet *topodatapb.Tab return response.Position, nil } -// // Backup related methods -// type backupStreamAdapter struct { stream tabletmanagerservicepb.TabletManager_BackupClient closer io.Closer diff --git a/go/vt/vttablet/onlineddl/vrepl/unique_key.go b/go/vt/vttablet/onlineddl/vrepl/unique_key.go index 1fbc9cc9a4e..c24ea7710c1 100644 --- a/go/vt/vttablet/onlineddl/vrepl/unique_key.go +++ b/go/vt/vttablet/onlineddl/vrepl/unique_key.go @@ -130,8 +130,10 @@ func SourceUniqueKeyAsOrMoreConstrainedThanTarget(sourceUniqueKey, targetUniqueK // AddedUniqueKeys returns the unique key constraints added in target. This does not necessarily mean that the unique key itself is new, // rather that there's a new, stricter constraint on a set of columns, that didn't exist before. Example: -// before: unique key `my_key`(c1, c2, c3); after: unique key `my_key`(c1, c2) -// The constraint on (c1, c2) is new; and `my_key` in target table ("after") is considered a new key +// +// before: unique key `my_key`(c1, c2, c3); after: unique key `my_key`(c1, c2) +// The constraint on (c1, c2) is new; and `my_key` in target table ("after") is considered a new key +// // Order of columns is immaterial to uniqueness of column combination. func AddedUniqueKeys(sourceUniqueKeys, targetUniqueKeys [](*UniqueKey), columnRenameMap map[string]string) (addedUKs [](*UniqueKey)) { addedUKs = [](*UniqueKey){} diff --git a/go/vt/vttablet/sandboxconn/sandboxconn.go b/go/vt/vttablet/sandboxconn/sandboxconn.go index 8ed2ed5e31f..5a158f5596e 100644 --- a/go/vt/vttablet/sandboxconn/sandboxconn.go +++ b/go/vt/vttablet/sandboxconn/sandboxconn.go @@ -632,7 +632,7 @@ func (sbc *SandboxConn) getTxReservedID(txID int64) int64 { return sbc.txIDToRID[txID] } -//StringQueries returns the queries executed as a slice of strings +// StringQueries returns the queries executed as a slice of strings func (sbc *SandboxConn) StringQueries() []string { result := make([]string, len(sbc.Queries)) for i, query := range sbc.Queries { diff --git a/go/vt/vttablet/tabletmanager/rpc_replication.go b/go/vt/vttablet/tabletmanager/rpc_replication.go index 7f15a3cf26e..18c1ae56266 100644 --- a/go/vt/vttablet/tabletmanager/rpc_replication.go +++ b/go/vt/vttablet/tabletmanager/rpc_replication.go @@ -476,10 +476,10 @@ func (tm *TabletManager) InitReplica(ctx context.Context, parent *topodatapb.Tab // // It attemps to idempotently ensure the following guarantees upon returning // successfully: -// * No future writes will be accepted. -// * No writes are in-flight. -// * MySQL is in read-only mode. -// * Semi-sync settings are consistent with a REPLICA tablet. +// - No future writes will be accepted. +// - No writes are in-flight. +// - MySQL is in read-only mode. +// - Semi-sync settings are consistent with a REPLICA tablet. // // If necessary, it waits for all in-flight writes to complete or time out. // diff --git a/go/vt/vttablet/tabletmanager/rpc_server.go b/go/vt/vttablet/tabletmanager/rpc_server.go index ff5e7f90db0..ffd30d299a4 100644 --- a/go/vt/vttablet/tabletmanager/rpc_server.go +++ b/go/vt/vttablet/tabletmanager/rpc_server.go @@ -85,7 +85,6 @@ func (tm *TabletManager) HandleRPCPanic(ctx context.Context, name string, args, } } -// // RegisterTabletManager is used to delay registration of RPC servers until we have all the objects. type RegisterTabletManager func(*TabletManager) diff --git a/go/vt/vttablet/tabletmanager/tm_state_test.go b/go/vt/vttablet/tabletmanager/tm_state_test.go index 231c356c8db..2fae382d12c 100644 --- a/go/vt/vttablet/tabletmanager/tm_state_test.go +++ b/go/vt/vttablet/tabletmanager/tm_state_test.go @@ -383,7 +383,9 @@ func TestStateChangeTabletType(t *testing.T) { assert.Equal(t, int64(2), statsTabletTypeCount.Counts()["replica"]) } -/* This test verifies, even if SetServingType returns error we should still publish +/* + This test verifies, even if SetServingType returns error we should still publish + the new table type */ func TestStateChangeTabletTypeWithFailure(t *testing.T) { diff --git a/go/vt/vttablet/tabletmanager/vdiff/controller.go b/go/vt/vttablet/tabletmanager/vdiff/controller.go index fd663b0a3c1..38156b661b8 100644 --- a/go/vt/vttablet/tabletmanager/vdiff/controller.go +++ b/go/vt/vttablet/tabletmanager/vdiff/controller.go @@ -37,8 +37,8 @@ import ( ) /* - vdiff operation states: pending/started/completed/error/unknown - vdiff table states: pending/started/completed/error/unknown +vdiff operation states: pending/started/completed/error/unknown +vdiff table states: pending/started/completed/error/unknown */ type VDiffState string //nolint const ( diff --git a/go/vt/vttablet/tabletmanager/vdiff/doc.go b/go/vt/vttablet/tabletmanager/vdiff/doc.go index 7880cd6fc38..0714d9277bc 100644 --- a/go/vt/vttablet/tabletmanager/vdiff/doc.go +++ b/go/vt/vttablet/tabletmanager/vdiff/doc.go @@ -15,10 +15,8 @@ limitations under the License. */ /* - package vdiff implements the Vitess Diff functionality which compares the logical contents of MySQL tables across keyspaces and shards Please see ./README.md for more information. - */ package vdiff diff --git a/go/vt/vttablet/tabletmanager/vreplication/engine.go b/go/vt/vttablet/tabletmanager/vreplication/engine.go index a63882345a4..fa15e9c0da8 100644 --- a/go/vt/vttablet/tabletmanager/vreplication/engine.go +++ b/go/vt/vttablet/tabletmanager/vreplication/engine.go @@ -332,8 +332,10 @@ func (vre *Engine) Exec(query string) (*sqltypes.Result, error) { // Exec executes the query and the related actions. // Example insert statement: // insert into _vt.vreplication +// // (workflow, source, pos, max_tps, max_replication_lag, time_updated, transaction_timestamp, state) // values ('Resharding', 'keyspace:"ks" shard:"0" tables:"a" tables:"b" ', 'MariaDB/0-1-1083', 9223372036854775807, 9223372036854775807, 481823, 0, 'Running')` +// // Example update statement: // update _vt.vreplication set state='Stopped', message='testing stop' where id=1 // Example delete: delete from _vt.vreplication where id=1 diff --git a/go/vt/vttablet/tabletmanager/vreplication/shard_sorter.go b/go/vt/vttablet/tabletmanager/vreplication/shard_sorter.go index 28d41fbda46..07cefaef976 100644 --- a/go/vt/vttablet/tabletmanager/vreplication/shard_sorter.go +++ b/go/vt/vttablet/tabletmanager/vreplication/shard_sorter.go @@ -18,25 +18,25 @@ package vreplication import "strings" -//ShardSorter implements a sort.Sort() function for sorting shard ranges +// ShardSorter implements a sort.Sort() function for sorting shard ranges type ShardSorter []string -//Len implements the required interface for a sorting function +// Len implements the required interface for a sorting function func (s ShardSorter) Len() int { return len(s) } -//Swap implements the required interface for a sorting function +// Swap implements the required interface for a sorting function func (s ShardSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -//Key returns the prefix of a shard range +// Key returns the prefix of a shard range func (s ShardSorter) Key(ind int) string { return strings.Split(s[ind], "-")[0] } -//Less implements the required interface for a sorting function +// Less implements the required interface for a sorting function func (s ShardSorter) Less(i, j int) bool { return s.Key(i) < s.Key(j) } diff --git a/go/vt/vttablet/tabletmanager/vreplication/vplayer.go b/go/vt/vttablet/tabletmanager/vreplication/vplayer.go index aa862513076..74adf6d6c93 100644 --- a/go/vt/vttablet/tabletmanager/vreplication/vplayer.go +++ b/go/vt/vttablet/tabletmanager/vreplication/vplayer.go @@ -72,13 +72,18 @@ type vplayer struct { // newVPlayer creates a new vplayer. Parameters: // vreplicator: the outer replicator. It's used for common functions like setState. -// Also used to access the engine for registering journal events. +// +// Also used to access the engine for registering journal events. +// // settings: current settings read from _vt.vreplication. // copyState: if set, contains the list of tables yet to be copied, or in the process -// of being copied. If copyState is non-nil, the plans generated make sure that -// replication is only applied to parts that have been copied so far. +// +// of being copied. If copyState is non-nil, the plans generated make sure that +// replication is only applied to parts that have been copied so far. +// // pausePos: if set, replication will stop at that position without updating the state to "Stopped". -// This is used by the fastForward function during copying. +// +// This is used by the fastForward function during copying. func newVPlayer(vr *vreplicator, settings binlogplayer.VRSettings, copyState map[string]*sqltypes.Result, pausePos mysql.Position, phase string) *vplayer { saveStop := true if !pausePos.IsZero() { @@ -271,30 +276,30 @@ func (vp *vplayer) recordHeartbeat() error { // applyEvents is the main thread that applies the events. It has the following use // cases to take into account: -// * Normal transaction that has row mutations. In this case, the transaction -// is committed along with an update of the position. -// * DDL event: the action depends on the OnDDL setting. -// * OTHER event: the current position of the event is saved. -// * JOURNAL event: if the event is relevant to the current stream, invoke registerJournal -// of the engine, and terminate. -// * HEARTBEAT: update ReplicationLagSeconds. -// * Empty transaction: The event is remembered as an unsavedEvent. If no commits -// happen for idleTimeout since timeLastSaved, the current position of the unsavedEvent -// is committed (updatePos). -// * An empty transaction: Empty transactions are necessary because the current -// position of that transaction may be the stop position. If so, we have to record it. -// If not significant, we should avoid saving these empty transactions individually -// because they can cause unnecessary churn and binlog bloat. We should -// also not go for too long without saving because we should not fall way behind -// on the current replication position. Additionally, WaitForPos or other external -// agents could be waiting on that specific position by watching the vreplication -// record. -// * A group of transactions: Combine them into a single transaction. -// * Partial transaction: Replay the events received so far and refetch from relay log -// for more. -// * A combination of any of the above: The trickier case is the one where a group -// of transactions come in, with the last one being partial. In this case, all transactions -// up to the last one have to be committed, and the final one must be partially applied. +// - Normal transaction that has row mutations. In this case, the transaction +// is committed along with an update of the position. +// - DDL event: the action depends on the OnDDL setting. +// - OTHER event: the current position of the event is saved. +// - JOURNAL event: if the event is relevant to the current stream, invoke registerJournal +// of the engine, and terminate. +// - HEARTBEAT: update ReplicationLagSeconds. +// - Empty transaction: The event is remembered as an unsavedEvent. If no commits +// happen for idleTimeout since timeLastSaved, the current position of the unsavedEvent +// is committed (updatePos). +// - An empty transaction: Empty transactions are necessary because the current +// position of that transaction may be the stop position. If so, we have to record it. +// If not significant, we should avoid saving these empty transactions individually +// because they can cause unnecessary churn and binlog bloat. We should +// also not go for too long without saving because we should not fall way behind +// on the current replication position. Additionally, WaitForPos or other external +// agents could be waiting on that specific position by watching the vreplication +// record. +// - A group of transactions: Combine them into a single transaction. +// - Partial transaction: Replay the events received so far and refetch from relay log +// for more. +// - A combination of any of the above: The trickier case is the one where a group +// of transactions come in, with the last one being partial. In this case, all transactions +// up to the last one have to be committed, and the final one must be partially applied. // // Of the above events, the saveable ones are COMMIT, DDL, and OTHER. Eventhough // A GTID comes as a separate event, it's not saveable until a subsequent saveable diff --git a/go/vt/vttablet/tabletmanager/vreplication/vreplicator.go b/go/vt/vttablet/tabletmanager/vreplication/vreplicator.go index ef7468a1895..b6df054fc01 100644 --- a/go/vt/vttablet/tabletmanager/vreplication/vreplicator.go +++ b/go/vt/vttablet/tabletmanager/vreplication/vreplicator.go @@ -126,20 +126,21 @@ type vreplicator struct { // The Filter can be empty: get all rows and columns. // The Filter can be a keyrange, like "-80": get all rows that are within the keyrange. // The Filter can be a select expression. Examples. -// "select * from t", same as an empty Filter, -// "select * from t where in_keyrange('-80')", same as "-80", -// "select * from t where in_keyrange(col1, 'hash', '-80')", -// "select col1, col2 from t where...", -// "select col1, keyspace_id() as ksid from t where...", -// "select id, count(*), sum(price) from t group by id", -// "select * from t where customer_id=1 and val = 'newton'". -// Only "in_keyrange" expressions, integer and string comparisons are supported in the where clause. -// The select expressions can be any valid non-aggregate expressions, -// or count(*), or sum(col). -// If the target column name does not match the source expression, an -// alias like "a+b as targetcol" must be used. -// More advanced constructs can be used. Please see the table plan builder -// documentation for more info. +// +// "select * from t", same as an empty Filter, +// "select * from t where in_keyrange('-80')", same as "-80", +// "select * from t where in_keyrange(col1, 'hash', '-80')", +// "select col1, col2 from t where...", +// "select col1, keyspace_id() as ksid from t where...", +// "select id, count(*), sum(price) from t group by id", +// "select * from t where customer_id=1 and val = 'newton'". +// Only "in_keyrange" expressions, integer and string comparisons are supported in the where clause. +// The select expressions can be any valid non-aggregate expressions, +// or count(*), or sum(col). +// If the target column name does not match the source expression, an +// alias like "a+b as targetcol" must be used. +// More advanced constructs can be used. Please see the table plan builder +// documentation for more info. func newVReplicator(id uint32, source *binlogdatapb.BinlogSource, sourceVStreamer VStreamerClient, stats *binlogplayer.Stats, dbClient binlogplayer.DBClient, mysqld mysqlctl.MysqlDaemon, vre *Engine) *vreplicator { if *vreplicationHeartbeatUpdateInterval > vreplicationMinimumHeartbeatUpdateInterval { log.Warningf("the supplied value for vreplication_heartbeat_update_interval:%d seconds is larger than the maximum allowed:%d seconds, vreplication will fallback to %d", @@ -500,12 +501,12 @@ func (vr *vreplicator) setSQLMode(ctx context.Context) (func(), error) { // throttlerAppName returns the app name to be used by throttlerClient for this particular workflow // example results: -// - "vreplication" for most flows -// - "vreplication:online-ddl" for online ddl flows. -// Note that with such name, it's possible to throttle -// the worflow by either /throttler/throttle-app?app=vreplication and/or /throttler/throttle-app?app=online-ddl -// This is useful when we want to throttle all migrations. We throttle "online-ddl" and that applies to both vreplication -// migrations as well as gh-ost migrations. +// - "vreplication" for most flows +// - "vreplication:online-ddl" for online ddl flows. +// Note that with such name, it's possible to throttle +// the worflow by either /throttler/throttle-app?app=vreplication and/or /throttler/throttle-app?app=online-ddl +// This is useful when we want to throttle all migrations. We throttle "online-ddl" and that applies to both vreplication +// migrations as well as gh-ost migrations. func (vr *vreplicator) throttlerAppName() string { names := []string{vr.WorkflowName, throttlerVReplicationAppName} if vr.WorkflowType == int64(binlogdatapb.VReplicationWorkflowType_ONLINEDDL) { diff --git a/go/vt/vttablet/tabletserver/stateful_connection_pool.go b/go/vt/vttablet/tabletserver/stateful_connection_pool.go index 51ec6bb4910..c0656118f52 100644 --- a/go/vt/vttablet/tabletserver/stateful_connection_pool.go +++ b/go/vt/vttablet/tabletserver/stateful_connection_pool.go @@ -60,7 +60,7 @@ type StatefulConnectionPool struct { lastID sync2.AtomicInt64 } -//NewStatefulConnPool creates an ActivePool +// NewStatefulConnPool creates an ActivePool func NewStatefulConnPool(env tabletenv.Env) *StatefulConnectionPool { config := env.Config() diff --git a/go/vt/vttablet/tabletserver/tabletserver.go b/go/vt/vttablet/tabletserver/tabletserver.go index c719c2b565d..707ceaf06e4 100644 --- a/go/vt/vttablet/tabletserver/tabletserver.go +++ b/go/vt/vttablet/tabletserver/tabletserver.go @@ -231,9 +231,9 @@ func NewTabletServer(name string, config *tabletenv.TabletConfig, topoServer *to // uses it to start/stop query buffering for a given table. // It is onlineDDLExecutor's responsibility to make sure beffering is stopped after some definite amount of time. // There are two layers to buffering/unbuffering: -// 1. the creation and destruction of a QueryRuleSource. The existence of such source affects query plan rules -// for all new queries (see Execute() function and call to GetPlan()) -// 2. affecting already existing rules: a Rule has a concext.WithCancel, that is cancelled by onlineDDLExecutor +// 1. the creation and destruction of a QueryRuleSource. The existence of such source affects query plan rules +// for all new queries (see Execute() function and call to GetPlan()) +// 2. affecting already existing rules: a Rule has a concext.WithCancel, that is cancelled by onlineDDLExecutor func (tsv *TabletServer) onlineDDLExecutorToggleTableBuffer(bufferingCtx context.Context, tableName string, bufferQueries bool) { queryRuleSource := fmt.Sprintf("onlineddl/%s", tableName) @@ -1422,9 +1422,10 @@ func (tsv *TabletServer) convertAndLogError(ctx context.Context, sql string, bin } // truncateSQLAndBindVars calls TruncateForLog which: -// splits off trailing comments, truncates the query, re-adds the trailing comments, -// if sanitize is false appends quoted bindvar:value pairs in sorted order, and -// lastly it truncates the resulting string +// +// splits off trailing comments, truncates the query, re-adds the trailing comments, +// if sanitize is false appends quoted bindvar:value pairs in sorted order, and +// lastly it truncates the resulting string func truncateSQLAndBindVars(sql string, bindVariables map[string]*querypb.BindVariable, sanitize bool) string { truncatedQuery := sqlparser.TruncateForLog(sql) buf := &bytes.Buffer{} diff --git a/go/vt/vttablet/tabletserver/tx/api.go b/go/vt/vttablet/tabletserver/tx/api.go index b011f783277..a06923776c0 100644 --- a/go/vt/vttablet/tabletserver/tx/api.go +++ b/go/vt/vttablet/tabletserver/tx/api.go @@ -89,7 +89,7 @@ func (r ReleaseReason) String() string { return txResolutions[r] } -//Name return the name of enum. +// Name return the name of enum. func (r ReleaseReason) Name() string { return txNames[r] } diff --git a/go/vt/vttablet/tabletserver/tx_pool.go b/go/vt/vttablet/tabletserver/tx_pool.go index 4673bc1432b..b51e4b10372 100644 --- a/go/vt/vttablet/tabletserver/tx_pool.go +++ b/go/vt/vttablet/tabletserver/tx_pool.go @@ -151,7 +151,7 @@ func (tp *TxPool) WaitForEmpty() { tp.scp.WaitForEmpty() } -//NewTxProps creates a new TxProperties struct +// NewTxProps creates a new TxProperties struct func (tp *TxPool) NewTxProps(immediateCaller *querypb.VTGateCallerID, effectiveCaller *vtrpcpb.CallerID, autocommit bool) *tx.Properties { return &tx.Properties{ StartTime: time.Now(), diff --git a/go/vt/vttablet/tabletserver/txserializer/tx_serializer.go b/go/vt/vttablet/tabletserver/txserializer/tx_serializer.go index c87da8864b7..8339a27c860 100644 --- a/go/vt/vttablet/tabletserver/txserializer/tx_serializer.go +++ b/go/vt/vttablet/tabletserver/txserializer/tx_serializer.go @@ -44,15 +44,15 @@ import ( // // This implementation has some parallels to the sync2.Consolidator class. // However, there are many substantial differences: -// - Results are not shared between queued transactions. -// - Only one waiting transaction and not all are notified when the current one -// has finished. -// - Waiting transactions are woken up in FIFO order. -// - Waiting transactions are unblocked if their context is done. -// - Both the local queue (per row range) and global queue (whole process) are -// limited to avoid that queued transactions can consume the full capacity -// of vttablet. This is important if the capaciy is finite. For example, the -// number of RPCs in flight could be limited by the RPC subsystem. +// - Results are not shared between queued transactions. +// - Only one waiting transaction and not all are notified when the current one +// has finished. +// - Waiting transactions are woken up in FIFO order. +// - Waiting transactions are unblocked if their context is done. +// - Both the local queue (per row range) and global queue (whole process) are +// limited to avoid that queued transactions can consume the full capacity +// of vttablet. This is important if the capaciy is finite. For example, the +// number of RPCs in flight could be limited by the RPC subsystem. type TxSerializer struct { env tabletenv.Env *sync2.ConsolidatorCache diff --git a/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go b/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go index 217c3ac1f1e..984a06bf12b 100644 --- a/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go +++ b/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go @@ -43,23 +43,24 @@ import ( // It uses a discovery.LegacyHealthCheck to send replication-lag updates to the wrapped throttler. // // Intended Usage: -// // Assuming topoServer is a topo.Server variable pointing to a Vitess topology server. -// t := NewTxThrottler(config, topoServer) // -// // A transaction throttler must be opened before its first use: -// if err := t.Open(keyspace, shard); err != nil { -// return err -// } +// // Assuming topoServer is a topo.Server variable pointing to a Vitess topology server. +// t := NewTxThrottler(config, topoServer) // -// // Checking whether to throttle can be done as follows before starting a transaction. -// if t.Throttle() { -// return fmt.Errorf("Transaction throttled!") -// } else { -// // execute transaction. -// } +// // A transaction throttler must be opened before its first use: +// if err := t.Open(keyspace, shard); err != nil { +// return err +// } // -// // To release the resources used by the throttler the caller should call Close(). -// t.Close() +// // Checking whether to throttle can be done as follows before starting a transaction. +// if t.Throttle() { +// return fmt.Errorf("Transaction throttled!") +// } else { +// // execute transaction. +// } +// +// // To release the resources used by the throttler the caller should call Close(). +// t.Close() // // A TxThrottler object is generally not thread-safe: at any given time at most one goroutine should // be executing a method. The only exception is the 'Throttle' method where multiple goroutines are diff --git a/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go b/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go index c50fc21b375..e612bdc9407 100644 --- a/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go +++ b/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go @@ -101,18 +101,22 @@ type streamerPlan struct { // cp: the mysql conn params. // sh: the schema engine. The vstreamer uses it to convert the TableMap into field info. // startPos: a flavor compliant position to stream from. This can also contain the special -// value "current", which means start from the current position. +// +// value "current", which means start from the current position. +// // filter: the list of filtering rules. If a rule has a select expression for its filter, -// the select list can only reference direct columns. No other expressions are allowed. -// The select expression is allowed to contain the special 'keyspace_id()' function which -// will return the keyspace id of the row. Examples: -// "select * from t", same as an empty Filter, -// "select * from t where in_keyrange('-80')", same as "-80", -// "select * from t where in_keyrange(col1, 'hash', '-80')", -// "select col1, col2 from t where...", -// "select col1, keyspace_id() from t where...". -// Only "in_keyrange" and limited comparison operators (see enum Opcode in planbuilder.go) are supported in the where clause. -// Other constructs like joins, group by, etc. are not supported. +// +// the select list can only reference direct columns. No other expressions are allowed. +// The select expression is allowed to contain the special 'keyspace_id()' function which +// will return the keyspace id of the row. Examples: +// "select * from t", same as an empty Filter, +// "select * from t where in_keyrange('-80')", same as "-80", +// "select * from t where in_keyrange(col1, 'hash', '-80')", +// "select col1, col2 from t where...", +// "select col1, keyspace_id() from t where...". +// Only "in_keyrange" and limited comparison operators (see enum Opcode in planbuilder.go) are supported in the where clause. +// Other constructs like joins, group by, etc. are not supported. +// // vschema: the current vschema. This value can later be changed through the SetVSchema method. // send: callback function to send events. func newVStreamer(ctx context.Context, cp dbconfigs.Connector, se *schema.Engine, startPos string, stopPos string, filter *binlogdatapb.Filter, vschema *localVSchema, send func([]*binlogdatapb.VEvent) error, phase string, vse *Engine) *vstreamer { diff --git a/go/vt/vttablet/tabletservermock/controller.go b/go/vt/vttablet/tabletservermock/controller.go index a83e9d8c551..edeb0c885f2 100644 --- a/go/vt/vttablet/tabletservermock/controller.go +++ b/go/vt/vttablet/tabletservermock/controller.go @@ -181,7 +181,7 @@ func (tqsc *Controller) OnlineDDLExecutor() vexec.Executor { return nil } -//ClearQueryPlanCache is part of the tabletserver.Controller interface +// ClearQueryPlanCache is part of the tabletserver.Controller interface func (tqsc *Controller) ClearQueryPlanCache() { } diff --git a/go/vt/vttablet/vexec/vexec.go b/go/vt/vttablet/vexec/vexec.go index c604b4eb1fd..63af3b06016 100644 --- a/go/vt/vttablet/vexec/vexec.go +++ b/go/vt/vttablet/vexec/vexec.go @@ -174,14 +174,14 @@ func (e *TabletVExec) AddOrReplaceInsertColumnVal(colName string, val *sqlparser // analyzeStatement analyzes a given statement and produces the following ingredients, useful for // VExec interceptors: -// - table name -// - column names with values, for col=VAL in a WHERE expression -// e.g. in "UPDATE my_table SET ... WHERE keyspace='test' AND shard='-80' AND status > 2", the -// ValColumns are "keyspace" and "shard" with matching values. `status` is a range operator therefore -// not included.package vexec -// Equals operator is of special importance because it is known to filter results. An interceptor may -// require, for example, that a `DELETE` statement includes a WHERE with a UNIQUE KEY column with Equals operator -// to ensure we're not doing anything too risky. +// - table name +// - column names with values, for col=VAL in a WHERE expression +// e.g. in "UPDATE my_table SET ... WHERE keyspace='test' AND shard='-80' AND status > 2", the +// ValColumns are "keyspace" and "shard" with matching values. `status` is a range operator therefore +// not included.package vexec +// Equals operator is of special importance because it is known to filter results. An interceptor may +// require, for example, that a `DELETE` statement includes a WHERE with a UNIQUE KEY column with Equals operator +// to ensure we're not doing anything too risky. func (e *TabletVExec) analyzeStatement() error { switch stmt := e.Stmt.(type) { case *sqlparser.Update: @@ -205,15 +205,15 @@ func (e *TabletVExec) analyzeStatement() error { // AnalyzeQuery analyzes a given statement and produces the following ingredients, useful for // VExec interceptors: -// - parsed statement -// - table name -// - column names with values, for col=VAL in a WHERE expression -// e.g. in "UPDATE my_table SET ... WHERE keyspace='test' AND shard='-80' AND status > 2", the -// ValColumns are "keyspace" and "shard" with matching values. `status` is a range operator therefore -// not included.package vexec -// Equals operator is of special importance because it is known to filter results. An interceptor may -// require, for example, that a `DELETE` statement includes a WHERE with a UNIQUE KEY column with Equals operator -// to ensure we're not doing anything too risky. +// - parsed statement +// - table name +// - column names with values, for col=VAL in a WHERE expression +// e.g. in "UPDATE my_table SET ... WHERE keyspace='test' AND shard='-80' AND status > 2", the +// ValColumns are "keyspace" and "shard" with matching values. `status` is a range operator therefore +// not included.package vexec +// Equals operator is of special importance because it is known to filter results. An interceptor may +// require, for example, that a `DELETE` statement includes a WHERE with a UNIQUE KEY column with Equals operator +// to ensure we're not doing anything too risky. func (e *TabletVExec) AnalyzeQuery(ctx context.Context, query string) (err error) { if e.Stmt, err = sqlparser.Parse(query); err != nil { return err diff --git a/go/vt/vttime/doc.go b/go/vt/vttime/doc.go index c7c6b621b27..6d4b2f2974f 100644 --- a/go/vt/vttime/doc.go +++ b/go/vt/vttime/doc.go @@ -29,11 +29,14 @@ limitations under the License. // // When comparing two intervals, we know one of them is smaller if // there is no overlap and it is before: -// [--------] -// [-----------] +// +// [--------] +// [-----------] +// // If there is overlap, we can't say for sure: -// [--------] -// [----------] +// +// [--------] +// [----------] // // However, if the goal is to be sure we are producing events that // clients will know are chonologically ordered, it is then possible diff --git a/go/vt/wrangler/materializer.go b/go/vt/wrangler/materializer.go index 6830e17fe3a..c9999c2f7dd 100644 --- a/go/vt/wrangler/materializer.go +++ b/go/vt/wrangler/materializer.go @@ -843,7 +843,6 @@ func (wr *Wrangler) ExternalizeVindex(ctx context.Context, qualifiedVindexName s return wr.ts.RebuildSrvVSchema(ctx, nil) } -// func (wr *Wrangler) collectTargetStreams(ctx context.Context, mz *materializer) ([]string, error) { var shardTablets []string var mu sync.Mutex diff --git a/go/vt/zkctl/zkconf.go b/go/vt/zkctl/zkconf.go index 8f7aab445af..5c21593aec3 100644 --- a/go/vt/zkctl/zkconf.go +++ b/go/vt/zkctl/zkconf.go @@ -94,7 +94,7 @@ func (cnf *ZkConfig) WriteMyid() error { } /* - Search for first existing file in cnfFiles and subsitute in the right values. +Search for first existing file in cnfFiles and subsitute in the right values. */ func MakeZooCfg(cnfFiles []string, cnf *ZkConfig, header string) (string, error) { myTemplateSource := new(bytes.Buffer) @@ -129,12 +129,12 @@ func MakeZooCfg(cnfFiles []string, cnf *ZkConfig, header string) (string, error) const GuessMyID = 0 /* - Create a config for this instance. +Create a config for this instance. - @::: +@::: - If server_id > 1000, then we assume this is a global quorum. - server_id's must be 1-255, global id's are 1001-1255 mod 1000. +If server_id > 1000, then we assume this is a global quorum. +server_id's must be 1-255, global id's are 1001-1255 mod 1000. */ func MakeZkConfigFromString(cmdLine string, myID uint32) *ZkConfig { zkConfig := NewZkConfig() diff --git a/tools/coverage-go/mysqlctl_test.go b/tools/coverage-go/mysqlctl_test.go index 8015ad4c2de..f3d6876a2d4 100644 --- a/tools/coverage-go/mysqlctl_test.go +++ b/tools/coverage-go/mysqlctl_test.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/tools/coverage-go/vtctl_test.go b/tools/coverage-go/vtctl_test.go index 497d0b21622..db215e48a6f 100644 --- a/tools/coverage-go/vtctl_test.go +++ b/tools/coverage-go/vtctl_test.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/tools/coverage-go/vtctld_test.go b/tools/coverage-go/vtctld_test.go index bf3704696a2..eaa7ebda1e5 100644 --- a/tools/coverage-go/vtctld_test.go +++ b/tools/coverage-go/vtctld_test.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/tools/coverage-go/vtgate_test.go b/tools/coverage-go/vtgate_test.go index 57d030895f4..c3601fc0372 100644 --- a/tools/coverage-go/vtgate_test.go +++ b/tools/coverage-go/vtgate_test.go @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,