From 4cb8351929e359d13b08f17f7e8cd2bda5ddb851 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= <36616255+hrapovd1@users.noreply.github.com> Date: Mon, 5 Feb 2024 22:46:15 +0300 Subject: [PATCH 01/10] enabled nonamedreturns linter * Refactored `config/defaults.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/basic/database_sql/data.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/basic/database_sql/series.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/basic/gorm/models.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/basic/native/series.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/basic/xorm/data.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/ddl/ddl.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/decimal/main.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/describe/main.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/pagination/cities.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/read_table/orders.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/serverless/healthcheck/service.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/serverless/url_shortener/service.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/topic/cdc-fill-and-read/tables.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/topic/topicreader/stubs.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/topic/topicreader/topicreader_advanced.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/topic/topicreader/topicreader_trace.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/ttl/series.go`, when golangci-lint nonamedreturns enabled * Refactored `examples/ttl_readtable/series.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/allocator/allocator.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/backoff/backoff_test.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/balancer/balancer.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/balancer/connections_state.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/balancer/ctx.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/balancer/local_dc.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/bind/auto_declare.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/bind/bind.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/bind/numeric_args.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/bind/params.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/bind/positional_args.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/bind/table_path_prefix.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/certificates/certificates.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/cmd/gtrace/main.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/cmd/gtrace/writer.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/conn/conn.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/conn/grpc_client_stream.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/conn/pool.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/coordination/client.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/credentials/static.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/decimal/decimal.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/discovery/discovery.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/dsn/dsn.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/endpoint/endpoint.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/grpcwrapper/rawtopic/client.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/grpcwrapper/rawtopic/rawtopicreader/messages.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/grpcwrapper/rawtopic/rawtopicwriter/messages.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/meta/meta.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/mock/conn.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/operation/context.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/ratelimiter/client.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/repeater/repeater.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/repeater/repeater_test.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/scheme/client.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/scheme/helpers/check_exists.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/scheme/helpers/check_exists_test.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/scripting/client.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/stack/record.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/client.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/client_test.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/retry.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/retry_test.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/scanner/result.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/scanner/scan_raw.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/scanner/scanner.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/scanner/scanner_test.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/scanner/stats.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/session.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/session_test.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/statement.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/table/transaction.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/retriable_error.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicclientinternal/client.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/batch.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/batcher.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/committer.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/message.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/one_time_reader.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/reader.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/stream_reader_impl.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicreaderinternal/stream_reconnector.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicwriterinternal/queue.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicwriterinternal/writer.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicwriterinternal/writer_reconnector.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/topic/topicwriterinternal/writer_single_stream.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/value/time.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/value/type.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/value/value.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/version/parse.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xcontext/context_with_cancel.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xcontext/context_with_timeout.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xcontext/without_deadline.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xerrors/check.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xerrors/issues.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xerrors/operation.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xresolver/xresolver.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/conn.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/connector.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/context.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/dsn.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/isolation/isolation.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/rows.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/stmt.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/tx.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/tx_fake.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xsql/unwrap.go`, when golangci-lint nonamedreturns enabled * Refactored `internal/xstring/convert.go`, when golangci-lint nonamedreturns enabled * Refactored `log/coordination.go`, when golangci-lint nonamedreturns enabled * Refactored `log/discovery.go`, when golangci-lint nonamedreturns enabled * Refactored `log/driver.go`, when golangci-lint nonamedreturns enabled * Refactored `log/field.go`, when golangci-lint nonamedreturns enabled * Refactored `log/ratelimiter.go`, when golangci-lint nonamedreturns enabled * Refactored `log/retry.go`, when golangci-lint nonamedreturns enabled * Refactored `log/scheme.go`, when golangci-lint nonamedreturns enabled * Refactored `log/scripting.go`, when golangci-lint nonamedreturns enabled * Refactored `log/sql.go`, when golangci-lint nonamedreturns enabled * Refactored `log/table.go`, when golangci-lint nonamedreturns enabled * Refactored `log/topic.go`, when golangci-lint nonamedreturns enabled * Refactored `meta/consumed_units.go`, when golangci-lint nonamedreturns enabled * Refactored `meta/example_test.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/coordination.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/discovery.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/driver.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/ratelimiter.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/retry.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/scheme.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/scripting.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/sql.go`, when golangci-lint nonamedreturns enabled * Refactored `metrics/table.go`, when golangci-lint nonamedreturns enabled * Refactored `retry/retry.go`, when golangci-lint nonamedreturns enabled * Refactored `retry/retryable_error.go`, when golangci-lint nonamedreturns enabled * Refactored `scheme/scheme.go`, when golangci-lint nonamedreturns enabled * Refactored `scripting/example_test.go`, when golangci-lint nonamedreturns enabled * Refactored `sugar/certificates.go`, when golangci-lint nonamedreturns enabled * Refactored `sugar/check_exists.go`, when golangci-lint nonamedreturns enabled * Refactored `sugar/dsn.go`, when golangci-lint nonamedreturns enabled * Refactored `sugar/params.go`, when golangci-lint nonamedreturns enabled * Refactored `sugar/params_test.go`, when golangci-lint nonamedreturns enabled * Refactored `sugar/path.go`, when golangci-lint nonamedreturns enabled * Refactored `table/example_test.go`, when golangci-lint nonamedreturns enabled * Refactored `table/types/cast.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/database/sql/main.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/database/sql/storage.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/gorm/main.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/gorm/storage.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/internal/workers/read.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/internal/workers/write.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/native/main.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/native/storage.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/xorm/main.go`, when golangci-lint nonamedreturns enabled * Refactored `tests/slo/xorm/storage.go`, when golangci-lint nonamedreturns enabled * Refactored `testutil/driver.go`, when golangci-lint nonamedreturns enabled * Refactored `topic/topicoptions/topicoptions_alter.go`, when golangci-lint nonamedreturns enabled * Refactored `topic/topicwriter/topicwriter.go`, when golangci-lint nonamedreturns enabled * Refactored `trace/details.go`, when golangci-lint nonamedreturns enabled * Refactored `trace/driver.go`, when golangci-lint nonamedreturns enabled --- .golangci.yml | 1 - CHANGELOG.md | 155 +++++++++++++ config/defaults.go | 5 +- examples/basic/database_sql/data.go | 41 ++-- examples/basic/database_sql/series.go | 36 +-- examples/basic/gorm/models.go | 12 +- examples/basic/native/series.go | 50 +++-- examples/basic/xorm/data.go | 47 ++-- examples/ddl/ddl.go | 6 +- examples/decimal/main.go | 8 +- examples/describe/main.go | 4 +- examples/pagination/cities.go | 28 ++- examples/read_table/orders.go | 18 +- examples/serverless/healthcheck/service.go | 16 +- examples/serverless/url_shortener/service.go | 25 ++- examples/topic/cdc-fill-and-read/tables.go | 8 +- examples/topic/topicreader/stubs.go | 2 +- .../topic/topicreader/topicreader_advanced.go | 5 +- .../topic/topicreader/topicreader_trace.go | 3 +- examples/ttl/series.go | 27 ++- examples/ttl_readtable/series.go | 39 ++-- internal/allocator/allocator.go | 166 +++++++------- internal/backoff/backoff_test.go | 10 +- internal/balancer/balancer.go | 43 ++-- internal/balancer/connections_state.go | 12 +- internal/balancer/ctx.go | 4 +- internal/balancer/local_dc.go | 4 +- internal/bind/auto_declare.go | 3 +- internal/bind/bind.go | 9 +- internal/bind/numeric_args.go | 10 +- internal/bind/params.go | 8 +- internal/bind/positional_args.go | 7 +- internal/bind/table_path_prefix.go | 3 +- internal/certificates/certificates.go | 12 +- internal/cmd/gtrace/main.go | 19 +- internal/cmd/gtrace/writer.go | 36 +-- internal/conn/conn.go | 57 +++-- internal/conn/grpc_client_stream.go | 13 +- internal/conn/pool.go | 7 +- internal/coordination/client.go | 24 +- internal/credentials/static.go | 11 +- internal/decimal/decimal.go | 3 +- internal/discovery/discovery.go | 15 +- internal/dsn/dsn.go | 3 +- internal/endpoint/endpoint.go | 2 +- internal/grpcwrapper/rawtopic/client.go | 12 +- .../rawtopic/rawtopicreader/messages.go | 4 +- .../rawtopic/rawtopicwriter/messages.go | 7 +- internal/meta/meta.go | 9 +- internal/mock/conn.go | 2 +- internal/operation/context.go | 12 +- internal/ratelimiter/client.go | 52 +++-- internal/repeater/repeater.go | 3 +- internal/repeater/repeater_test.go | 4 +- internal/scheme/client.go | 84 ++++--- internal/scheme/helpers/check_exists.go | 4 +- internal/scheme/helpers/check_exists_test.go | 8 +- internal/scripting/client.go | 44 ++-- internal/stack/record.go | 3 +- internal/table/client.go | 87 +++++--- internal/table/client_test.go | 8 +- internal/table/retry.go | 10 +- internal/table/retry_test.go | 2 +- internal/table/scanner/result.go | 10 +- internal/table/scanner/scan_raw.go | 208 +++++++++--------- internal/table/scanner/scanner.go | 122 +++++----- internal/table/scanner/scanner_test.go | 9 +- internal/table/scanner/stats.go | 16 +- internal/table/session.go | 102 +++++---- internal/table/session_test.go | 14 +- internal/table/statement.go | 7 +- internal/table/transaction.go | 54 +++-- internal/topic/retriable_error.go | 12 +- internal/topic/topicclientinternal/client.go | 16 +- internal/topic/topicreaderinternal/batch.go | 6 +- internal/topic/topicreaderinternal/batcher.go | 18 +- .../topic/topicreaderinternal/committer.go | 2 +- internal/topic/topicreaderinternal/message.go | 4 +- .../topicreaderinternal/one_time_reader.go | 5 +- internal/topic/topicreaderinternal/reader.go | 13 +- .../topicreaderinternal/stream_reader_impl.go | 22 +- .../topicreaderinternal/stream_reconnector.go | 11 +- internal/topic/topicwriterinternal/queue.go | 13 +- internal/topic/topicwriterinternal/writer.go | 2 +- .../topicwriterinternal/writer_reconnector.go | 46 ++-- .../writer_single_stream.go | 9 +- internal/value/time.go | 21 +- internal/value/type.go | 6 +- internal/value/value.go | 7 +- internal/version/parse.go | 8 +- internal/xcontext/context_with_cancel.go | 2 +- internal/xcontext/context_with_timeout.go | 2 +- internal/xcontext/without_deadline.go | 2 +- internal/xerrors/check.go | 2 +- internal/xerrors/issues.go | 7 +- internal/xerrors/operation.go | 3 +- internal/xresolver/xresolver.go | 8 +- internal/xsql/conn.go | 148 ++++++++----- internal/xsql/connector.go | 14 +- internal/xsql/context.go | 3 +- internal/xsql/dsn.go | 6 +- internal/xsql/isolation/isolation.go | 2 +- internal/xsql/rows.go | 7 +- internal/xsql/stmt.go | 29 ++- internal/xsql/tx.go | 55 +++-- internal/xsql/tx_fake.go | 63 ++++-- internal/xsql/unwrap.go | 6 +- internal/xstring/convert.go | 2 +- log/coordination.go | 4 +- log/discovery.go | 5 +- log/driver.go | 6 +- log/field.go | 3 +- log/ratelimiter.go | 4 +- log/retry.go | 5 +- log/scheme.go | 4 +- log/scripting.go | 5 +- log/sql.go | 5 +- log/table.go | 5 +- log/topic.go | 6 +- meta/consumed_units.go | 3 +- meta/example_test.go | 8 +- metrics/coordination.go | 4 +- metrics/discovery.go | 4 +- metrics/driver.go | 3 +- metrics/ratelimiter.go | 4 +- metrics/retry.go | 3 +- metrics/scheme.go | 4 +- metrics/scripting.go | 4 +- metrics/sql.go | 3 +- metrics/table.go | 3 +- retry/retry.go | 2 +- retry/retryable_error.go | 3 +- scheme/scheme.go | 5 +- scripting/example_test.go | 24 +- sugar/certificates.go | 9 +- sugar/check_exists.go | 8 +- sugar/dsn.go | 2 +- sugar/params.go | 3 +- sugar/params_test.go | 9 +- sugar/path.go | 2 +- table/example_test.go | 42 ++-- table/types/cast.go | 5 +- tests/slo/database/sql/main.go | 14 +- tests/slo/database/sql/storage.go | 25 ++- tests/slo/gorm/main.go | 14 +- tests/slo/gorm/storage.go | 17 +- tests/slo/internal/workers/read.go | 7 +- tests/slo/internal/workers/write.go | 7 +- tests/slo/native/main.go | 14 +- tests/slo/native/storage.go | 25 ++- tests/slo/xorm/main.go | 14 +- tests/slo/xorm/storage.go | 24 +- testutil/driver.go | 12 +- topic/topicoptions/topicoptions_alter.go | 4 +- topic/topicwriter/topicwriter.go | 6 +- trace/details.go | 3 +- trace/driver.go | 14 +- 157 files changed, 1785 insertions(+), 1120 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 40e5b3514..483bb7f55 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -238,7 +238,6 @@ linters: - ireturn - maintidx - maligned - - nonamedreturns - paralleltest - protogetter - scopelint diff --git a/CHANGELOG.md b/CHANGELOG.md index 86c81bc7f..541a2ce58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,161 @@ * Fixed topic writer infinite reconnections in some cases * Refactored nil on err `internal/grpcwrapper/rawydb/issues.go`, when golangci-lint nilerr enabled * Refactored nil on err `internal/grpcwrapper/rawtopic/describe_topic.go`, when golangci-lint nilerr enabled +* Refactored `config/defaults.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/basic/database_sql/data.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/basic/database_sql/series.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/basic/gorm/models.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/basic/native/series.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/basic/xorm/data.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/ddl/ddl.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/decimal/main.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/describe/main.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/pagination/cities.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/read_table/orders.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/serverless/healthcheck/service.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/serverless/url_shortener/service.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/topic/cdc-fill-and-read/tables.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/topic/topicreader/stubs.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/topic/topicreader/topicreader_advanced.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/topic/topicreader/topicreader_trace.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/ttl/series.go`, when golangci-lint nonamedreturns enabled +* Refactored `examples/ttl_readtable/series.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/allocator/allocator.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/backoff/backoff_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/balancer/balancer.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/balancer/connections_state.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/balancer/ctx.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/balancer/local_dc.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/bind/auto_declare.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/bind/bind.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/bind/numeric_args.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/bind/params.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/bind/positional_args.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/bind/table_path_prefix.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/certificates/certificates.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/cmd/gtrace/main.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/cmd/gtrace/writer.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/conn/conn.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/conn/grpc_client_stream.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/conn/pool.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/coordination/client.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/credentials/static.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/decimal/decimal.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/discovery/discovery.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/dsn/dsn.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/endpoint/endpoint.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/grpcwrapper/rawtopic/client.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/grpcwrapper/rawtopic/rawtopicreader/messages.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/grpcwrapper/rawtopic/rawtopicwriter/messages.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/meta/meta.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/mock/conn.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/operation/context.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/ratelimiter/client.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/repeater/repeater.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/repeater/repeater_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/scheme/client.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/scheme/helpers/check_exists.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/scheme/helpers/check_exists_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/scripting/client.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/stack/record.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/client.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/client_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/retry.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/retry_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/scanner/result.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/scanner/scan_raw.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/scanner/scanner.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/scanner/scanner_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/scanner/stats.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/session.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/session_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/statement.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/table/transaction.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/retriable_error.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicclientinternal/client.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/batch.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/batcher.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/committer.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/message.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/one_time_reader.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/reader.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/stream_reader_impl.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicreaderinternal/stream_reconnector.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicwriterinternal/queue.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicwriterinternal/writer.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicwriterinternal/writer_reconnector.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/topic/topicwriterinternal/writer_single_stream.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/value/time.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/value/type.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/value/value.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/version/parse.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xcontext/context_with_cancel.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xcontext/context_with_timeout.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xcontext/without_deadline.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xerrors/check.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xerrors/issues.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xerrors/operation.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xresolver/xresolver.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/conn.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/connector.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/context.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/dsn.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/isolation/isolation.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/rows.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/stmt.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/tx.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/tx_fake.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xsql/unwrap.go`, when golangci-lint nonamedreturns enabled +* Refactored `internal/xstring/convert.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/coordination.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/discovery.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/driver.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/field.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/ratelimiter.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/retry.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/scheme.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/scripting.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/sql.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/table.go`, when golangci-lint nonamedreturns enabled +* Refactored `log/topic.go`, when golangci-lint nonamedreturns enabled +* Refactored `meta/consumed_units.go`, when golangci-lint nonamedreturns enabled +* Refactored `meta/example_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/coordination.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/discovery.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/driver.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/ratelimiter.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/retry.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/scheme.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/scripting.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/sql.go`, when golangci-lint nonamedreturns enabled +* Refactored `metrics/table.go`, when golangci-lint nonamedreturns enabled +* Refactored `retry/retry.go`, when golangci-lint nonamedreturns enabled +* Refactored `retry/retryable_error.go`, when golangci-lint nonamedreturns enabled +* Refactored `scheme/scheme.go`, when golangci-lint nonamedreturns enabled +* Refactored `scripting/example_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `sugar/certificates.go`, when golangci-lint nonamedreturns enabled +* Refactored `sugar/check_exists.go`, when golangci-lint nonamedreturns enabled +* Refactored `sugar/dsn.go`, when golangci-lint nonamedreturns enabled +* Refactored `sugar/params.go`, when golangci-lint nonamedreturns enabled +* Refactored `sugar/params_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `sugar/path.go`, when golangci-lint nonamedreturns enabled +* Refactored `table/example_test.go`, when golangci-lint nonamedreturns enabled +* Refactored `table/types/cast.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/database/sql/main.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/database/sql/storage.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/gorm/main.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/gorm/storage.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/internal/workers/read.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/internal/workers/write.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/native/main.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/native/storage.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/xorm/main.go`, when golangci-lint nonamedreturns enabled +* Refactored `tests/slo/xorm/storage.go`, when golangci-lint nonamedreturns enabled +* Refactored `testutil/driver.go`, when golangci-lint nonamedreturns enabled +* Refactored `topic/topicoptions/topicoptions_alter.go`, when golangci-lint nonamedreturns enabled +* Refactored `topic/topicwriter/topicwriter.go`, when golangci-lint nonamedreturns enabled +* Refactored `trace/details.go`, when golangci-lint nonamedreturns enabled +* Refactored `trace/driver.go`, when golangci-lint nonamedreturns enabled ## v3.55.2 * Fixed init info in topic writer, when autoseq num turned off. diff --git a/config/defaults.go b/config/defaults.go index e63867808..92f7a9b53 100644 --- a/config/defaults.go +++ b/config/defaults.go @@ -30,7 +30,8 @@ var ( } ) -func defaultGrpcOptions(t *trace.Driver, secure bool, tlsConfig *tls.Config) (opts []grpc.DialOption) { +func defaultGrpcOptions(t *trace.Driver, secure bool, tlsConfig *tls.Config) []grpc.DialOption { + var opts []grpc.DialOption opts = append(opts, // keep-aliving all connections grpc.WithKeepaliveParams( @@ -84,7 +85,7 @@ func defaultTLSConfig() *tls.Config { } } -func defaultConfig() (c *Config) { +func defaultConfig() *Config { return &Config{ credentials: credentials.NewAnonymousCredentials( credentials.WithSourceInfo(stack.Record(0)), diff --git a/examples/basic/database_sql/data.go b/examples/basic/database_sql/data.go index 5b373b7a3..a62620e40 100644 --- a/examples/basic/database_sql/data.go +++ b/examples/basic/database_sql/data.go @@ -48,7 +48,12 @@ func episodeData(seriesID, seasonID, episodeID, title string, date time.Time) ty ) } -func getData() (series, seasons, episodes []types.Value) { +func getData() ([]types.Value, []types.Value, []types.Value) { + var ( + series = make([]types.Value, 0) + seasons = make([]types.Value, 0) + episodes = make([]types.Value, 0) + ) for seriesID, fill := range map[string]func(seriesID string) ( seriesData types.Value, seasons []types.Value, episodes []types.Value, ){ @@ -61,15 +66,19 @@ func getData() (series, seasons, episodes []types.Value) { episodes = append(episodes, episodesData...) } - return + return series, seasons, episodes } -func getDataForITCrowd(seriesID string) (series types.Value, seasons, episodes []types.Value) { - series = seriesData( - seriesID, date("2006-02-03"), "IT Crowd", ""+ - "The IT Crowd is a British sitcom produced by Channel 4, written by Graham Linehan, produced by "+ - "Ash Atalla and starring Chris O'Dowd, Richard Ayoade, Katherine Parkinson, and Matt Berry.", - "", // NULL comment. +func getDataForITCrowd(seriesID string) (types.Value, []types.Value, []types.Value) { + var ( + series = seriesData( + seriesID, date("2006-02-03"), "IT Crowd", ""+ + "The IT Crowd is a British sitcom produced by Channel 4, written by Graham Linehan, produced by "+ + "Ash Atalla and starring Chris O'Dowd, Richard Ayoade, Katherine Parkinson, and Matt Berry.", + "", // NULL comment. + ) + seasons = make([]types.Value, 0) + episodes = make([]types.Value, 0) ) for _, season := range []struct { //nolint:gocritic title string @@ -120,12 +129,16 @@ func getDataForITCrowd(seriesID string) (series types.Value, seasons, episodes [ return series, seasons, episodes } -func getDataForSiliconValley(seriesID string) (series types.Value, seasons, episodes []types.Value) { - series = seriesData( - seriesID, date("2014-04-06"), "Silicon Valley", ""+ - "Silicon Valley is an American comedy television series created by Mike Judge, John Altschuler and "+ - "Dave Krinsky. The series focuses on five young men who founded a startup company in Silicon Valley.", - "Some comment here", +func getDataForSiliconValley(seriesID string) (types.Value, []types.Value, []types.Value) { + var ( + series = seriesData( + seriesID, date("2014-04-06"), "Silicon Valley", ""+ + "Silicon Valley is an American comedy television series created by Mike Judge, John Altschuler and "+ + "Dave Krinsky. The series focuses on five young men who founded a startup company in Silicon Valley.", + "Some comment here", + ) + seasons = make([]types.Value, 0) + episodes = make([]types.Value, 0) ) for _, season := range []struct { //nolint:gocritic title string diff --git a/examples/basic/database_sql/series.go b/examples/basic/database_sql/series.go index 28c39a50d..8357f6f7a 100644 --- a/examples/basic/database_sql/series.go +++ b/examples/basic/database_sql/series.go @@ -16,9 +16,9 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/table/types" ) -func selectDefault(ctx context.Context, db *sql.DB) (err error) { +func selectDefault(ctx context.Context, db *sql.DB) error { // explain of query - err = retry.Do(ctx, db, func(ctx context.Context, cc *sql.Conn) (err error) { + err := retry.Do(ctx, db, func(ctx context.Context, cc *sql.Conn) error { row := cc.QueryRowContext(ydb.WithQueryMode(ctx, ydb.ExplainQueryMode), `SELECT series_id, title, release_date FROM series;`, ) @@ -26,7 +26,7 @@ func selectDefault(ctx context.Context, db *sql.DB) (err error) { ast string plan string ) - if err = row.Scan(&ast, &plan); err != nil { + if err := row.Scan(&ast, &plan); err != nil { return err } log.Printf("AST = %s\n\nPlan = %s", ast, plan) @@ -39,10 +39,10 @@ func selectDefault(ctx context.Context, db *sql.DB) (err error) { err = retry.Do( ydb.WithTxControl(ctx, table.OnlineReadOnlyTxControl()), db, - func(ctx context.Context, cc *sql.Conn) (err error) { - rows, err := cc.QueryContext(ctx, `SELECT series_id, title, release_date FROM series;`) - if err != nil { - return err + func(ctx context.Context, cc *sql.Conn) error { + rows, errIn := cc.QueryContext(ctx, `SELECT series_id, title, release_date FROM series;`) + if errIn != nil { + return errIn } defer func() { _ = rows.Close() @@ -72,12 +72,12 @@ func selectDefault(ctx context.Context, db *sql.DB) (err error) { return nil } -func selectScan(ctx context.Context, db *sql.DB) (err error) { +func selectScan(ctx context.Context, db *sql.DB) error { // scan query - err = retry.Do( + err := retry.Do( ydb.WithTxControl(ctx, table.StaleReadOnlyTxControl()), db, - func(ctx context.Context, cc *sql.Conn) (err error) { + func(ctx context.Context, cc *sql.Conn) error { var ( id string seriesIDs []types.Value @@ -92,11 +92,11 @@ func selectScan(ctx context.Context, db *sql.DB) (err error) { table.ValueParam("$seriesTitle", types.TextValue("%IT Crowd%")), ), ) - if err = row.Scan(&id); err != nil { + if err := row.Scan(&id); err != nil { return err } seriesIDs = append(seriesIDs, types.BytesValueFromString(id)) - if err = row.Err(); err != nil { + if err := row.Err(); err != nil { return err } @@ -167,15 +167,15 @@ func selectScan(ctx context.Context, db *sql.DB) (err error) { return nil } -func fillTablesWithData(ctx context.Context, db *sql.DB) (err error) { +func fillTablesWithData(ctx context.Context, db *sql.DB) error { series, seasonsData, episodesData := getData() args := []interface{}{ sql.Named("seriesData", types.ListValue(series...)), sql.Named("seasonsData", types.ListValue(seasonsData...)), sql.Named("episodesData", types.ListValue(episodesData...)), } - err = retry.DoTx(ctx, db, func(ctx context.Context, tx *sql.Tx) error { - if _, err = tx.ExecContext(ctx, ` + err := retry.DoTx(ctx, db, func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, ` REPLACE INTO series SELECT series_id, @@ -216,9 +216,9 @@ func fillTablesWithData(ctx context.Context, db *sql.DB) (err error) { return nil } -func prepareSchema(ctx context.Context, db *sql.DB) (err error) { - err = retry.Do(ctx, db, func(ctx context.Context, cc *sql.Conn) error { - err = dropTableIfExists(ctx, cc, "series") +func prepareSchema(ctx context.Context, db *sql.DB) error { + err := retry.Do(ctx, db, func(ctx context.Context, cc *sql.Conn) error { + err := dropTableIfExists(ctx, cc, "series") if err != nil { _, _ = fmt.Fprintf(os.Stdout, "warn: drop series table failed: %v\n", err) } diff --git a/examples/basic/gorm/models.go b/examples/basic/gorm/models.go index 8b2b05d64..7804df52a 100644 --- a/examples/basic/gorm/models.go +++ b/examples/basic/gorm/models.go @@ -17,7 +17,7 @@ type Series struct { Seasons []Season } -func (s *Series) BeforeCreate(_ *gorm.DB) (err error) { +func (s *Series) BeforeCreate(_ *gorm.DB) error { id, err := uuid.NewUUID() if err != nil { return err @@ -27,7 +27,7 @@ func (s *Series) BeforeCreate(_ *gorm.DB) (err error) { s.Seasons[i].SeriesID = s.ID } - return + return err } type Season struct { @@ -40,7 +40,7 @@ type Season struct { Episodes []Episode } -func (s *Season) BeforeCreate(_ *gorm.DB) (err error) { +func (s *Season) BeforeCreate(_ *gorm.DB) error { id, err := uuid.NewUUID() if err != nil { return err @@ -50,7 +50,7 @@ func (s *Season) BeforeCreate(_ *gorm.DB) (err error) { s.Episodes[i].SeasonID = s.ID } - return + return err } type Episode struct { @@ -60,12 +60,12 @@ type Episode struct { AirDate time.Time `gorm:"column:air_date"` } -func (e *Episode) BeforeCreate(_ *gorm.DB) (err error) { +func (e *Episode) BeforeCreate(_ *gorm.DB) error { id, err := uuid.NewUUID() if err != nil { return err } e.ID = id.String() - return + return err } diff --git a/examples/basic/native/series.go b/examples/basic/native/series.go index 625c5967e..3b19a05d6 100644 --- a/examples/basic/native/series.go +++ b/examples/basic/native/series.go @@ -70,10 +70,13 @@ SELECT FROM AS_TABLE($episodesData); `)) -func readTable(ctx context.Context, c table.Client, path string) (err error) { - var res result.StreamResult +func readTable(ctx context.Context, c table.Client, path string) error { + var ( + res result.StreamResult + err error + ) err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { res, err = s.StreamReadTable(ctx, path, options.ReadOrdered(), options.ReadColumn("series_id"), @@ -81,7 +84,7 @@ func readTable(ctx context.Context, c table.Client, path string) (err error) { options.ReadColumn("release_date"), ) - return + return err }, ) if err != nil { @@ -138,13 +141,16 @@ func readTable(ctx context.Context, c table.Client, path string) (err error) { return res.Err() } -func describeTableOptions(ctx context.Context, c table.Client) (err error) { - var desc options.TableOptionsDescription +func describeTableOptions(ctx context.Context, c table.Client) error { + var ( + desc options.TableOptionsDescription + err error + ) err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { desc, err = s.DescribeTableOptions(ctx) - return + return err }, ) if err != nil { @@ -191,7 +197,7 @@ func describeTableOptions(ctx context.Context, c table.Client) (err error) { return nil } -func selectSimple(ctx context.Context, c table.Client, prefix string) (err error) { +func selectSimple(ctx context.Context, c table.Client, prefix string) error { query := render( template.Must(template.New("").Parse(` PRAGMA TablePathPrefix("{{ .TablePathPrefix }}"); @@ -220,9 +226,12 @@ func selectSimple(ctx context.Context, c table.Client, prefix string) (err error ), table.CommitTx(), ) - var res result.Result + var ( + res result.Result + err error + ) err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { _, res, err = s.Execute(ctx, readTx, query, table.NewQueryParameters( table.ValueParam("$seriesID", types.Uint64Value(1)), @@ -230,7 +239,7 @@ func selectSimple(ctx context.Context, c table.Client, prefix string) (err error options.WithCollectStatsModeBasic(), ) - return + return err }, ) if err != nil { @@ -266,7 +275,7 @@ func selectSimple(ctx context.Context, c table.Client, prefix string) (err error return res.Err() } -func scanQuerySelect(ctx context.Context, c table.Client, prefix string) (err error) { +func scanQuerySelect(ctx context.Context, c table.Client, prefix string) error { query := render( template.Must(template.New("").Parse(` PRAGMA TablePathPrefix("{{ .TablePathPrefix }}"); @@ -327,7 +336,8 @@ func scanQuerySelect(ctx context.Context, c table.Client, prefix string) (err er ) } -func fillTablesWithData(ctx context.Context, c table.Client, prefix string) (err error) { +func fillTablesWithData(ctx context.Context, c table.Client, prefix string) error { + var err error writeTx := table.TxControl( table.BeginTx( table.WithSerializableReadWrite(), @@ -335,7 +345,7 @@ func fillTablesWithData(ctx context.Context, c table.Client, prefix string) (err table.CommitTx(), ) err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { _, _, err = s.Execute(ctx, writeTx, render(fill, templateConfig{ TablePathPrefix: prefix, }), table.NewQueryParameters( @@ -351,8 +361,8 @@ func fillTablesWithData(ctx context.Context, c table.Client, prefix string) (err return err } -func createTables(ctx context.Context, c table.Client, prefix string) (err error) { - err = c.Do(ctx, +func createTables(ctx context.Context, c table.Client, prefix string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path.Join(prefix, "series"), options.WithColumn("series_id", types.Optional(types.TypeUint64)), @@ -403,8 +413,8 @@ func createTables(ctx context.Context, c table.Client, prefix string) (err error return nil } -func describeTable(ctx context.Context, c table.Client, path string) (err error) { - err = c.Do(ctx, +func describeTable(ctx context.Context, c table.Client, path string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { desc, err := s.DescribeTable(ctx, path) if err != nil { @@ -419,7 +429,7 @@ func describeTable(ctx context.Context, c table.Client, path string) (err error) }, ) - return + return err } func render(t *template.Template, data interface{}) string { diff --git a/examples/basic/xorm/data.go b/examples/basic/xorm/data.go index c6cfbb3fe..966886acc 100644 --- a/examples/basic/xorm/data.go +++ b/examples/basic/xorm/data.go @@ -35,11 +35,16 @@ func episodeData(seasonID, episodeID, title string, date time.Time) *Episodes { } } -func getData() (series []*Series, seasons []*Seasons, episodes []*Episodes) { +func getData() ([]*Series, []*Seasons, []*Episodes) { + var ( + series = make([]*Series, 0) + seasons = make([]*Seasons, 0) + episodes = make([]*Episodes, 0) + ) for seriesID, fill := range map[string]func(seriesID string) ( - seriesData *Series, - seasons []*Seasons, - episodes []*Episodes, + *Series, + []*Seasons, + []*Episodes, ){ uuid.New().String(): getDataForITCrowd, uuid.New().String(): getDataForSiliconValley, @@ -50,15 +55,19 @@ func getData() (series []*Series, seasons []*Seasons, episodes []*Episodes) { episodes = append(episodes, episodesData...) } - return + return series, seasons, episodes } -func getDataForITCrowd(seriesID string) (series *Series, seasons []*Seasons, episodes []*Episodes) { - series = seriesData( - seriesID, date("2006-02-03"), "IT Crowd", ""+ - "The IT Crowd is a British sitcom produced by Channel 4, written by Graham Linehan, produced by "+ - "Ash Atalla and starring Chris O'Dowd, Richard Ayoade, Katherine Parkinson, and Matt Berry.", - "", // NULL comment. +func getDataForITCrowd(seriesID string) (*Series, []*Seasons, []*Episodes) { + var ( + series = seriesData( + seriesID, date("2006-02-03"), "IT Crowd", ""+ + "The IT Crowd is a British sitcom produced by Channel 4, written by Graham Linehan, produced by "+ + "Ash Atalla and starring Chris O'Dowd, Richard Ayoade, Katherine Parkinson, and Matt Berry.", + "", // NULL comment. + ) + seasons = make([]*Seasons, 0) + episodes = make([]*Episodes, 0) ) for _, season := range []*struct { title string @@ -117,12 +126,16 @@ func getDataForITCrowd(seriesID string) (series *Series, seasons []*Seasons, epi return series, seasons, episodes } -func getDataForSiliconValley(seriesID string) (series *Series, seasons []*Seasons, episodes []*Episodes) { - series = seriesData( - seriesID, date("2014-04-06"), "Silicon Valley", ""+ - "Silicon Valley is an American comedy television series created by Mike Judge, John Altschuler and "+ - "Dave Krinsky. The series focuses on five young men who founded a startup company in Silicon Valley.", - "Some comment here", +func getDataForSiliconValley(seriesID string) (*Series, []*Seasons, []*Episodes) { + var ( + series = seriesData( + seriesID, date("2014-04-06"), "Silicon Valley", ""+ + "Silicon Valley is an American comedy television series created by Mike Judge, John Altschuler and "+ + "Dave Krinsky. The series focuses on five young men who founded a startup company in Silicon Valley.", + "Some comment here", + ) + seasons = make([]*Seasons, 0) + episodes = make([]*Episodes, 0) ) for _, season := range []*struct { title string diff --git a/examples/ddl/ddl.go b/examples/ddl/ddl.go index 9e0d4725a..7670f055d 100644 --- a/examples/ddl/ddl.go +++ b/examples/ddl/ddl.go @@ -67,10 +67,10 @@ ALTER TABLE small_table3 SET (TTL = Interval("PT3H") ON d); ` ) -func executeQuery(ctx context.Context, c table.Client, prefix, query string) (err error) { - err = c.Do(ctx, +func executeQuery(ctx context.Context, c table.Client, prefix, query string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { - err = s.ExecuteSchemeQuery(ctx, fmt.Sprintf(query, prefix)) + err := s.ExecuteSchemeQuery(ctx, fmt.Sprintf(query, prefix)) return err }, diff --git a/examples/decimal/main.go b/examples/decimal/main.go index 8e77c2ce1..44abdd2bf 100644 --- a/examples/decimal/main.go +++ b/examples/decimal/main.go @@ -12,6 +12,7 @@ import ( ydb "github.com/ydb-platform/ydb-go-sdk/v3" "github.com/ydb-platform/ydb-go-sdk/v3/table" "github.com/ydb-platform/ydb-go-sdk/v3/table/options" + "github.com/ydb-platform/ydb-go-sdk/v3/table/result" "github.com/ydb-platform/ydb-go-sdk/v3/table/types" ) @@ -70,7 +71,7 @@ func main() { tablePath := path.Join(prefix, "decimals") err = db.Table().Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, tablePath, options.WithColumn("id", types.Optional(types.TypeUint32)), options.WithColumn("value", types.Optional(types.DefaultDecimal)), @@ -83,7 +84,7 @@ func main() { } err = db.Table().Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { txc := table.TxControl( table.BeginTx( table.WithSerializableReadWrite(), @@ -110,7 +111,8 @@ func main() { return err } - _, res, err := s.Execute(ctx, txc, render(readQuery, templateConfig{ + var res result.Result + _, res, err = s.Execute(ctx, txc, render(readQuery, templateConfig{ TablePathPrefix: prefix, }), nil) if err != nil { diff --git a/examples/describe/main.go b/examples/describe/main.go index 93fb00333..4db1f3ad1 100644 --- a/examples/describe/main.go +++ b/examples/describe/main.go @@ -99,7 +99,7 @@ func main() { func list(ctx context.Context, db *ydb.Driver, t *template.Template, p string) { var dir scheme.Directory var err error - err = retry.Retry(ctx, func(ctx context.Context) (err error) { + err = retry.Retry(ctx, func(ctx context.Context) error { dir, err = db.Scheme().ListDirectory(ctx, p) return err @@ -121,7 +121,7 @@ func list(ctx context.Context, db *ydb.Driver, t *template.Template, p string) { case scheme.EntryTable: var desc options.Description - err = db.Table().Do(ctx, func(ctx context.Context, s table.Session) (err error) { + err = db.Table().Do(ctx, func(ctx context.Context, s table.Session) error { desc, err = s.DescribeTable(ctx, pt) return err diff --git a/examples/pagination/cities.go b/examples/pagination/cities.go index 620e9ee72..b75f9f987 100644 --- a/examples/pagination/cities.go +++ b/examples/pagination/cities.go @@ -6,6 +6,7 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/table" "github.com/ydb-platform/ydb-go-sdk/v3/table/options" + "github.com/ydb-platform/ydb-go-sdk/v3/table/result" "github.com/ydb-platform/ydb-go-sdk/v3/table/result/named" "github.com/ydb-platform/ydb-go-sdk/v3/table/types" ) @@ -18,10 +19,13 @@ func selectPaging( lastNum *uint, lastCity *string, ) ( - empty bool, - err error, + bool, + error, ) { - query := fmt.Sprintf(` + var ( + empty bool + err error + query = fmt.Sprintf(` PRAGMA TablePathPrefix("%v"); DECLARE $limit AS Uint64; @@ -49,12 +53,14 @@ func selectPaging( SELECT * FROM $union ORDER BY city, number LIMIT $limit; `, prefix) + ) readTx := table.TxControl(table.BeginTx(table.WithOnlineReadOnly()), table.CommitTx()) err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, res, err := s.Execute(ctx, readTx, query, + func(ctx context.Context, s table.Session) error { + var res result.Result + _, res, err = s.Execute(ctx, readTx, query, table.NewQueryParameters( table.ValueParam("$limit", types.Uint64Value(uint64(limit))), table.ValueParam("$lastCity", types.TextValue(*lastCity)), @@ -92,7 +98,7 @@ func selectPaging( return empty, err } -func fillTableWithData(ctx context.Context, c table.Client, prefix string) (err error) { +func fillTableWithData(ctx context.Context, c table.Client, prefix string) error { query := fmt.Sprintf(` PRAGMA TablePathPrefix("%v"); @@ -110,9 +116,9 @@ func fillTableWithData(ctx context.Context, c table.Client, prefix string) (err writeTx := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx()) - err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, _, err = s.Execute(ctx, writeTx, query, table.NewQueryParameters( + err := c.Do(ctx, + func(ctx context.Context, s table.Session) error { + _, _, err := s.Execute(ctx, writeTx, query, table.NewQueryParameters( table.ValueParam("$schoolsData", getSchoolData()), )) @@ -122,8 +128,8 @@ func fillTableWithData(ctx context.Context, c table.Client, prefix string) (err return err } -func createTable(ctx context.Context, c table.Client, path string) (err error) { - err = c.Do(ctx, +func createTable(ctx context.Context, c table.Client, path string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path, options.WithColumn("city", types.Optional(types.TypeUTF8)), diff --git a/examples/read_table/orders.go b/examples/read_table/orders.go index c9e007193..6887ff25c 100644 --- a/examples/read_table/orders.go +++ b/examples/read_table/orders.go @@ -21,8 +21,8 @@ type row struct { description string } -func dropTableIfExists(ctx context.Context, c table.Client, path string) (err error) { - err = c.Do(ctx, +func dropTableIfExists(ctx context.Context, c table.Client, path string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.DropTable(ctx, path) }, @@ -35,7 +35,7 @@ func dropTableIfExists(ctx context.Context, c table.Client, path string) (err er return nil } -func createTable(ctx context.Context, c table.Client, path string) (err error) { +func createTable(ctx context.Context, c table.Client, path string) error { return c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path, @@ -85,10 +85,10 @@ type templateConfig struct { TablePathPrefix string } -func fillTable(ctx context.Context, c table.Client, prefix string) (err error) { +func fillTable(ctx context.Context, c table.Client, prefix string) error { return c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, _, err = s.Execute( + func(ctx context.Context, s table.Session) error { + _, _, err := s.Execute( ctx, table.TxControl( table.BeginTx( @@ -138,9 +138,9 @@ func order(customerID, orderID uint64, description, date string) types.Value { ) } -func readTable(ctx context.Context, c table.Client, path string, opts ...options.ReadTableOption) (err error) { - err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { +func readTable(ctx context.Context, c table.Client, path string, opts ...options.ReadTableOption) error { + err := c.Do(ctx, + func(ctx context.Context, s table.Session) error { res, err := s.StreamReadTable(ctx, path, opts...) if err != nil { return err diff --git a/examples/serverless/healthcheck/service.go b/examples/serverless/healthcheck/service.go index 7e5ecb486..c257ee7e6 100644 --- a/examples/serverless/healthcheck/service.go +++ b/examples/serverless/healthcheck/service.go @@ -27,7 +27,11 @@ type service struct { var once sync.Once -func getService(ctx context.Context, dsn string, opts ...ydb.Option) (s *service, err error) { +func getService(ctx context.Context, dsn string, opts ...ydb.Option) (*service, error) { + var ( + s *service + err error + ) once.Do(func() { s = &service{ client: &http.Client{ @@ -93,7 +97,7 @@ func (s *service) createTableIfNotExists(ctx context.Context) error { ) } -func (s *service) ping(ctx context.Context, path string) (code int32, err error) { +func (s *service) ping(ctx context.Context, path string) (int32, error) { uri, err := url.Parse(path) if err != nil { return -1, err @@ -153,7 +157,7 @@ func (s *service) check(ctx context.Context, urls []string) error { return s.upsertRows(ctx, rows) } -func (s *service) upsertRows(ctx context.Context, rows []row) (err error) { +func (s *service) upsertRows(ctx context.Context, rows []row) error { values := make([]types.Value, len(rows)) for i := range rows { values[i] = types.StructValue( @@ -169,9 +173,9 @@ func (s *service) upsertRows(ctx context.Context, rows []row) (err error) { }(rows[i].err))), ) } - err = s.db.Table().Do(ctx, - func(ctx context.Context, session table.Session) (err error) { - _, _, err = session.Execute(ctx, + err := s.db.Table().Do(ctx, + func(ctx context.Context, session table.Session) error { + _, _, err := session.Execute(ctx, table.SerializableReadWriteTxControl(table.CommitTx()), fmt.Sprintf(` PRAGMA TablePathPrefix("%s"); diff --git a/examples/serverless/url_shortener/service.go b/examples/serverless/url_shortener/service.go index b7a435458..254e20c40 100644 --- a/examples/serverless/url_shortener/service.go +++ b/examples/serverless/url_shortener/service.go @@ -83,7 +83,11 @@ type service struct { var once sync.Once -func getService(ctx context.Context, dsn string, opts ...ydb.Option) (s *service, err error) { +func getService(ctx context.Context, dsn string, opts ...ydb.Option) (*service, error) { + var ( + s *service + err error + ) once.Do(func() { var ( registry = prometheus.NewRegistry() @@ -182,7 +186,7 @@ func (s *service) Close(ctx context.Context) { _ = s.db.Close(ctx) } -func (s *service) createTable(ctx context.Context) (err error) { +func (s *service) createTable(ctx context.Context) error { query := render( template.Must(template.New("").Parse(` PRAGMA TablePathPrefix("{{ .TablePathPrefix }}"); @@ -208,8 +212,8 @@ func (s *service) createTable(ctx context.Context) (err error) { ) } -func (s *service) insertShort(ctx context.Context, url string) (h string, err error) { - h, err = hash(url) +func (s *service) insertShort(ctx context.Context, url string) (string, error) { + h, err := hash(url) if err != nil { return "", err } @@ -236,7 +240,7 @@ func (s *service) insertShort(ctx context.Context, url string) (h string, err er table.CommitTx(), ) err = s.db.Table().Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { _, _, err = s.Execute(ctx, writeTx, query, table.NewQueryParameters( table.ValueParam("$hash", types.TextValue(h)), @@ -245,14 +249,14 @@ func (s *service) insertShort(ctx context.Context, url string) (h string, err er options.WithCollectStatsModeBasic(), ) - return + return err }, ) return h, err } -func (s *service) selectLong(ctx context.Context, hash string) (url string, err error) { +func (s *service) selectLong(ctx context.Context, hash string) (string, error) { query := render( template.Must(template.New("").Parse(` PRAGMA TablePathPrefix("{{ .TablePathPrefix }}"); @@ -276,9 +280,12 @@ func (s *service) selectLong(ctx context.Context, hash string) (url string, err ), table.CommitTx(), ) - var res result.Result + var ( + res result.Result + err error + ) err = s.db.Table().Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { _, res, err = s.Execute(ctx, readTx, query, table.NewQueryParameters( table.ValueParam("$hash", types.TextValue(hash)), diff --git a/examples/topic/cdc-fill-and-read/tables.go b/examples/topic/cdc-fill-and-read/tables.go index a522bdf11..dd95d6a3e 100644 --- a/examples/topic/cdc-fill-and-read/tables.go +++ b/examples/topic/cdc-fill-and-read/tables.go @@ -19,8 +19,8 @@ const ( interval = time.Second ) -func dropTableIfExists(ctx context.Context, c table.Client, path string) (err error) { - err = c.Do(ctx, +func dropTableIfExists(ctx context.Context, c table.Client, path string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.DropTable(ctx, path) }, @@ -33,8 +33,8 @@ func dropTableIfExists(ctx context.Context, c table.Client, path string) (err er return nil } -func createTable(ctx context.Context, c table.Client, prefix, tableName string) (err error) { - err = c.Do(ctx, +func createTable(ctx context.Context, c table.Client, prefix, tableName string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path.Join(prefix, tableName), options.WithColumn("id", types.Optional(types.TypeUint64)), diff --git a/examples/topic/topicreader/stubs.go b/examples/topic/topicreader/stubs.go index ef64775a3..bc382e96b 100644 --- a/examples/topic/topicreader/stubs.go +++ b/examples/topic/topicreader/stubs.go @@ -14,7 +14,7 @@ func externalSystemCommit(ctx context.Context, topic string, partition, offset i panic("example stub") } -func externalSystemLock(ctx context.Context, topic string, partition int64) (err error) { +func externalSystemLock(ctx context.Context, topic string, partition int64) error { panic("example stub") } diff --git a/examples/topic/topicreader/topicreader_advanced.go b/examples/topic/topicreader/topicreader_advanced.go index 962f4700b..b627f7cab 100644 --- a/examples/topic/topicreader/topicreader_advanced.go +++ b/examples/topic/topicreader/topicreader_advanced.go @@ -72,9 +72,10 @@ func OwnReadProgressStorage(ctx context.Context, db *ydb.Driver) { ctx context.Context, req topicoptions.GetPartitionStartOffsetRequest, ) ( - res topicoptions.GetPartitionStartOffsetResponse, - err error, + topicoptions.GetPartitionStartOffsetResponse, + error, ) { + var res topicoptions.GetPartitionStartOffsetResponse offset, err := readLastOffsetFromDB(ctx, req.Topic, req.PartitionID) res.StartFrom(offset) diff --git a/examples/topic/topicreader/topicreader_trace.go b/examples/topic/topicreader/topicreader_trace.go index 28ab11427..989ccaf3c 100644 --- a/examples/topic/topicreader/topicreader_trace.go +++ b/examples/topic/topicreader/topicreader_trace.go @@ -92,7 +92,8 @@ func PartitionStartStopHandlerAndOwnReadProgressStorage(ctx context.Context, db readStartPosition := func( ctx context.Context, req topicoptions.GetPartitionStartOffsetRequest, - ) (res topicoptions.GetPartitionStartOffsetResponse, err error) { + ) (topicoptions.GetPartitionStartOffsetResponse, error) { + var res topicoptions.GetPartitionStartOffsetResponse offset, err := readLastOffsetFromDB(ctx, req.Topic, req.PartitionID) res.StartFrom(offset) diff --git a/examples/ttl/series.go b/examples/ttl/series.go index a6e4753c3..988cb1182 100644 --- a/examples/ttl/series.go +++ b/examples/ttl/series.go @@ -54,9 +54,12 @@ func readExpiredBatchTransaction(ctx context.Context, c table.Client, prefix str readTx := table.TxControl(table.BeginTx(table.WithOnlineReadOnly()), table.CommitTx()) - var res result.Result - err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + var ( + res result.Result + err error + ) + err = c.Do(ctx, + func(ctx context.Context, s table.Session) error { _, res, err = s.Execute(ctx, readTx, query, table.NewQueryParameters( table.ValueParam("$timestamp", types.Uint64Value(timestamp)), table.ValueParam("$prev_timestamp", types.Uint64Value(prevTimestamp)), @@ -94,8 +97,8 @@ func deleteDocumentWithTimestamp(ctx context.Context, writeTx := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx()) err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, _, err = s.Execute(ctx, writeTx, query, table.NewQueryParameters( + func(ctx context.Context, s table.Session) error { + _, _, err := s.Execute(ctx, writeTx, query, table.NewQueryParameters( table.ValueParam("$doc_id", types.Uint64Value(lastDocID)), table.ValueParam("$timestamp", types.Uint64Value(timestamp)), )) @@ -107,14 +110,14 @@ func deleteDocumentWithTimestamp(ctx context.Context, return err } -func deleteExpired(ctx context.Context, c table.Client, prefix string, queue, timestamp uint64) (err error) { +func deleteExpired(ctx context.Context, c table.Client, prefix string, queue, timestamp uint64) error { fmt.Printf("> DeleteExpired from queue #%d:\n", queue) empty := false lastTimestamp := uint64(0) lastDocID := uint64(0) for !empty { - err = func() (err error) { // for isolate defer inside lambda + err := func() error { // for isolate defer inside lambda res, err := readExpiredBatchTransaction(ctx, c, prefix, queue, timestamp, lastTimestamp, lastDocID) if err != nil { return err @@ -169,7 +172,7 @@ func readDocument(ctx context.Context, c table.Client, prefix, url string) error readTx := table.TxControl(table.BeginTx(table.WithOnlineReadOnly()), table.CommitTx()) err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { _, res, err := s.Execute(ctx, readTx, query, table.NewQueryParameters( table.ValueParam("$url", types.TextValue(url)), )) @@ -236,8 +239,8 @@ func addDocument(ctx context.Context, c table.Client, prefix, url, html string, writeTx := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx()) err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, _, err = s.Execute(ctx, writeTx, query, table.NewQueryParameters( + func(ctx context.Context, s table.Session) error { + _, _, err := s.Execute(ctx, writeTx, query, table.NewQueryParameters( table.ValueParam("$url", types.TextValue(url)), table.ValueParam("$html", types.TextValue(html)), table.ValueParam("$timestamp", types.Uint64Value(timestamp)), @@ -250,8 +253,8 @@ func addDocument(ctx context.Context, c table.Client, prefix, url, html string, return err } -func createTables(ctx context.Context, c table.Client, prefix string) (err error) { - err = c.Do(ctx, +func createTables(ctx context.Context, c table.Client, prefix string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path.Join(prefix, "documents"), options.WithColumn("doc_id", types.Optional(types.TypeUint64)), diff --git a/examples/ttl_readtable/series.go b/examples/ttl_readtable/series.go index 0ed5c33a3..bc2f9258d 100644 --- a/examples/ttl_readtable/series.go +++ b/examples/ttl_readtable/series.go @@ -54,8 +54,8 @@ func deleteExpiredDocuments(ctx context.Context, c table.Client, prefix string, writeTx := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx()) err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, _, err = s.Execute(ctx, writeTx, query, + func(ctx context.Context, s table.Session) error { + _, _, err := s.Execute(ctx, writeTx, query, table.NewQueryParameters( table.ValueParam("$keys", keys), table.ValueParam("$timestamp", types.Uint64Value(timestamp)), @@ -74,9 +74,12 @@ func deleteExpiredRange(ctx context.Context, c table.Client, prefix string, time ) error { fmt.Printf("> DeleteExpiredRange: %+v\n", keyRange) - var res result.StreamResult - err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + var ( + res result.StreamResult + err error + ) + err = c.Do(ctx, + func(ctx context.Context, s table.Session) error { res, err = s.StreamReadTable(ctx, path.Join(prefix, "documents"), options.ReadKeyRange(keyRange), options.ReadColumn("doc_id"), @@ -136,9 +139,12 @@ func deleteExpiredRange(ctx context.Context, c table.Client, prefix string, time func deleteExpired(ctx context.Context, c table.Client, prefix string, timestamp uint64) error { fmt.Printf("> DeleteExpired: timestamp: %v:\n", timestamp) - var res options.Description - err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + var ( + res options.Description + err error + ) + err = c.Do(ctx, + func(ctx context.Context, s table.Session) error { res, err = s.DescribeTable(ctx, path.Join(prefix, "documents"), options.WithShardKeyBounds()) return err @@ -176,9 +182,12 @@ func readDocument(ctx context.Context, c table.Client, prefix, url string) error readTx := table.TxControl(table.BeginTx(table.WithOnlineReadOnly()), table.CommitTx()) - var res result.Result - err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + var ( + res result.Result + err error + ) + err = c.Do(ctx, + func(ctx context.Context, s table.Session) error { _, res, err = s.Execute(ctx, readTx, query, table.NewQueryParameters( table.ValueParam("$url", types.TextValue(url))), ) @@ -239,8 +248,8 @@ func addDocument(ctx context.Context, c table.Client, prefix, url, html string, writeTx := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx()) err := c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, _, err = s.Execute(ctx, writeTx, query, table.NewQueryParameters( + func(ctx context.Context, s table.Session) error { + _, _, err := s.Execute(ctx, writeTx, query, table.NewQueryParameters( table.ValueParam("$url", types.TextValue(url)), table.ValueParam("$html", types.TextValue(html)), table.ValueParam("$timestamp", types.Uint64Value(timestamp))), @@ -253,8 +262,8 @@ func addDocument(ctx context.Context, c table.Client, prefix, url, html string, return err } -func createTables(ctx context.Context, c table.Client, prefix string) (err error) { - err = c.Do(ctx, +func createTables(ctx context.Context, c table.Client, prefix string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path.Join(prefix, "documents"), options.WithColumn("doc_id", types.Optional(types.TypeUint64)), diff --git a/internal/allocator/allocator.go b/internal/allocator/allocator.go index 6c55c51b4..272828173 100644 --- a/internal/allocator/allocator.go +++ b/internal/allocator/allocator.go @@ -53,7 +53,7 @@ type ( } ) -func New() (v *Allocator) { +func New() *Allocator { return allocatorPool.Get() } @@ -107,8 +107,8 @@ type boolAllocator struct { allocations []*Ydb.Value_BoolValue } -func (a *boolAllocator) Bool() (v *Ydb.Value_BoolValue) { - v = boolPool.Get() +func (a *boolAllocator) Bool() *Ydb.Value_BoolValue { + v := boolPool.Get() a.allocations = append(a.allocations, v) return v @@ -126,8 +126,8 @@ type bytesAllocator struct { allocations []*Ydb.Value_BytesValue } -func (a *bytesAllocator) Bytes() (v *Ydb.Value_BytesValue) { - v = bytesPool.Get() +func (a *bytesAllocator) Bytes() *Ydb.Value_BytesValue { + v := bytesPool.Get() a.allocations = append(a.allocations, v) return v @@ -145,8 +145,8 @@ type decimalAllocator struct { allocations []*Ydb.DecimalType } -func (a *decimalAllocator) Decimal() (v *Ydb.DecimalType) { - v = decimalPool.Get() +func (a *decimalAllocator) Decimal() *Ydb.DecimalType { + v := decimalPool.Get() a.allocations = append(a.allocations, v) return v @@ -164,8 +164,8 @@ type dictAllocator struct { allocations []*Ydb.DictType } -func (a *dictAllocator) Dict() (v *Ydb.DictType) { - v = dictPool.Get() +func (a *dictAllocator) Dict() *Ydb.DictType { + v := dictPool.Get() a.allocations = append(a.allocations, v) return v @@ -183,8 +183,8 @@ type doubleAllocator struct { allocations []*Ydb.Value_DoubleValue } -func (a *doubleAllocator) Double() (v *Ydb.Value_DoubleValue) { - v = doublePool.Get() +func (a *doubleAllocator) Double() *Ydb.Value_DoubleValue { + v := doublePool.Get() a.allocations = append(a.allocations, v) return v @@ -202,8 +202,8 @@ type floatAllocator struct { allocations []*Ydb.Value_FloatValue } -func (a *floatAllocator) Float() (v *Ydb.Value_FloatValue) { - v = floatPool.Get() +func (a *floatAllocator) Float() *Ydb.Value_FloatValue { + v := floatPool.Get() a.allocations = append(a.allocations, v) return v @@ -221,8 +221,8 @@ type int32Allocator struct { allocations []*Ydb.Value_Int32Value } -func (a *int32Allocator) Int32() (v *Ydb.Value_Int32Value) { - v = int32Pool.Get() +func (a *int32Allocator) Int32() *Ydb.Value_Int32Value { + v := int32Pool.Get() a.allocations = append(a.allocations, v) return v @@ -240,8 +240,8 @@ type int64Allocator struct { allocations []*Ydb.Value_Int64Value } -func (a *int64Allocator) Int64() (v *Ydb.Value_Int64Value) { - v = int64Pool.Get() +func (a *int64Allocator) Int64() *Ydb.Value_Int64Value { + v := int64Pool.Get() a.allocations = append(a.allocations, v) return v @@ -259,8 +259,8 @@ type listAllocator struct { allocations []*Ydb.ListType } -func (a *listAllocator) List() (v *Ydb.ListType) { - v = listPool.Get() +func (a *listAllocator) List() *Ydb.ListType { + v := listPool.Get() a.allocations = append(a.allocations, v) return v @@ -278,8 +278,8 @@ type low128Allocator struct { allocations []*Ydb.Value_Low_128 } -func (a *low128Allocator) Low128() (v *Ydb.Value_Low_128) { - v = low128Pool.Get() +func (a *low128Allocator) Low128() *Ydb.Value_Low_128 { + v := low128Pool.Get() a.allocations = append(a.allocations, v) return v @@ -297,8 +297,8 @@ type nestedAllocator struct { allocations []*Ydb.Value_NestedValue } -func (a *nestedAllocator) Nested() (v *Ydb.Value_NestedValue) { - v = nestedPool.Get() +func (a *nestedAllocator) Nested() *Ydb.Value_NestedValue { + v := nestedPool.Get() a.allocations = append(a.allocations, v) return v @@ -316,8 +316,8 @@ type nullFlagAllocator struct { allocations []*Ydb.Value_NullFlagValue } -func (a *nullFlagAllocator) NullFlag() (v *Ydb.Value_NullFlagValue) { - v = nullFlagPool.Get() +func (a *nullFlagAllocator) NullFlag() *Ydb.Value_NullFlagValue { + v := nullFlagPool.Get() a.allocations = append(a.allocations, v) return v @@ -335,8 +335,8 @@ type optionalAllocator struct { allocations []*Ydb.OptionalType } -func (a *optionalAllocator) Optional() (v *Ydb.OptionalType) { - v = optionalPool.Get() +func (a *optionalAllocator) Optional() *Ydb.OptionalType { + v := optionalPool.Get() a.allocations = append(a.allocations, v) return v @@ -354,8 +354,8 @@ type pairAllocator struct { allocations []*Ydb.ValuePair } -func (a *pairAllocator) Pair() (v *Ydb.ValuePair) { - v = pairPool.Get() +func (a *pairAllocator) Pair() *Ydb.ValuePair { + v := pairPool.Get() a.allocations = append(a.allocations, v) return v @@ -373,8 +373,8 @@ type structAllocator struct { allocations []*Ydb.StructType } -func (a *structAllocator) Struct() (v *Ydb.StructType) { - v = structPool.Get() +func (a *structAllocator) Struct() *Ydb.StructType { + v := structPool.Get() if cap(v.Members) <= 0 { v.Members = make([]*Ydb.StructMember, 0, 10) } @@ -400,8 +400,8 @@ type structMemberAllocator struct { allocations []*Ydb.StructMember } -func (a *structMemberAllocator) StructMember() (v *Ydb.StructMember) { - v = structMemberPool.Get() +func (a *structMemberAllocator) StructMember() *Ydb.StructMember { + v := structMemberPool.Get() a.allocations = append(a.allocations, v) return v @@ -419,8 +419,8 @@ type textAllocator struct { allocations []*Ydb.Value_TextValue } -func (a *textAllocator) Text() (v *Ydb.Value_TextValue) { - v = textPool.Get() +func (a *textAllocator) Text() *Ydb.Value_TextValue { + v := textPool.Get() a.allocations = append(a.allocations, v) return v @@ -438,8 +438,8 @@ type tupleAllocator struct { allocations []*Ydb.TupleType } -func (a *tupleAllocator) Tuple() (v *Ydb.TupleType) { - v = tuplePool.Get() +func (a *tupleAllocator) Tuple() *Ydb.TupleType { + v := tuplePool.Get() a.allocations = append(a.allocations, v) return v @@ -462,8 +462,8 @@ type typeDecimalAllocator struct { allocations []*Ydb.Type_DecimalType } -func (a *typeDecimalAllocator) TypeDecimal() (v *Ydb.Type_DecimalType) { - v = typeDecimalPool.Get() +func (a *typeDecimalAllocator) TypeDecimal() *Ydb.Type_DecimalType { + v := typeDecimalPool.Get() a.allocations = append(a.allocations, v) return v @@ -481,8 +481,8 @@ type typeDictAllocator struct { allocations []*Ydb.Type_DictType } -func (a *typeDictAllocator) TypeDict() (v *Ydb.Type_DictType) { - v = typeDictPool.Get() +func (a *typeDictAllocator) TypeDict() *Ydb.Type_DictType { + v := typeDictPool.Get() a.allocations = append(a.allocations, v) return v @@ -500,8 +500,8 @@ type typeEmptyListAllocator struct { allocations []*Ydb.Type_EmptyListType } -func (a *typeEmptyListAllocator) TypeEmptyList() (v *Ydb.Type_EmptyListType) { - v = typeEmptyListPool.Get() +func (a *typeEmptyListAllocator) TypeEmptyList() *Ydb.Type_EmptyListType { + v := typeEmptyListPool.Get() a.allocations = append(a.allocations, v) return v @@ -519,8 +519,8 @@ type typeEmptyDictAllocator struct { allocations []*Ydb.Type_EmptyDictType } -func (a *typeEmptyDictAllocator) TypeEmptyDict() (v *Ydb.Type_EmptyDictType) { - v = typeEmptyDictPool.Get() +func (a *typeEmptyDictAllocator) TypeEmptyDict() *Ydb.Type_EmptyDictType { + v := typeEmptyDictPool.Get() a.allocations = append(a.allocations, v) return v @@ -538,8 +538,8 @@ type typeAllocator struct { allocations []*Ydb.Type } -func (a *typeAllocator) Type() (v *Ydb.Type) { - v = typePool.Get() +func (a *typeAllocator) Type() *Ydb.Type { + v := typePool.Get() a.allocations = append(a.allocations, v) return v @@ -557,8 +557,8 @@ type typeListAllocator struct { allocations []*Ydb.Type_ListType } -func (a *typeListAllocator) TypeList() (v *Ydb.Type_ListType) { - v = typeListPool.Get() +func (a *typeListAllocator) TypeList() *Ydb.Type_ListType { + v := typeListPool.Get() a.allocations = append(a.allocations, v) return v @@ -576,8 +576,8 @@ type typeOptionalAllocator struct { allocations []*Ydb.Type_OptionalType } -func (a *typeOptionalAllocator) TypeOptional() (v *Ydb.Type_OptionalType) { - v = typeOptionalPool.Get() +func (a *typeOptionalAllocator) TypeOptional() *Ydb.Type_OptionalType { + v := typeOptionalPool.Get() a.allocations = append(a.allocations, v) return v @@ -595,8 +595,8 @@ type typeStructAllocator struct { allocations []*Ydb.Type_StructType } -func (a *typeStructAllocator) TypeStruct() (v *Ydb.Type_StructType) { - v = typeStructPool.Get() +func (a *typeStructAllocator) TypeStruct() *Ydb.Type_StructType { + v := typeStructPool.Get() a.allocations = append(a.allocations, v) return v @@ -614,8 +614,8 @@ type typeTupleAllocator struct { allocations []*Ydb.Type_TupleType } -func (a *typeTupleAllocator) TypeTuple() (v *Ydb.Type_TupleType) { - v = typeTuplePool.Get() +func (a *typeTupleAllocator) TypeTuple() *Ydb.Type_TupleType { + v := typeTuplePool.Get() a.allocations = append(a.allocations, v) return v @@ -633,8 +633,8 @@ type typeVariantAllocator struct { allocations []*Ydb.Type_VariantType } -func (a *typeVariantAllocator) TypeVariant() (v *Ydb.Type_VariantType) { - v = typeVariantPool.Get() +func (a *typeVariantAllocator) TypeVariant() *Ydb.Type_VariantType { + v := typeVariantPool.Get() a.allocations = append(a.allocations, v) return v @@ -652,8 +652,8 @@ type typedValueAllocator struct { allocations []*Ydb.TypedValue } -func (a *typedValueAllocator) TypedValue() (v *Ydb.TypedValue) { - v = typedValuePool.Get() +func (a *typedValueAllocator) TypedValue() *Ydb.TypedValue { + v := typedValuePool.Get() a.allocations = append(a.allocations, v) return v @@ -671,8 +671,8 @@ type uint32Allocator struct { allocations []*Ydb.Value_Uint32Value } -func (a *uint32Allocator) Uint32() (v *Ydb.Value_Uint32Value) { - v = uint32Pool.Get() +func (a *uint32Allocator) Uint32() *Ydb.Value_Uint32Value { + v := uint32Pool.Get() a.allocations = append(a.allocations, v) return v @@ -690,8 +690,8 @@ type uint64Allocator struct { allocations []*Ydb.Value_Uint64Value } -func (a *uint64Allocator) Uint64() (v *Ydb.Value_Uint64Value) { - v = uint64Pool.Get() +func (a *uint64Allocator) Uint64() *Ydb.Value_Uint64Value { + v := uint64Pool.Get() a.allocations = append(a.allocations, v) return v @@ -709,8 +709,8 @@ type valueAllocator struct { allocations []*Ydb.Value } -func (a *valueAllocator) Value() (v *Ydb.Value) { - v = valuePool.Get() +func (a *valueAllocator) Value() *Ydb.Value { + v := valuePool.Get() a.allocations = append(a.allocations, v) return v @@ -738,8 +738,8 @@ type variantAllocator struct { allocations []*Ydb.VariantType } -func (a *variantAllocator) Variant() (v *Ydb.VariantType) { - v = variantPool.Get() +func (a *variantAllocator) Variant() *Ydb.VariantType { + v := variantPool.Get() a.allocations = append(a.allocations, v) return v @@ -756,8 +756,8 @@ type variantStructItemsAllocator struct { allocations []*Ydb.VariantType_StructItems } -func (a *variantStructItemsAllocator) VariantStructItems() (v *Ydb.VariantType_StructItems) { - v = variantStructItemsPool.Get() +func (a *variantStructItemsAllocator) VariantStructItems() *Ydb.VariantType_StructItems { + v := variantStructItemsPool.Get() a.allocations = append(a.allocations, v) return v @@ -774,8 +774,8 @@ type variantTupleItemsAllocator struct { allocations []*Ydb.VariantType_TupleItems } -func (a *variantTupleItemsAllocator) VariantTupleItems() (v *Ydb.VariantType_TupleItems) { - v = variantTupleItemsPool.Get() +func (a *variantTupleItemsAllocator) VariantTupleItems() *Ydb.VariantType_TupleItems { + v := variantTupleItemsPool.Get() a.allocations = append(a.allocations, v) return v @@ -792,8 +792,8 @@ type tableExecuteQueryResultAllocator struct { allocations []*Ydb_Table.ExecuteQueryResult } -func (a *tableExecuteQueryResultAllocator) TableExecuteQueryResult() (v *Ydb_Table.ExecuteQueryResult) { - v = tableExecuteQueryResultPool.Get() +func (a *tableExecuteQueryResultAllocator) TableExecuteQueryResult() *Ydb_Table.ExecuteQueryResult { + v := tableExecuteQueryResultPool.Get() a.allocations = append(a.allocations, v) return v @@ -811,8 +811,8 @@ type tableExecuteQueryRequestAllocator struct { allocations []*Ydb_Table.ExecuteDataQueryRequest } -func (a *tableExecuteQueryRequestAllocator) TableExecuteDataQueryRequest() (v *Ydb_Table.ExecuteDataQueryRequest) { - v = tableExecuteDataQueryRequestPool.Get() +func (a *tableExecuteQueryRequestAllocator) TableExecuteDataQueryRequest() *Ydb_Table.ExecuteDataQueryRequest { + v := tableExecuteDataQueryRequestPool.Get() a.allocations = append(a.allocations, v) return v @@ -830,8 +830,8 @@ type tableQueryCachePolicyAllocator struct { allocations []*Ydb_Table.QueryCachePolicy } -func (a *tableQueryCachePolicyAllocator) TableQueryCachePolicy() (v *Ydb_Table.QueryCachePolicy) { - v = tableQueryCachePolicyPool.Get() +func (a *tableQueryCachePolicyAllocator) TableQueryCachePolicy() *Ydb_Table.QueryCachePolicy { + v := tableQueryCachePolicyPool.Get() a.allocations = append(a.allocations, v) return v @@ -849,8 +849,8 @@ type tableQueryAllocator struct { allocations []*Ydb_Table.Query } -func (a *tableQueryAllocator) TableQuery() (v *Ydb_Table.Query) { - v = tableQueryPool.Get() +func (a *tableQueryAllocator) TableQuery() *Ydb_Table.Query { + v := tableQueryPool.Get() a.allocations = append(a.allocations, v) return v @@ -868,8 +868,8 @@ type tableQueryYqlTextAllocator struct { allocations []*Ydb_Table.Query_YqlText } -func (a *tableQueryYqlTextAllocator) TableQueryYqlText(s string) (v *Ydb_Table.Query_YqlText) { - v = tableQueryYqlTextPool.Get() +func (a *tableQueryYqlTextAllocator) TableQueryYqlText(s string) *Ydb_Table.Query_YqlText { + v := tableQueryYqlTextPool.Get() v.YqlText = s a.allocations = append(a.allocations, v) @@ -887,8 +887,8 @@ type tableQueryIDAllocator struct { allocations []*Ydb_Table.Query_Id } -func (a *tableQueryIDAllocator) TableQueryID(id string) (v *Ydb_Table.Query_Id) { - v = tableQueryIDPool.Get() +func (a *tableQueryIDAllocator) TableQueryID(id string) *Ydb_Table.Query_Id { + v := tableQueryIDPool.Get() v.Id = id a.allocations = append(a.allocations, v) diff --git a/internal/backoff/backoff_test.go b/internal/backoff/backoff_test.go index 45cd7fd1e..f590d5822 100644 --- a/internal/backoff/backoff_test.go +++ b/internal/backoff/backoff_test.go @@ -10,7 +10,7 @@ import ( ) func TestDelays(t *testing.T) { - duration := func(s string) (d time.Duration) { + duration := func(s string) time.Duration { d, err := time.ParseDuration(s) if err != nil { panic(err) @@ -171,8 +171,8 @@ func TestFastSlowDelaysWithoutJitter(t *testing.T) { }{ { name: "FastBackoff", - backoff: func() (backoff logBackoff) { - backoff = Fast + backoff: func() logBackoff { + backoff := Fast backoff.jitterLimit = 1 return backoff @@ -193,8 +193,8 @@ func TestFastSlowDelaysWithoutJitter(t *testing.T) { }, { name: "SlowBackoff", - backoff: func() (backoff logBackoff) { - backoff = Slow + backoff: func() logBackoff { + backoff := Slow backoff.jitterLimit = 1 return backoff diff --git a/internal/balancer/balancer.go b/internal/balancer/balancer.go index 2ee0140e6..08b02f190 100644 --- a/internal/balancer/balancer.go +++ b/internal/balancer/balancer.go @@ -65,11 +65,11 @@ func (b *Balancer) OnUpdate(onApplyDiscoveredEndpoints func(ctx context.Context, }) } -func (b *Balancer) clusterDiscovery(ctx context.Context) (err error) { +func (b *Balancer) clusterDiscovery(ctx context.Context) error { return retry.Retry( repeater.WithEvent(ctx, repeater.EventInit), - func(childCtx context.Context) (err error) { - if err = b.clusterDiscoveryAttempt(childCtx); err != nil { + func(childCtx context.Context) error { + if err := b.clusterDiscoveryAttempt(childCtx); err != nil { if credentials.IsAccessError(err) { return credentials.AccessError("cluster discovery failed", err, credentials.WithEndpoint(b.driverConfig.Endpoint()), @@ -92,7 +92,7 @@ func (b *Balancer) clusterDiscovery(ctx context.Context) (err error) { ) } -func (b *Balancer) clusterDiscoveryAttempt(ctx context.Context) (err error) { +func (b *Balancer) clusterDiscoveryAttempt(ctx context.Context) error { var ( address = "ydb:///" + b.driverConfig.Endpoint() onDone = trace.DriverOnBalancerClusterDiscoveryAttempt( @@ -103,6 +103,7 @@ func (b *Balancer) clusterDiscoveryAttempt(ctx context.Context) (err error) { endpoints []endpoint.Endpoint localDC string cancel context.CancelFunc + err error ) defer func() { onDone(err) @@ -133,14 +134,14 @@ func (b *Balancer) clusterDiscoveryAttempt(ctx context.Context) (err error) { } func endpointsDiff(newestEndpoints []endpoint.Endpoint, previousConns []conn.Conn) ( - nodes []trace.EndpointInfo, - added []trace.EndpointInfo, - dropped []trace.EndpointInfo, + []trace.EndpointInfo, + []trace.EndpointInfo, + []trace.EndpointInfo, ) { - nodes = make([]trace.EndpointInfo, 0, len(newestEndpoints)) - added = make([]trace.EndpointInfo, 0, len(previousConns)) - dropped = make([]trace.EndpointInfo, 0, len(previousConns)) var ( + nodes = make([]trace.EndpointInfo, 0, len(newestEndpoints)) + added = make([]trace.EndpointInfo, 0, len(previousConns)) + dropped = make([]trace.EndpointInfo, 0, len(previousConns)) newestMap = make(map[string]struct{}, len(newestEndpoints)) previousMap = make(map[string]struct{}, len(previousConns)) ) @@ -208,7 +209,8 @@ func (b *Balancer) applyDiscoveredEndpoints(ctx context.Context, endpoints []end }) } -func (b *Balancer) Close(ctx context.Context) (err error) { +func (b *Balancer) Close(ctx context.Context) error { + var err error onDone := trace.DriverOnBalancerClose( b.driverConfig.Trace(), &ctx, stack.FunctionID(""), @@ -233,7 +235,7 @@ func New( driverConfig *config.Config, pool *conn.Pool, opts ...discoveryConfig.Option, -) (b *Balancer, finalErr error) { +) (*Balancer, error) { var ( onDone = trace.DriverOnBalancerInit( driverConfig.Trace(), &ctx, @@ -247,6 +249,8 @@ func New( discoveryConfig.WithSecure(driverConfig.Secure()), discoveryConfig.WithMeta(driverConfig.Meta()), )...) + b *Balancer + finalErr error ) defer func() { onDone(finalErr) @@ -311,8 +315,11 @@ func (b *Balancer) NewStream( desc *grpc.StreamDesc, method string, opts ...grpc.CallOption, -) (_ grpc.ClientStream, err error) { - var client grpc.ClientStream +) (grpc.ClientStream, error) { + var ( + client grpc.ClientStream + err error + ) err = b.wrapCall(ctx, func(ctx context.Context, cc conn.Conn) error { client, err = cc.NewStream(ctx, desc, method, opts...) @@ -325,7 +332,7 @@ func (b *Balancer) NewStream( return nil, err } -func (b *Balancer) wrapCall(ctx context.Context, f func(ctx context.Context, cc conn.Conn) error) (err error) { +func (b *Balancer) wrapCall(ctx context.Context, f func(ctx context.Context, cc conn.Conn) error) error { cc, err := b.getConn(ctx) if err != nil { return xerrors.WithStackTrace(err) @@ -371,7 +378,11 @@ func (b *Balancer) connections() *connectionsState { return b.connectionsState } -func (b *Balancer) getConn(ctx context.Context) (c conn.Conn, err error) { +func (b *Balancer) getConn(ctx context.Context) (conn.Conn, error) { + var ( + c conn.Conn + err error + ) onDone := trace.DriverOnBalancerChooseEndpoint( b.driverConfig.Trace(), &ctx, stack.FunctionID(""), diff --git a/internal/balancer/connections_state.go b/internal/balancer/connections_state.go index e9196ead7..e35dc55ed 100644 --- a/internal/balancer/connections_state.go +++ b/internal/balancer/connections_state.go @@ -43,7 +43,8 @@ func (s *connectionsState) PreferredCount() int { return len(s.prefer) } -func (s *connectionsState) GetConnection(ctx context.Context) (_ conn.Conn, failedCount int) { +func (s *connectionsState) GetConnection(ctx context.Context) (_ conn.Conn, failedCount int) { //nolint:nonamedreturns + // gocritic more important if err := ctx.Err(); err != nil { return nil, 0 } @@ -83,7 +84,8 @@ func (s *connectionsState) preferConnection(ctx context.Context) conn.Conn { return nil } -func (s *connectionsState) selectRandomConnection(conns []conn.Conn, allowBanned bool) (c conn.Conn, failedConns int) { +func (s *connectionsState) selectRandomConnection(conns []conn.Conn, allowBanned bool) (conn.Conn, int) { + var failedConns int connCount := len(conns) if connCount == 0 { // return for empty list need for prevent panic in fast path @@ -115,7 +117,8 @@ func (s *connectionsState) selectRandomConnection(conns []conn.Conn, allowBanned return nil, failedConns } -func connsToNodeIDMap(conns []conn.Conn) (nodes map[uint32]conn.Conn) { +func connsToNodeIDMap(conns []conn.Conn) map[uint32]conn.Conn { + var nodes map[uint32]conn.Conn if len(conns) == 0 { return nil } @@ -132,7 +135,8 @@ func sortPreferConnections( filter balancerConfig.Filter, info balancerConfig.Info, allowFallback bool, -) (prefer, fallback []conn.Conn) { +) ([]conn.Conn, []conn.Conn) { + var prefer, fallback []conn.Conn if filter == nil { return conns, nil } diff --git a/internal/balancer/ctx.go b/internal/balancer/ctx.go index 9b4aeb209..2d36ba3d7 100644 --- a/internal/balancer/ctx.go +++ b/internal/balancer/ctx.go @@ -14,8 +14,8 @@ func WithEndpoint(ctx context.Context, endpoint Endpoint) context.Context { return context.WithValue(ctx, ctxEndpointKey{}, endpoint) } -func ContextEndpoint(ctx context.Context) (e Endpoint, ok bool) { - if e, ok = ctx.Value(ctxEndpointKey{}).(Endpoint); ok { +func ContextEndpoint(ctx context.Context) (Endpoint, bool) { + if e, ok := ctx.Value(ctxEndpointKey{}).(Endpoint); ok { return e, true } diff --git a/internal/balancer/local_dc.go b/internal/balancer/local_dc.go index e764af7d8..965acc758 100644 --- a/internal/balancer/local_dc.go +++ b/internal/balancer/local_dc.go @@ -135,7 +135,7 @@ func detectLocalDC(ctx context.Context, endpoints []endpoint.Endpoint) (string, return "", err } -func extractHostPort(address string) (host, port string, _ error) { +func extractHostPort(address string) (string, string, error) { if !strings.Contains(address, "://") { address = "stub://" + address } @@ -144,7 +144,7 @@ func extractHostPort(address string) (host, port string, _ error) { if err != nil { return "", "", xerrors.WithStackTrace(err) } - host, port, err = net.SplitHostPort(u.Host) + host, port, err := net.SplitHostPort(u.Host) if err != nil { return "", "", xerrors.WithStackTrace(err) } diff --git a/internal/bind/auto_declare.go b/internal/bind/auto_declare.go index a3c07c4f7..049a68e36 100644 --- a/internal/bind/auto_declare.go +++ b/internal/bind/auto_declare.go @@ -13,7 +13,8 @@ func (m AutoDeclare) blockID() blockID { return blockDeclare } -func (m AutoDeclare) RewriteQuery(query string, args ...interface{}) ( +func (m AutoDeclare) RewriteQuery(query string, args ...interface{}) ( //nolint:nonamedreturns + // gocritic more important yql string, newArgs []interface{}, err error, ) { params, err := Params(args...) diff --git a/internal/bind/bind.go b/internal/bind/bind.go index 2b4f0a346..e4e3f4fa1 100644 --- a/internal/bind/bind.go +++ b/internal/bind/bind.go @@ -27,11 +27,11 @@ type Bind interface { type Bindings []Bind func (bindings Bindings) RewriteQuery(query string, args ...interface{}) ( - yql string, _ *table.QueryParameters, err error, + string, *table.QueryParameters, error, ) { if len(bindings) == 0 { var params []table.ParameterOption - params, err = Params(args...) + params, err := Params(args...) if err != nil { return "", nil, xerrors.WithStackTrace(err) } @@ -39,7 +39,10 @@ func (bindings Bindings) RewriteQuery(query string, args ...interface{}) ( return query, table.NewQueryParameters(params...), nil } - buffer := xstring.Buffer() + var ( + err error + buffer = xstring.Buffer() + ) defer buffer.Free() for i := range bindings { diff --git a/internal/bind/numeric_args.go b/internal/bind/numeric_args.go index 89c9c4ecc..425c15dcc 100644 --- a/internal/bind/numeric_args.go +++ b/internal/bind/numeric_args.go @@ -16,7 +16,7 @@ func (m NumericArgs) blockID() blockID { return blockYQL } -func (m NumericArgs) RewriteQuery(sql string, args ...interface{}) ( +func (m NumericArgs) RewriteQuery(sql string, args ...interface{}) ( //nolint:nonamedreturns // gocritic more important yql string, newArgs []interface{}, err error, ) { l := &sqlLexer{ @@ -29,10 +29,8 @@ func (m NumericArgs) RewriteQuery(sql string, args ...interface{}) ( l.stateFn = l.stateFn(l) } - var ( - buffer = xstring.Buffer() - param table.ParameterOption - ) + buffer := xstring.Buffer() + defer buffer.Free() if len(args) > 0 { @@ -54,7 +52,7 @@ func (m NumericArgs) RewriteQuery(sql string, args ...interface{}) ( } paramName := "$p" + strconv.Itoa(int(p-1)) //nolint:goconst if newArgs[p-1] == nil { - param, err = toYdbParam(paramName, args[p-1]) + param, err := toYdbParam(paramName, args[p-1]) if err != nil { return "", nil, xerrors.WithStackTrace(err) } diff --git a/internal/bind/params.go b/internal/bind/params.go index a817dd2cb..c1912b548 100644 --- a/internal/bind/params.go +++ b/internal/bind/params.go @@ -22,9 +22,9 @@ var ( ) //nolint:gocyclo -func toValue(v interface{}) (_ types.Value, err error) { +func toValue(v interface{}) (types.Value, error) { if valuer, ok := v.(driver.Valuer); ok { - v, err = valuer.Value() + _, err := valuer.Value() if err != nil { return nil, fmt.Errorf("ydb: driver.Valuer error: %w", err) } @@ -174,8 +174,8 @@ func toYdbParam(name string, value interface{}) (table.ParameterOption, error) { return table.ValueParam(name, v), nil } -func Params(args ...interface{}) (params []table.ParameterOption, _ error) { - params = make([]table.ParameterOption, 0, len(args)) +func Params(args ...interface{}) ([]table.ParameterOption, error) { + params := make([]table.ParameterOption, 0, len(args)) for i, arg := range args { switch x := arg.(type) { case driver.NamedValue: diff --git a/internal/bind/positional_args.go b/internal/bind/positional_args.go index e3c0afa13..d24382370 100644 --- a/internal/bind/positional_args.go +++ b/internal/bind/positional_args.go @@ -7,7 +7,6 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors" "github.com/ydb-platform/ydb-go-sdk/v3/internal/xstring" - "github.com/ydb-platform/ydb-go-sdk/v3/table" ) type PositionalArgs struct{} @@ -16,7 +15,8 @@ func (m PositionalArgs) blockID() blockID { return blockYQL } -func (m PositionalArgs) RewriteQuery(sql string, args ...interface{}) ( +func (m PositionalArgs) RewriteQuery(sql string, args ...interface{}) ( //nolint:nonamedreturns + // gocritic more important yql string, newArgs []interface{}, err error, ) { l := &sqlLexer{ @@ -32,7 +32,6 @@ func (m PositionalArgs) RewriteQuery(sql string, args ...interface{}) ( var ( buffer = xstring.Buffer() position = 0 - param table.ParameterOption ) defer buffer.Free() @@ -47,7 +46,7 @@ func (m PositionalArgs) RewriteQuery(sql string, args ...interface{}) ( ) } paramName := "$p" + strconv.Itoa(position) - param, err = toYdbParam(paramName, args[position]) + param, err := toYdbParam(paramName, args[position]) if err != nil { return "", nil, xerrors.WithStackTrace(err) } diff --git a/internal/bind/table_path_prefix.go b/internal/bind/table_path_prefix.go index 84cf3f05f..043224e07 100644 --- a/internal/bind/table_path_prefix.go +++ b/internal/bind/table_path_prefix.go @@ -24,7 +24,8 @@ func (tablePathPrefix TablePathPrefix) NormalizePath(folderOrTable string) strin } } -func (tablePathPrefix TablePathPrefix) RewriteQuery(query string, args ...interface{}) ( +func (tablePathPrefix TablePathPrefix) RewriteQuery(query string, args ...interface{}) ( //nolint:nonamedreturns + // gocritic more important yql string, newArgs []interface{}, err error, ) { buffer := xstring.Buffer() diff --git a/internal/certificates/certificates.go b/internal/certificates/certificates.go index 8282dce79..5ce0686ff 100644 --- a/internal/certificates/certificates.go +++ b/internal/certificates/certificates.go @@ -38,7 +38,7 @@ func FromFileOnHit(onHit func()) FromFileOption { } } -func loadFromFileCache(key string) (_ []*x509.Certificate, exists bool) { +func loadFromFileCache(key string) ([]*x509.Certificate, bool) { value, exists := fileCache.Load(key) if !exists { return nil, false @@ -93,7 +93,7 @@ func FromFile(file string, opts ...FromFileOption) ([]*x509.Certificate, error) return certs, nil } -func loadFromPemCache(key string) (_ *x509.Certificate, exists bool) { +func loadFromPemCache(key string) (*x509.Certificate, bool) { value, exists := pemCache.Load(key) if !exists { return nil, false @@ -173,8 +173,12 @@ func FromPemNoCache(noCache bool) FromPemOption { // FromPem parses one or more certificate from pem blocks in bytes. // It returns nil error if at least one certificate was successfully parsed. // This function uses cached parseCertificate. -func FromPem(bytes []byte, opts ...FromPemOption) (certs []*x509.Certificate, err error) { - var block *pem.Block +func FromPem(bytes []byte, opts ...FromPemOption) ([]*x509.Certificate, error) { + var ( + block *pem.Block + certs []*x509.Certificate + err error + ) for len(bytes) > 0 { block, bytes = pem.Decode(bytes) diff --git a/internal/cmd/gtrace/main.go b/internal/cmd/gtrace/main.go index d6c1b5d7b..a11a679dd 100644 --- a/internal/cmd/gtrace/main.go +++ b/internal/cmd/gtrace/main.go @@ -156,7 +156,8 @@ func main() { depth int item *GenItem ) - ast.Inspect(astFile, func(n ast.Node) (next bool) { + ast.Inspect(astFile, func(n ast.Node) bool { + var next bool if n == nil { item = nil depth-- @@ -251,8 +252,8 @@ func main() { log.Println("OK") } -func buildFunc(info *types.Info, traces map[string]*Trace, fn *ast.FuncType) (ret *Func, err error) { - ret = new(Func) +func buildFunc(info *types.Info, traces map[string]*Trace, fn *ast.FuncType) (*Func, error) { + ret := new(Func) for _, p := range fn.Params.List { t := info.TypeOf(p.Type) if t == nil { @@ -313,10 +314,11 @@ func buildFunc(info *types.Info, traces map[string]*Trace, fn *ast.FuncType) (re ) } -func splitOSArchTags(ctx *build.Context, name string) (base, tags, ext string) { +func splitOSArchTags(ctx *build.Context, name string) (string, string, string) { + var base, tags string fileTags := make(map[string]bool) build_goodOSArchFile(ctx, name, fileTags) - ext = filepath.Ext(name) + ext := filepath.Ext(name) switch len(fileTags) { case 0: // * base = strings.TrimSuffix(name, ext) @@ -342,7 +344,7 @@ func splitOSArchTags(ctx *build.Context, name string) (base, tags, ext string) { )) } - return + return base, tags, ext } type Package struct { @@ -400,7 +402,7 @@ type GenItem struct { StructType *ast.StructType } -func rsplit(s string, c byte) (s1, s2 string) { +func rsplit(s string, c byte) (string, string) { i := strings.LastIndexByte(s, c) if i == -1 { return s, "" @@ -409,7 +411,8 @@ func rsplit(s string, c byte) (s1, s2 string) { return s[:i], s[i+1:] } -func scanBuildConstraints(r io.Reader) (cs []string, err error) { +func scanBuildConstraints(r io.Reader) ([]string, error) { + cs := make([]string, 0) br := bufio.NewReader(r) for { line, err := br.ReadBytes('\n') diff --git a/internal/cmd/gtrace/writer.go b/internal/cmd/gtrace/writer.go index fcc87a43e..fa474ef62 100644 --- a/internal/cmd/gtrace/writer.go +++ b/internal/cmd/gtrace/writer.go @@ -170,14 +170,17 @@ func forEachField(s *types.Struct, fn func(*types.Var)) { } } -func unwrapStruct(t types.Type) (n *types.Named, s *types.Struct) { - var ok bool - n, ok = t.(*types.Named) +func unwrapStruct(t types.Type) (*types.Named, *types.Struct) { + var ( + ok bool + s *types.Struct + ) + n, ok := t.(*types.Named) if ok { s, _ = n.Underlying().(*types.Struct) } - return + return n, s } func (w *Writer) funcImports(dst []dep, fn *Func) []dep { @@ -535,8 +538,8 @@ func (w *Writer) hookFuncCall(fn *Func, name string, args []string) { w.line(`return `, res) } -func nameParam(p *Param) (s string) { - s = p.Name +func nameParam(p *Param) string { + s := p.Name if s == "" { s = firstChar(ident(typeBasename(p.Type))) } @@ -544,8 +547,8 @@ func nameParam(p *Param) (s string) { return unexported(s) } -func (w *Writer) declareParams(src []Param) (names []string) { - names = make([]string, len(src)) +func (w *Writer) declareParams(src []Param) []string { + names := make([]string, len(src)) for i := range src { names[i] = w.declare(nameParam(&src[i])) } @@ -553,7 +556,8 @@ func (w *Writer) declareParams(src []Param) (names []string) { return names } -func flattenParams(params []Param) (dst []Param) { +func flattenParams(params []Param) []Param { + dst := make([]Param, 0) for i := range params { _, s := unwrapStruct(params[i].Type) if s != nil { @@ -567,7 +571,7 @@ func flattenParams(params []Param) (dst []Param) { return dst } -func typeBasename(t types.Type) (name string) { +func typeBasename(t types.Type) string { lo, name := rsplit(t.String(), '.') if name == "" { name = lo @@ -599,7 +603,8 @@ func flattenStruct(dst []Param, s *types.Struct) []Param { return dst } -func (w *Writer) constructParams(params []Param, names []string) (res []string) { +func (w *Writer) constructParams(params []Param, names []string) []string { + res := make([]string, 0, len(params)) for i := range params { n, s := unwrapStruct(params[i].Type) if s != nil { @@ -762,7 +767,8 @@ func (w *Writer) zeroReturn(fn *Func) { } } -func (w *Writer) funcParams(params []Param) (vars []string) { +func (w *Writer) funcParams(params []Param) []string { + vars := make([]string, 0, len(params)) w.code(`(`) for i := range params { if i > 0 { @@ -772,11 +778,11 @@ func (w *Writer) funcParams(params []Param) (vars []string) { } w.code(`)`) - return + return vars } -func (w *Writer) funcParam(p *Param) (name string) { - name = w.declare(nameParam(p)) +func (w *Writer) funcParam(p *Param) string { + name := w.declare(nameParam(p)) w.code(name, ` `) w.code(w.typeString(p.Type)) diff --git a/internal/conn/conn.go b/internal/conn/conn.go index e20266f48..7fa6da512 100644 --- a/internal/conn/conn.go +++ b/internal/conn/conn.go @@ -94,11 +94,14 @@ func (c *conn) IsState(states ...State) bool { return false } -func (c *conn) park(ctx context.Context) (err error) { - onDone := trace.DriverOnConnPark( - c.config.Trace(), &ctx, - stack.FunctionID(""), - c.Endpoint(), +func (c *conn) park(ctx context.Context) error { + var ( + err error + onDone = trace.DriverOnConnPark( + c.config.Trace(), &ctx, + stack.FunctionID(""), + c.Endpoint(), + ) ) defer func() { onDone(err) @@ -172,11 +175,11 @@ func (c *conn) Unban(ctx context.Context) State { return newState } -func (c *conn) GetState() (s State) { +func (c *conn) GetState() State { return State(c.state.Load()) } -func (c *conn) realConn(ctx context.Context) (cc *grpc.ClientConn, err error) { +func (c *conn) realConn(ctx context.Context) (*grpc.ClientConn, error) { if c.isClosed() { return nil, c.wrapError(errClosedConnection) } @@ -194,10 +197,13 @@ func (c *conn) realConn(ctx context.Context) (cc *grpc.ClientConn, err error) { defer cancel() } - onDone := trace.DriverOnConnDial( - c.config.Trace(), &ctx, - stack.FunctionID(""), - c.endpoint.Copy(), + var ( + err error + onDone = trace.DriverOnConnDial( + c.config.Trace(), &ctx, + stack.FunctionID(""), + c.endpoint.Copy(), + ) ) defer func() { onDone(err) @@ -207,7 +213,7 @@ func (c *conn) realConn(ctx context.Context) (cc *grpc.ClientConn, err error) { // three slashes in "ydb:///" is ok. It needs for good parse scheme in grpc resolver. address := "ydb:///" + c.endpoint.Address() - cc, err = grpc.DialContext(ctx, address, append( + cc, err := grpc.DialContext(ctx, address, append( []grpc.DialOption{ grpc.WithStatsHandler(statsHandler{}), }, c.config.GrpcDialOptions()..., @@ -251,11 +257,11 @@ func isAvailable(raw *grpc.ClientConn) bool { } // conn must be locked -func (c *conn) close(ctx context.Context) (err error) { +func (c *conn) close(ctx context.Context) error { if c.cc == nil { return nil } - err = c.cc.Close() + err := c.cc.Close() c.cc = nil c.setState(ctx, Offline) @@ -269,7 +275,7 @@ func (c *conn) isClosed() bool { return c.closed } -func (c *conn) Close(ctx context.Context) (err error) { +func (c *conn) Close(ctx context.Context) error { c.mtx.Lock() defer c.mtx.Unlock() @@ -277,10 +283,13 @@ func (c *conn) Close(ctx context.Context) (err error) { return nil } - onDone := trace.DriverOnConnClose( - c.config.Trace(), &ctx, - stack.FunctionID(""), - c.Endpoint(), + var ( + err error + onDone = trace.DriverOnConnClose( + c.config.Trace(), &ctx, + stack.FunctionID(""), + c.Endpoint(), + ) ) defer func() { onDone(err) @@ -305,7 +314,7 @@ func (c *conn) Invoke( req interface{}, res interface{}, opts ...grpc.CallOption, -) (err error) { +) error { var ( opID string issues []trace.Issue @@ -315,8 +324,9 @@ func (c *conn) Invoke( stack.FunctionID(""), c.endpoint, trace.Method(method), ) - cc *grpc.ClientConn - md = metadata.MD{} + cc *grpc.ClientConn + md = metadata.MD{} + err error ) defer func() { meta.CallTrailerCallback(ctx, md) @@ -389,7 +399,7 @@ func (c *conn) NewStream( desc *grpc.StreamDesc, method string, opts ...grpc.CallOption, -) (_ grpc.ClientStream, err error) { +) (grpc.ClientStream, error) { var ( streamRecv = trace.DriverOnConnNewStream( c.config.Trace(), &ctx, @@ -399,6 +409,7 @@ func (c *conn) NewStream( useWrapping = UseWrapping(ctx) cc *grpc.ClientConn s grpc.ClientStream + err error ) defer func() { diff --git a/internal/conn/grpc_client_stream.go b/internal/conn/grpc_client_stream.go index ca07acb79..f2390a773 100644 --- a/internal/conn/grpc_client_stream.go +++ b/internal/conn/grpc_client_stream.go @@ -25,9 +25,8 @@ type grpcClientStream struct { recv func(error) func(error, trace.ConnState, map[string][]string) } -func (s *grpcClientStream) CloseSend() (err error) { - err = s.ClientStream.CloseSend() - +func (s *grpcClientStream) CloseSend() error { + err := s.ClientStream.CloseSend() if err != nil { if s.wrapping { return s.wrapError( @@ -45,12 +44,11 @@ func (s *grpcClientStream) CloseSend() (err error) { return nil } -func (s *grpcClientStream) SendMsg(m interface{}) (err error) { +func (s *grpcClientStream) SendMsg(m interface{}) error { cancel := createPinger(s.c) defer cancel() - err = s.ClientStream.SendMsg(m) - + err := s.ClientStream.SendMsg(m) if err != nil { defer func() { s.c.onTransportError(s.Context(), err) @@ -76,7 +74,8 @@ func (s *grpcClientStream) SendMsg(m interface{}) (err error) { return nil } -func (s *grpcClientStream) RecvMsg(m interface{}) (err error) { +func (s *grpcClientStream) RecvMsg(m interface{}) error { + var err error cancel := createPinger(s.c) defer cancel() diff --git a/internal/conn/pool.go b/internal/conn/pool.go index cbf49f93d..1a4808262 100644 --- a/internal/conn/pool.go +++ b/internal/conn/pool.go @@ -124,8 +124,11 @@ func (p *Pool) Take(context.Context) error { return nil } -func (p *Pool) Release(ctx context.Context) (finalErr error) { - onDone := trace.DriverOnPoolRelease(p.config.Trace(), &ctx, stack.FunctionID("")) +func (p *Pool) Release(ctx context.Context) error { + var ( + finalErr error + onDone = trace.DriverOnPoolRelease(p.config.Trace(), &ctx, stack.FunctionID("")) + ) defer func() { onDone(finalErr) }() diff --git a/internal/coordination/client.go b/internal/coordination/client.go index c6ceede63..bd5ccc220 100644 --- a/internal/coordination/client.go +++ b/internal/coordination/client.go @@ -160,24 +160,29 @@ func (c *Client) DescribeNode( ctx context.Context, path string, ) ( - entry *scheme.Entry, - config *coordination.NodeConfig, - _ error, + *scheme.Entry, + *coordination.NodeConfig, + error, ) { + var ( + entry *scheme.Entry + config *coordination.NodeConfig + err error + ) if c == nil { return nil, nil, xerrors.WithStackTrace(errNilClient) } - call := func(ctx context.Context) (err error) { + call := func(ctx context.Context) error { entry, config, err = c.describeNode(ctx, path) return xerrors.WithStackTrace(err) } if !c.config.AutoRetry() { - err := call(ctx) + err = call(ctx) return entry, config, xerrors.WithStackTrace(err) } - err := retry.Retry(ctx, call, + err = retry.Retry(ctx, call, retry.WithStackTrace(), retry.WithIdempotent(true), retry.WithTrace(c.config.TraceRetry()), @@ -191,13 +196,14 @@ func (c *Client) describeNode( ctx context.Context, path string, ) ( - _ *scheme.Entry, - _ *coordination.NodeConfig, - err error, + *scheme.Entry, + *coordination.NodeConfig, + error, ) { var ( response *Ydb_Coordination.DescribeNodeResponse result Ydb_Coordination.DescribeNodeResult + err error ) response, err = c.service.DescribeNode( ctx, diff --git a/internal/credentials/static.go b/internal/credentials/static.go index 56e80277d..0293a454c 100644 --- a/internal/credentials/static.go +++ b/internal/credentials/static.go @@ -71,7 +71,7 @@ type Static struct { sourceInfo string } -func (c *Static) Token(ctx context.Context) (token string, err error) { +func (c *Static) Token(ctx context.Context) (string, error) { c.mu.Lock() defer c.mu.Unlock() if time.Until(c.requestAt) > 0 { @@ -137,9 +137,12 @@ func (c *Static) Token(ctx context.Context) (token string, err error) { return c.token, nil } -func parseExpiresAt(raw string) (expiresAt time.Time, err error) { - var claims jwt.RegisteredClaims - if _, _, err = jwt.NewParser().ParseUnverified(raw, &claims); err != nil { +func parseExpiresAt(raw string) (time.Time, error) { + var ( + claims jwt.RegisteredClaims + expiresAt time.Time + ) + if _, _, err := jwt.NewParser().ParseUnverified(raw, &claims); err != nil { return expiresAt, xerrors.WithStackTrace(err) } diff --git a/internal/decimal/decimal.go b/internal/decimal/decimal.go index a4753992a..ad157a8ad 100644 --- a/internal/decimal/decimal.go +++ b/internal/decimal/decimal.go @@ -270,7 +270,8 @@ func Format(x *big.Int, precision, scale uint32) string { // // If x value does not fit in 16 bytes with given precision, it returns 16-byte // representation of infinity or negative infinity value accordingly to x's sign. -func BigIntToByte(x *big.Int, precision, scale uint32) (p [16]byte) { +func BigIntToByte(x *big.Int, precision, scale uint32) [16]byte { + var p [16]byte if !IsInf(x) && !IsNaN(x) && !IsErr(x) && x.CmpAbs(pow(ten, precision)) >= 0 { if x.Sign() < 0 { x = neginf diff --git a/internal/discovery/discovery.go b/internal/discovery/discovery.go index dba4ca480..1ff45e700 100644 --- a/internal/discovery/discovery.go +++ b/internal/discovery/discovery.go @@ -36,7 +36,7 @@ type Client struct { } // Discover cluster endpoints -func (c *Client) Discover(ctx context.Context) (endpoints []endpoint.Endpoint, err error) { +func (c *Client) Discover(ctx context.Context) ([]endpoint.Endpoint, error) { var ( onDone = trace.DiscoveryOnDiscover( c.config.Trace(), &ctx, @@ -46,9 +46,11 @@ func (c *Client) Discover(ctx context.Context) (endpoints []endpoint.Endpoint, e request = Ydb_Discovery.ListEndpointsRequest{ Database: c.config.Database(), } - response *Ydb_Discovery.ListEndpointsResponse - result Ydb_Discovery.ListEndpointsResult - location string + response *Ydb_Discovery.ListEndpointsResponse + result Ydb_Discovery.ListEndpointsResult + location string + endpoints = make([]endpoint.Endpoint, 0, len(result.Endpoints)) + err error ) defer func() { nodes := make([]trace.EndpointInfo, 0, len(endpoints)) @@ -82,7 +84,6 @@ func (c *Client) Discover(ctx context.Context) (endpoints []endpoint.Endpoint, e } location = result.GetSelfLocation() - endpoints = make([]endpoint.Endpoint, 0, len(result.Endpoints)) for _, e := range result.Endpoints { if e.Ssl == c.config.Secure() { endpoints = append(endpoints, endpoint.New( @@ -99,12 +100,14 @@ func (c *Client) Discover(ctx context.Context) (endpoints []endpoint.Endpoint, e return endpoints, nil } -func (c *Client) WhoAmI(ctx context.Context) (whoAmI *discovery.WhoAmI, err error) { +func (c *Client) WhoAmI(ctx context.Context) (*discovery.WhoAmI, error) { var ( onDone = trace.DiscoveryOnWhoAmI(c.config.Trace(), &ctx, stack.FunctionID("")) request = Ydb_Discovery.WhoAmIRequest{} response *Ydb_Discovery.WhoAmIResponse whoAmIResultResult Ydb_Discovery.WhoAmIResult + whoAmI *discovery.WhoAmI + err error ) defer func() { if err != nil { diff --git a/internal/dsn/dsn.go b/internal/dsn/dsn.go index 17e77088e..199c19c5d 100644 --- a/internal/dsn/dsn.go +++ b/internal/dsn/dsn.go @@ -24,7 +24,8 @@ type parsedInfo struct { Params url.Values } -func Parse(dsn string) (info parsedInfo, err error) { +func Parse(dsn string) (parsedInfo, error) { + var info parsedInfo uri, err := url.Parse(dsn) if err != nil { return info, xerrors.WithStackTrace(err) diff --git a/internal/endpoint/endpoint.go b/internal/endpoint/endpoint.go index cdaba3710..5338ac5e3 100644 --- a/internal/endpoint/endpoint.go +++ b/internal/endpoint/endpoint.go @@ -72,7 +72,7 @@ func (e *endpoint) NodeID() uint32 { return e.id } -func (e *endpoint) Address() (address string) { +func (e *endpoint) Address() string { e.mu.RLock() defer e.mu.RUnlock() diff --git a/internal/grpcwrapper/rawtopic/client.go b/internal/grpcwrapper/rawtopic/client.go index 5ccc30225..bef21e554 100644 --- a/internal/grpcwrapper/rawtopic/client.go +++ b/internal/grpcwrapper/rawtopic/client.go @@ -19,7 +19,8 @@ func NewClient(service Ydb_Topic_V1.TopicServiceClient) Client { return Client{service: service} } -func (c *Client) AlterTopic(ctx context.Context, req *AlterTopicRequest) (res AlterTopicResult, err error) { +func (c *Client) AlterTopic(ctx context.Context, req *AlterTopicRequest) (AlterTopicResult, error) { + var res AlterTopicResult resp, err := c.service.AlterTopic(ctx, req.ToProto()) if err != nil { return res, xerrors.WithStackTrace(fmt.Errorf("ydb: alter topic grpc failed: %w", err)) @@ -32,7 +33,8 @@ func (c *Client) AlterTopic(ctx context.Context, req *AlterTopicRequest) (res Al func (c *Client) CreateTopic( ctx context.Context, req *CreateTopicRequest, -) (res CreateTopicResult, err error) { +) (CreateTopicResult, error) { + var res CreateTopicResult resp, err := c.service.CreateTopic(ctx, req.ToProto()) if err != nil { return res, xerrors.WithStackTrace(fmt.Errorf("ydb: create topic grpc failed: %w", err)) @@ -42,7 +44,8 @@ func (c *Client) CreateTopic( return res, err } -func (c *Client) DescribeTopic(ctx context.Context, req DescribeTopicRequest) (res DescribeTopicResult, err error) { +func (c *Client) DescribeTopic(ctx context.Context, req DescribeTopicRequest) (DescribeTopicResult, error) { + var res DescribeTopicResult resp, err := c.service.DescribeTopic(ctx, req.ToProto()) if err != nil { return DescribeTopicResult{}, xerrors.WithStackTrace(xerrors.Wrap( @@ -57,7 +60,8 @@ func (c *Client) DescribeTopic(ctx context.Context, req DescribeTopicRequest) (r func (c *Client) DropTopic( ctx context.Context, req DropTopicRequest, -) (res DropTopicResult, err error) { +) (DropTopicResult, error) { + var res DropTopicResult resp, err := c.service.DropTopic(ctx, req.ToProto()) if err != nil { return res, xerrors.WithStackTrace(fmt.Errorf("ydb: drop topic grpc failed: %w", err)) diff --git a/internal/grpcwrapper/rawtopic/rawtopicreader/messages.go b/internal/grpcwrapper/rawtopic/rawtopicreader/messages.go index b7b32da1c..ad1c075b2 100644 --- a/internal/grpcwrapper/rawtopic/rawtopicreader/messages.go +++ b/internal/grpcwrapper/rawtopic/rawtopicreader/messages.go @@ -192,7 +192,9 @@ func (r *ReadResponse) GetBytesSize() int { } // GetPartitionBatchMessagesCounts implements trace.TopicReaderDataResponseInfo -func (r *ReadResponse) GetPartitionBatchMessagesCounts() (partitionDataCount, batchCount, messagesCount int) { +func (r *ReadResponse) GetPartitionBatchMessagesCounts() ( //nolint:nonamedreturns // gocritic more important + partitionDataCount, batchCount, messagesCount int, +) { partitionDataCount = len(r.PartitionData) for partitionIndex := range r.PartitionData { partitionData := &r.PartitionData[partitionIndex] diff --git a/internal/grpcwrapper/rawtopic/rawtopicwriter/messages.go b/internal/grpcwrapper/rawtopic/rawtopicwriter/messages.go index 5f89a2f6b..3f6e417a2 100644 --- a/internal/grpcwrapper/rawtopic/rawtopicwriter/messages.go +++ b/internal/grpcwrapper/rawtopic/rawtopicwriter/messages.go @@ -146,8 +146,11 @@ type WriteRequest struct { Codec rawtopiccommon.Codec } -func (r *WriteRequest) toProto() (p *Ydb_Topic.StreamWriteMessage_FromClient_WriteRequest, err error) { - messages := make([]*Ydb_Topic.StreamWriteMessage_WriteRequest_MessageData, len(r.Messages)) +func (r *WriteRequest) toProto() (*Ydb_Topic.StreamWriteMessage_FromClient_WriteRequest, error) { + var ( + messages = make([]*Ydb_Topic.StreamWriteMessage_WriteRequest_MessageData, len(r.Messages)) + err error + ) for i := range r.Messages { messages[i], err = r.Messages[i].ToProto() diff --git a/internal/meta/meta.go b/internal/meta/meta.go index 4f1564732..c4802605f 100644 --- a/internal/meta/meta.go +++ b/internal/meta/meta.go @@ -75,7 +75,7 @@ type Meta struct { capabilities []string } -func (m *Meta) meta(ctx context.Context) (_ metadata.MD, err error) { +func (m *Meta) meta(ctx context.Context) (metadata.MD, error) { md, has := metadata.FromOutgoingContext(ctx) if !has { md = metadata.MD{} @@ -107,7 +107,10 @@ func (m *Meta) meta(ctx context.Context) (_ metadata.MD, err error) { return md, nil } - var token string + var ( + token string + err error + ) done := trace.DriverOnGetCredentials(m.trace, &ctx, stack.FunctionID("")) defer func() { @@ -128,7 +131,7 @@ func (m *Meta) meta(ctx context.Context) (_ metadata.MD, err error) { return md, nil } -func (m *Meta) Context(ctx context.Context) (_ context.Context, err error) { +func (m *Meta) Context(ctx context.Context) (context.Context, error) { md, err := m.meta(ctx) if err != nil { return ctx, xerrors.WithStackTrace(err) diff --git a/internal/mock/conn.go b/internal/mock/conn.go index ac57f6c41..4703d73ee 100644 --- a/internal/mock/conn.go +++ b/internal/mock/conn.go @@ -49,7 +49,7 @@ func (c *Conn) LastUsage() time.Time { panic("not implemented in mock") } -func (c *Conn) Park(ctx context.Context) (err error) { +func (c *Conn) Park(ctx context.Context) error { panic("not implemented in mock") } diff --git a/internal/operation/context.go b/internal/operation/context.go index 3ce2e1ee5..a60c2f689 100644 --- a/internal/operation/context.go +++ b/internal/operation/context.go @@ -35,18 +35,18 @@ func WithCancelAfter(ctx context.Context, operationCancelAfter time.Duration) co // Timeout returns the timeout within given context after which // YDB should try to cancel operation and return result regardless of the cancelation. -func Timeout(ctx context.Context) (d time.Duration, ok bool) { - d, ok = ctx.Value(ctxOperationTimeoutKey{}).(time.Duration) +func Timeout(ctx context.Context) (time.Duration, bool) { + d, ok := ctx.Value(ctxOperationTimeoutKey{}).(time.Duration) - return + return d, ok } // CancelAfter returns the timeout within given context after which // YDB should try to cancel operation and return result regardless of the cancellation. -func CancelAfter(ctx context.Context) (d time.Duration, ok bool) { - d, ok = ctx.Value(ctxOperationCancelAfterKey{}).(time.Duration) +func CancelAfter(ctx context.Context) (time.Duration, bool) { + d, ok := ctx.Value(ctxOperationCancelAfterKey{}).(time.Duration) - return + return d, ok } func untilDeadline(ctx context.Context) (time.Duration, bool) { diff --git a/internal/ratelimiter/client.go b/internal/ratelimiter/client.go index 206cbf5f9..179a511b4 100644 --- a/internal/ratelimiter/client.go +++ b/internal/ratelimiter/client.go @@ -48,7 +48,7 @@ func (c *Client) CreateResource( ctx context.Context, coordinationNodePath string, resource ratelimiter.Resource, -) (err error) { +) error { if c == nil { return xerrors.WithStackTrace(errNilClient) } @@ -70,8 +70,8 @@ func (c *Client) createResource( ctx context.Context, coordinationNodePath string, resource ratelimiter.Resource, -) (err error) { - _, err = c.service.CreateResource(ctx, &Ydb_RateLimiter.CreateResourceRequest{ +) error { + _, err := c.service.CreateResource(ctx, &Ydb_RateLimiter.CreateResourceRequest{ CoordinationNodePath: coordinationNodePath, Resource: &Ydb_RateLimiter.Resource{ ResourcePath: resource.ResourcePath, @@ -90,14 +90,14 @@ func (c *Client) createResource( ), }) - return + return err } func (c *Client) AlterResource( ctx context.Context, coordinationNodePath string, resource ratelimiter.Resource, -) (err error) { +) error { if c == nil { return xerrors.WithStackTrace(errNilClient) } @@ -119,8 +119,8 @@ func (c *Client) alterResource( ctx context.Context, coordinationNodePath string, resource ratelimiter.Resource, -) (err error) { - _, err = c.service.AlterResource(ctx, &Ydb_RateLimiter.AlterResourceRequest{ +) error { + _, err := c.service.AlterResource(ctx, &Ydb_RateLimiter.AlterResourceRequest{ CoordinationNodePath: coordinationNodePath, Resource: &Ydb_RateLimiter.Resource{ ResourcePath: resource.ResourcePath, @@ -139,14 +139,14 @@ func (c *Client) alterResource( ), }) - return + return err } func (c *Client) DropResource( ctx context.Context, coordinationNodePath string, resourcePath string, -) (err error) { +) error { if c == nil { return xerrors.WithStackTrace(errNilClient) } @@ -168,8 +168,8 @@ func (c *Client) dropResource( ctx context.Context, coordinationNodePath string, resourcePath string, -) (err error) { - _, err = c.service.DropResource(ctx, &Ydb_RateLimiter.DropResourceRequest{ +) error { + _, err := c.service.DropResource(ctx, &Ydb_RateLimiter.DropResourceRequest{ CoordinationNodePath: coordinationNodePath, ResourcePath: resourcePath, OperationParams: operation.Params( @@ -180,7 +180,7 @@ func (c *Client) dropResource( ), }) - return + return err } func (c *Client) ListResource( @@ -188,11 +188,13 @@ func (c *Client) ListResource( coordinationNodePath string, resourcePath string, recursive bool, -) (list []string, _ error) { +) ([]string, error) { + var list []string if c == nil { return list, xerrors.WithStackTrace(errNilClient) } - call := func(ctx context.Context) (err error) { + call := func(ctx context.Context) error { + var err error list, err = c.listResource(ctx, coordinationNodePath, resourcePath, recursive) return xerrors.WithStackTrace(err) @@ -216,12 +218,12 @@ func (c *Client) listResource( coordinationNodePath string, resourcePath string, recursive bool, -) (_ []string, err error) { +) ([]string, error) { var ( response *Ydb_RateLimiter.ListResourcesResponse result Ydb_RateLimiter.ListResourcesResult ) - response, err = c.service.ListResources(ctx, &Ydb_RateLimiter.ListResourcesRequest{ + response, err := c.service.ListResources(ctx, &Ydb_RateLimiter.ListResourcesRequest{ CoordinationNodePath: coordinationNodePath, ResourcePath: resourcePath, Recursive: recursive, @@ -247,7 +249,11 @@ func (c *Client) DescribeResource( ctx context.Context, coordinationNodePath string, resourcePath string, -) (resource *ratelimiter.Resource, err error) { +) (*ratelimiter.Resource, error) { + var ( + resource *ratelimiter.Resource + err error + ) if c == nil { return resource, xerrors.WithStackTrace(errNilClient) } @@ -259,7 +265,7 @@ func (c *Client) DescribeResource( if !c.config.AutoRetry() { err = call(ctx) - return + return resource, err } err = retry.Retry(ctx, call, retry.WithIdempotent(true), @@ -267,17 +273,18 @@ func (c *Client) DescribeResource( retry.WithTrace(c.config.TraceRetry()), ) - return + return resource, err } func (c *Client) describeResource( ctx context.Context, coordinationNodePath string, resourcePath string, -) (_ *ratelimiter.Resource, err error) { +) (*ratelimiter.Resource, error) { var ( response *Ydb_RateLimiter.DescribeResourceResponse result Ydb_RateLimiter.DescribeResourceResult + err error ) response, err = c.service.DescribeResource(ctx, &Ydb_RateLimiter.DescribeResourceRequest{ CoordinationNodePath: coordinationNodePath, @@ -319,7 +326,7 @@ func (c *Client) AcquireResource( resourcePath string, amount uint64, opts ...options.AcquireOption, -) (err error) { +) error { if c == nil { return xerrors.WithStackTrace(errNilClient) } @@ -342,7 +349,8 @@ func (c *Client) acquireResource( resourcePath string, amount uint64, opts ...options.AcquireOption, -) (err error) { +) error { + var err error acquireOptions := options.NewAcquire( append( []options.AcquireOption{ diff --git a/internal/repeater/repeater.go b/internal/repeater/repeater.go index 4085a4690..7562e656e 100644 --- a/internal/repeater/repeater.go +++ b/internal/repeater/repeater.go @@ -139,7 +139,8 @@ func (r *repeater) Force() { } } -func (r *repeater) wakeUp(ctx context.Context, e Event) (err error) { +func (r *repeater) wakeUp(ctx context.Context, e Event) error { + var err error if err = ctx.Err(); err != nil { return err } diff --git a/internal/repeater/repeater_test.go b/internal/repeater/repeater_test.go index 6749ac19a..c66851e90 100644 --- a/internal/repeater/repeater_test.go +++ b/internal/repeater/repeater_test.go @@ -17,7 +17,7 @@ func TestRepeaterNoWakeUpsAfterStop(t *testing.T) { wakeUpDone = make(chan struct{}) ) fakeClock := clockwork.NewFakeClock() - r := New(context.Background(), interval, func(ctx context.Context) (err error) { + r := New(context.Background(), interval, func(ctx context.Context) error { wakeUpStart <- struct{}{} <-wakeUpDone @@ -72,7 +72,7 @@ func TestRepeaterForceLogBackoff(t *testing.T) { ) repeaterDone := make(chan struct{}) - r := New(context.Background(), 10*time.Minute, func(ctx context.Context) (err error) { + r := New(context.Background(), 10*time.Minute, func(ctx context.Context) error { defer func() { repeaterDone <- struct{}{} }() diff --git a/internal/scheme/client.go b/internal/scheme/client.go index f9dd3a621..1df532bdc 100644 --- a/internal/scheme/client.go +++ b/internal/scheme/client.go @@ -45,10 +45,13 @@ func New(ctx context.Context, cc grpc.ClientConnInterface, config config.Config) }, nil } -func (c *Client) MakeDirectory(ctx context.Context, path string) (finalErr error) { - onDone := trace.SchemeOnMakeDirectory(c.config.Trace(), &ctx, - stack.FunctionID(""), - path, +func (c *Client) MakeDirectory(ctx context.Context, path string) error { + var ( + finalErr error + onDone = trace.SchemeOnMakeDirectory(c.config.Trace(), &ctx, + stack.FunctionID(""), + path, + ) ) defer func() { onDone(finalErr) @@ -67,8 +70,8 @@ func (c *Client) MakeDirectory(ctx context.Context, path string) (finalErr error ) } -func (c *Client) makeDirectory(ctx context.Context, path string) (err error) { - _, err = c.service.MakeDirectory( +func (c *Client) makeDirectory(ctx context.Context, path string) error { + _, err := c.service.MakeDirectory( ctx, &Ydb_Scheme.MakeDirectoryRequest{ Path: path, @@ -84,10 +87,13 @@ func (c *Client) makeDirectory(ctx context.Context, path string) (err error) { return xerrors.WithStackTrace(err) } -func (c *Client) RemoveDirectory(ctx context.Context, path string) (finalErr error) { - onDone := trace.SchemeOnRemoveDirectory(c.config.Trace(), &ctx, - stack.FunctionID(""), - path, +func (c *Client) RemoveDirectory(ctx context.Context, path string) error { + var ( + finalErr error + onDone = trace.SchemeOnRemoveDirectory(c.config.Trace(), &ctx, + stack.FunctionID(""), + path, + ) ) defer func() { onDone(finalErr) @@ -106,8 +112,8 @@ func (c *Client) RemoveDirectory(ctx context.Context, path string) (finalErr err ) } -func (c *Client) removeDirectory(ctx context.Context, path string) (err error) { - _, err = c.service.RemoveDirectory( +func (c *Client) removeDirectory(ctx context.Context, path string) error { + _, err := c.service.RemoveDirectory( ctx, &Ydb_Scheme.RemoveDirectoryRequest{ Path: path, @@ -123,15 +129,19 @@ func (c *Client) removeDirectory(ctx context.Context, path string) (err error) { return xerrors.WithStackTrace(err) } -func (c *Client) ListDirectory(ctx context.Context, path string) (d scheme.Directory, finalErr error) { - onDone := trace.SchemeOnListDirectory(c.config.Trace(), &ctx, stack.FunctionID("")) +func (c *Client) ListDirectory(ctx context.Context, path string) (scheme.Directory, error) { + var ( + d scheme.Directory + finalErr error + onDone = trace.SchemeOnListDirectory(c.config.Trace(), &ctx, stack.FunctionID("")) + ) defer func() { onDone(finalErr) }() - call := func(ctx context.Context) (err error) { - d, err = c.listDirectory(ctx, path) + call := func(ctx context.Context) error { + d, finalErr = c.listDirectory(ctx, path) - return xerrors.WithStackTrace(err) + return xerrors.WithStackTrace(finalErr) } if !c.config.AutoRetry() { err := call(ctx) @@ -180,18 +190,22 @@ func (c *Client) listDirectory(ctx context.Context, path string) (scheme.Directo return d, nil } -func (c *Client) DescribePath(ctx context.Context, path string) (e scheme.Entry, finalErr error) { - onDone := trace.SchemeOnDescribePath(c.config.Trace(), &ctx, - stack.FunctionID(""), - path, +func (c *Client) DescribePath(ctx context.Context, path string) (scheme.Entry, error) { + var ( + e scheme.Entry + finalErr error + onDone = trace.SchemeOnDescribePath(c.config.Trace(), &ctx, + stack.FunctionID(""), + path, + ) ) defer func() { onDone(e.Type.String(), finalErr) }() - call := func(ctx context.Context) (err error) { - e, err = c.describePath(ctx, path) - if err != nil { - return xerrors.WithStackTrace(err) + call := func(ctx context.Context) error { + e, finalErr = c.describePath(ctx, path) + if finalErr != nil { + return xerrors.WithStackTrace(finalErr) } return nil @@ -210,12 +224,13 @@ func (c *Client) DescribePath(ctx context.Context, path string) (e scheme.Entry, return e, xerrors.WithStackTrace(err) } -func (c *Client) describePath(ctx context.Context, path string) (e scheme.Entry, err error) { +func (c *Client) describePath(ctx context.Context, path string) (scheme.Entry, error) { var ( response *Ydb_Scheme.DescribePathResponse result Ydb_Scheme.DescribePathResult + e scheme.Entry ) - response, err = c.service.DescribePath( + response, err := c.service.DescribePath( ctx, &Ydb_Scheme.DescribePathRequest{ Path: path, @@ -241,10 +256,13 @@ func (c *Client) describePath(ctx context.Context, path string) (e scheme.Entry, func (c *Client) ModifyPermissions( ctx context.Context, path string, opts ...scheme.PermissionsOption, -) (finalErr error) { - onDone := trace.SchemeOnModifyPermissions(c.config.Trace(), &ctx, - stack.FunctionID(""), - path, +) error { + var ( + finalErr error + onDone = trace.SchemeOnModifyPermissions(c.config.Trace(), &ctx, + stack.FunctionID(""), + path, + ) ) defer func() { onDone(finalErr) @@ -269,8 +287,8 @@ func (c *Client) ModifyPermissions( ) } -func (c *Client) modifyPermissions(ctx context.Context, path string, desc permissionsDesc) (err error) { - _, err = c.service.ModifyPermissions( +func (c *Client) modifyPermissions(ctx context.Context, path string, desc permissionsDesc) error { + _, err := c.service.ModifyPermissions( ctx, &Ydb_Scheme.ModifyPermissionsRequest{ Path: path, diff --git a/internal/scheme/helpers/check_exists.go b/internal/scheme/helpers/check_exists.go index 534d12b36..f926e089f 100644 --- a/internal/scheme/helpers/check_exists.go +++ b/internal/scheme/helpers/check_exists.go @@ -16,7 +16,7 @@ type schemeClient interface { } func IsDirectoryExists(ctx context.Context, c schemeClient, directory string) ( - exists bool, _ error, + bool, error, ) { if !strings.HasPrefix(directory, c.Database()) { return false, xerrors.WithStackTrace(fmt.Errorf( @@ -58,7 +58,7 @@ func IsDirectoryExists(ctx context.Context, c schemeClient, directory string) ( } func IsEntryExists(ctx context.Context, c schemeClient, absPath string, entryTypes ...scheme.EntryType) ( - exists bool, _ error, + bool, error, ) { if !strings.HasPrefix(absPath, c.Database()) { return false, xerrors.WithStackTrace(fmt.Errorf( diff --git a/internal/scheme/helpers/check_exists_test.go b/internal/scheme/helpers/check_exists_test.go index 265346cae..dca77e965 100644 --- a/internal/scheme/helpers/check_exists_test.go +++ b/internal/scheme/helpers/check_exists_test.go @@ -21,7 +21,7 @@ func (c isDirectoryExistsSchemeClient) Database() string { } func (c isDirectoryExistsSchemeClient) ListDirectory(ctx context.Context, path string) ( - d scheme.Directory, err error, + scheme.Directory, error, ) { if c.existingPath == path { return scheme.Directory{ @@ -48,7 +48,7 @@ func (c isDirectoryExistsSchemeClient) ListDirectory(ctx context.Context, path s }, nil } - return d, fmt.Errorf("path '%s' not found in '%s'", path, c) + return scheme.Directory{}, fmt.Errorf("path '%s' not found in '%s'", path, c) } func TestIsDirectoryExists(t *testing.T) { @@ -135,7 +135,7 @@ func (c isTableExistsSchemeClient) Database() string { } func (c isTableExistsSchemeClient) ListDirectory(ctx context.Context, path string) ( - d scheme.Directory, err error, + scheme.Directory, error, ) { if strings.HasPrefix(c.tablePath, path) { children := strings.Split(strings.TrimLeft(c.tablePath, path), "/") @@ -176,7 +176,7 @@ func (c isTableExistsSchemeClient) ListDirectory(ctx context.Context, path strin } } - return d, fmt.Errorf("path '%s' not found in '%s'", path, c) + return scheme.Directory{}, fmt.Errorf("path '%s' not found in '%s'", path, c) } func TestIsTableExists(t *testing.T) { diff --git a/internal/scripting/client.go b/internal/scripting/client.go index bf57a3edd..bb0b3472b 100644 --- a/internal/scripting/client.go +++ b/internal/scripting/client.go @@ -41,7 +41,11 @@ func (c *Client) Execute( ctx context.Context, query string, params *table.QueryParameters, -) (r result.Result, err error) { +) (result.Result, error) { + var ( + r result.Result + err error + ) if c == nil { return r, xerrors.WithStackTrace(errNilClient) } @@ -53,7 +57,7 @@ func (c *Client) Execute( if !c.config.AutoRetry() { err = call(ctx) - return + return r, err } err = retry.Retry(ctx, call, retry.WithStackTrace(), @@ -67,8 +71,10 @@ func (c *Client) execute( ctx context.Context, query string, params *table.QueryParameters, -) (r result.Result, err error) { +) (result.Result, error) { var ( + r result.Result + err error onDone = trace.ScriptingOnExecute(c.config.Trace(), &ctx, stack.FunctionID(""), query, params, @@ -119,7 +125,11 @@ func (c *Client) Explain( ctx context.Context, query string, mode scripting.ExplainMode, -) (e table.ScriptingYQLExplanation, err error) { +) (table.ScriptingYQLExplanation, error) { + var ( + e table.ScriptingYQLExplanation + err error + ) if c == nil { return e, xerrors.WithStackTrace(errNilClient) } @@ -131,7 +141,7 @@ func (c *Client) Explain( if !c.config.AutoRetry() { err = call(ctx) - return + return e, err } err = retry.Retry(ctx, call, retry.WithStackTrace(), @@ -146,8 +156,10 @@ func (c *Client) explain( ctx context.Context, query string, mode scripting.ExplainMode, -) (e table.ScriptingYQLExplanation, err error) { +) (table.ScriptingYQLExplanation, error) { var ( + e table.ScriptingYQLExplanation + err error onDone = trace.ScriptingOnExplain(c.config.Trace(), &ctx, stack.FunctionID(""), query, @@ -194,7 +206,11 @@ func (c *Client) StreamExecute( ctx context.Context, query string, params *table.QueryParameters, -) (r result.StreamResult, err error) { +) (result.StreamResult, error) { + var ( + r result.StreamResult + err error + ) if c == nil { return r, xerrors.WithStackTrace(errNilClient) } @@ -206,7 +222,7 @@ func (c *Client) StreamExecute( if !c.config.AutoRetry() { err = call(ctx) - return + return r, err } err = retry.Retry(ctx, call, retry.WithStackTrace(), @@ -220,7 +236,7 @@ func (c *Client) streamExecute( ctx context.Context, query string, params *table.QueryParameters, -) (r result.StreamResult, err error) { +) (result.StreamResult, error) { var ( onIntermediate = trace.ScriptingOnStreamExecute(c.config.Trace(), &ctx, stack.FunctionID(""), @@ -237,6 +253,7 @@ func (c *Client) streamExecute( operation.ModeSync, ), } + err error ) defer func() { a.Free() @@ -256,9 +273,9 @@ func (c *Client) streamExecute( return scanner.NewStream(ctx, func(ctx context.Context) ( - set *Ydb.ResultSet, - stats *Ydb_TableStats.QueryStats, - err error, + *Ydb.ResultSet, + *Ydb_TableStats.QueryStats, + error, ) { defer func() { onIntermediate(xerrors.HideEOF(err)) @@ -286,7 +303,8 @@ func (c *Client) streamExecute( ) } -func (c *Client) Close(ctx context.Context) (err error) { +func (c *Client) Close(ctx context.Context) error { + var err error if c == nil { return xerrors.WithStackTrace(errNilClient) } diff --git a/internal/stack/record.go b/internal/stack/record.go index 3ae77866f..e3d0abca5 100644 --- a/internal/stack/record.go +++ b/internal/stack/record.go @@ -70,7 +70,8 @@ type call struct { line int } -func Call(depth int) (c call) { +func Call(depth int) call { + var c call c.function, c.file, c.line, _ = runtime.Caller(depth + 1) return c diff --git a/internal/table/client.go b/internal/table/client.go index 505a66f01..7ad66049a 100644 --- a/internal/table/client.go +++ b/internal/table/client.go @@ -35,7 +35,7 @@ type balancer interface { } func New(ctx context.Context, balancer balancer, config *config.Config) (*Client, error) { - return newClient(ctx, balancer, func(ctx context.Context) (s *session, err error) { + return newClient(ctx, balancer, func(ctx context.Context) (*session, error) { return newSession(ctx, balancer, config) }, config) } @@ -45,12 +45,15 @@ func newClient( balancer balancer, builder sessionBuilder, config *config.Config, -) (c *Client, finalErr error) { - onDone := trace.TableOnInit(config.Trace(), &ctx, stack.FunctionID("")) +) (*Client, error) { + var ( + finalErr error + onDone = trace.TableOnInit(config.Trace(), &ctx, stack.FunctionID("")) + ) defer func() { onDone(config.SizeLimit(), finalErr) }() - c = &Client{ + c := &Client{ clock: config.Clock(), config: config, cc: balancer, @@ -119,8 +122,11 @@ func withCreateSessionOnClose(onClose func(s *session)) createSessionOption { } } -func (c *Client) createSession(ctx context.Context, opts ...createSessionOption) (s *session, err error) { - options := createSessionOptions{} +func (c *Client) createSession(ctx context.Context, opts ...createSessionOption) (*session, error) { + var ( + s *session + options = createSessionOptions{} + ) for _, o := range opts { if o != nil { o(&options) @@ -223,14 +229,17 @@ func (c *Client) createSession(ctx context.Context, opts ...createSessionOption) } } -func (c *Client) CreateSession(ctx context.Context, opts ...table.Option) (_ table.ClosableSession, err error) { +func (c *Client) CreateSession(ctx context.Context, opts ...table.Option) (table.ClosableSession, error) { if c == nil { return nil, xerrors.WithStackTrace(errNilClient) } if c.isClosed() { return nil, xerrors.WithStackTrace(errClosedClient) } - var s *session + var ( + s *session + err error + ) createSession := func(ctx context.Context) (*session, error) { s, err = c.createSession(ctx) if err != nil { @@ -248,7 +257,7 @@ func (c *Client) CreateSession(ctx context.Context, opts ...table.Option) (_ tab return s, nil } err = retry.Retry(ctx, - func(ctx context.Context) (err error) { + func(ctx context.Context) error { s, err = createSession(ctx) if err != nil { return xerrors.WithStackTrace(err) @@ -289,7 +298,7 @@ func (c *Client) isClosed() bool { } // c.mu must NOT be held. -func (c *Client) internalPoolCreateSession(ctx context.Context) (s *session, err error) { +func (c *Client) internalPoolCreateSession(ctx context.Context) (*session, error) { if c.isClosed() { return nil, errClosedClient } @@ -312,7 +321,7 @@ func (c *Client) internalPoolCreateSession(ctx context.Context) (s *session, err }) }() - s, err = c.createSession( + s, err := c.createSession( meta.WithAllowFeatures(ctx, metaHeaders.HintSessionBalancer, ), @@ -364,7 +373,7 @@ func withTrace(t *trace.Table) getOption { } } -func (c *Client) internalPoolGet(ctx context.Context, opts ...getOption) (s *session, err error) { +func (c *Client) internalPoolGet(ctx context.Context, opts ...getOption) (*session, error) { if c.isClosed() { return nil, xerrors.WithStackTrace(errClosedClient) } @@ -380,7 +389,11 @@ func (c *Client) internalPoolGet(ctx context.Context, opts ...getOption) (s *ses } } - onDone := trace.TableOnPoolGet(o.t, &ctx, stack.FunctionID("")) + var ( + s *session + err error + onDone = trace.TableOnPoolGet(o.t, &ctx, stack.FunctionID("")) + ) defer func() { onDone(s, i, err) }() @@ -460,15 +473,17 @@ func (c *Client) internalPoolGet(ctx context.Context, opts ...getOption) (s *ses // Get returns first idle session from the Client and removes it from // there. If no items stored in Client it creates new one returns it. -func (c *Client) Get(ctx context.Context) (s *session, err error) { +func (c *Client) Get(ctx context.Context) (*session, error) { return c.internalPoolGet(ctx) } -func (c *Client) internalPoolWaitFromCh(ctx context.Context, t *trace.Table) (s *session, err error) { +func (c *Client) internalPoolWaitFromCh(ctx context.Context, t *trace.Table) (*session, error) { var ( - ch *chan *session - el *list.Element // Element in the wait queue. - ok bool + ch *chan *session + el *list.Element // Element in the wait queue. + ok bool + s *session + err error ) c.mu.WithLock(func() { @@ -536,10 +551,13 @@ func (c *Client) internalPoolWaitFromCh(ctx context.Context, t *trace.Table) (s // Note that Put() must be called only once after being created or received by // Get() or Take() calls. In other way it will produce unexpected behavior or // panic. -func (c *Client) Put(ctx context.Context, s *session) (err error) { - onDone := trace.TableOnPoolPut(c.config.Trace(), &ctx, - stack.FunctionID(""), - s, +func (c *Client) Put(ctx context.Context, s *session) error { + var ( + err error + onDone = trace.TableOnPoolPut(c.config.Trace(), &ctx, + stack.FunctionID(""), + s, + ) ) defer func() { onDone(err) @@ -584,7 +602,7 @@ func (c *Client) Put(ctx context.Context, s *session) (err error) { // It also stops all underlying timers and goroutines. // It returns first error occurred during stale sessions' deletion. // Note that even on error it calls Close() on each session. -func (c *Client) Close(ctx context.Context) (err error) { +func (c *Client) Close(ctx context.Context) error { if c == nil { return xerrors.WithStackTrace(errNilClient) } @@ -597,7 +615,10 @@ func (c *Client) Close(ctx context.Context) (err error) { default: close(c.done) - onDone := trace.TableOnClose(c.config.Trace(), &ctx, stack.FunctionID("")) + var ( + err error + onDone = trace.TableOnClose(c.config.Trace(), &ctx, stack.FunctionID("")) + ) defer func() { onDone(err) }() @@ -631,7 +652,7 @@ func (c *Client) Close(ctx context.Context) (err error) { // - deadline was canceled or deadlined // - retry operation returned nil as error // Warning: if deadline without deadline or cancellation func Retry will be worked infinite -func (c *Client) Do(ctx context.Context, op table.Operation, opts ...table.Option) (finalErr error) { +func (c *Client) Do(ctx context.Context, op table.Operation, opts ...table.Option) error { if c == nil { return xerrors.WithStackTrace(errNilClient) } @@ -640,6 +661,8 @@ func (c *Client) Do(ctx context.Context, op table.Operation, opts ...table.Optio return xerrors.WithStackTrace(errClosedClient) } + var finalErr error + config := c.retryOptions(opts...) attempts, onIntermediate := 0, trace.TableOnDo(config.Trace, &ctx, @@ -661,7 +684,7 @@ func (c *Client) Do(ctx context.Context, op table.Operation, opts ...table.Optio return nil } -func (c *Client) DoTx(ctx context.Context, op table.TxOperation, opts ...table.Option) (finalErr error) { +func (c *Client) DoTx(ctx context.Context, op table.TxOperation, opts ...table.Option) error { if c == nil { return xerrors.WithStackTrace(errNilClient) } @@ -670,6 +693,8 @@ func (c *Client) DoTx(ctx context.Context, op table.TxOperation, opts ...table.O return xerrors.WithStackTrace(errClosedClient) } + var finalErr error + config := c.retryOptions(opts...) attempts, onIntermediate := 0, trace.TableOnDoTx(config.Trace, &ctx, @@ -808,10 +833,14 @@ func (c *Client) internalPoolPutWaitCh(ch *chan *session) { //nolint:gocritic } // c.mu must be held. -func (c *Client) internalPoolPeekFirstIdle() (s *session, touched time.Time) { +func (c *Client) internalPoolPeekFirstIdle() (*session, time.Time) { + var ( + s *session + touched time.Time + ) el := c.idle.Front() if el == nil { - return + return s, touched } s = el.Value.(*session) info, has := c.index[s] @@ -837,7 +866,7 @@ func (c *Client) internalPoolRemoveFirstIdle() *session { } // c.mu must be held. -func (c *Client) internalPoolNotify(s *session) (notified bool) { +func (c *Client) internalPoolNotify(s *session) bool { for el := c.waitQ.Front(); el != nil; el = c.waitQ.Front() { // Some goroutine is waiting for a session. // diff --git a/internal/table/client_test.go b/internal/table/client_test.go index a04672a4c..342721a1c 100644 --- a/internal/table/client_test.go +++ b/internal/table/client_test.go @@ -532,7 +532,7 @@ func TestSessionPoolSizeLimitOverflow(t *testing.T) { p := newClientWithStubBuilder( t, testutil.NewBalancer(testutil.WithInvokeHandlers(testutil.InvokeHandlers{ - testutil.TableCreateSession: func(interface{}) (result proto.Message, _ error) { + testutil.TableCreateSession: func(interface{}) (proto.Message, error) { return &Ydb_Table.CreateSessionResult{ SessionId: testutil.SessionID(), }, nil @@ -887,7 +887,11 @@ func newClientWithStubBuilder( return c } -func (s *StubBuilder) createSession(ctx context.Context) (session *session, err error) { +func (s *StubBuilder) createSession(ctx context.Context) (*session, error) { + var ( + session *session + err error + ) defer s.mu.WithLock(func() { if session != nil { s.actual++ diff --git a/internal/table/retry.go b/internal/table/retry.go index d6577d7ad..13666062f 100644 --- a/internal/table/retry.go +++ b/internal/table/retry.go @@ -29,9 +29,11 @@ func do( op table.Operation, onAttempt func(err error), opts ...retry.Option, -) (err error) { +) error { + var err error + return retryBackoff(ctx, c, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { defer func() { if onAttempt != nil { onAttempt(err) @@ -66,8 +68,10 @@ func retryBackoff( op table.Operation, opts ...retry.Option, ) error { + var err error + return retry.Retry(ctx, - func(ctx context.Context) (err error) { + func(ctx context.Context) error { var s *session s, err = p.Get(ctx) diff --git a/internal/table/retry_test.go b/internal/table/retry_test.go index 008633786..0f9a8bd66 100644 --- a/internal/table/retry_test.go +++ b/internal/table/retry_test.go @@ -446,7 +446,7 @@ func TestRetryWithCustomErrors(t *testing.T) { ctx, p, config.New(), - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { sessions[s]++ i++ if i < limit { diff --git a/internal/table/scanner/result.go b/internal/table/scanner/result.go index 8cf05cf8e..7694ce1f0 100644 --- a/internal/table/scanner/result.go +++ b/internal/table/scanner/result.go @@ -151,7 +151,7 @@ func (r *baseResult) Reset(set *Ydb.ResultSet, columnNames ...string) { } } -func (r *unaryResult) NextResultSetErr(ctx context.Context, columns ...string) (err error) { +func (r *unaryResult) NextResultSetErr(ctx context.Context, columns ...string) error { if r.isClosed() { return xerrors.WithStackTrace(errAlreadyClosed) } @@ -168,7 +168,7 @@ func (r *unaryResult) NextResultSet(ctx context.Context, columns ...string) bool return r.NextResultSetErr(ctx, columns...) == nil } -func (r *streamResult) nextResultSetErr(ctx context.Context, columns ...string) (err error) { +func (r *streamResult) nextResultSetErr(ctx context.Context, columns ...string) error { // skipping second recv because first call of recv is from New Stream(), second call is from user if r.nextResultSetCounter.Add(1) == 2 { r.setColumnIndexes(columns) @@ -194,11 +194,11 @@ func (r *streamResult) nextResultSetErr(ctx context.Context, columns ...string) return ctx.Err() } -func (r *streamResult) NextResultSetErr(ctx context.Context, columns ...string) (err error) { +func (r *streamResult) NextResultSetErr(ctx context.Context, columns ...string) error { if r.isClosed() { return xerrors.WithStackTrace(errAlreadyClosed) } - if err = r.Err(); err != nil { + if err := r.Err(); err != nil { return xerrors.WithStackTrace(err) } if err := r.nextResultSetErr(ctx, columns...); err != nil { @@ -236,7 +236,7 @@ func (r *baseResult) Stats() stats.QueryStats { } // Close closes the result, preventing further iteration. -func (r *streamResult) Close() (err error) { +func (r *streamResult) Close() error { if r.closed.CompareAndSwap(false, true) { return r.close(r.Err()) } diff --git a/internal/table/scanner/scan_raw.go b/internal/table/scanner/scan_raw.go index 1a0c8be98..7311c7b6e 100644 --- a/internal/table/scanner/scan_raw.go +++ b/internal/table/scanner/scan_raw.go @@ -20,7 +20,7 @@ type rawConverter struct { *scanner } -func (s *rawConverter) String() (v []byte) { +func (s *rawConverter) String() []byte { s.unwrap() return s.bytes() @@ -41,7 +41,11 @@ func (s *rawConverter) Path() string { return buf.String() } -func (s *rawConverter) WritePathTo(w io.Writer) (n int64, err error) { +func (s *rawConverter) WritePathTo(w io.Writer) (int64, error) { + var ( + n int64 + err error + ) for sp := 0; sp < s.stack.size(); sp++ { if sp > 0 { var m int @@ -71,133 +75,133 @@ func (s *rawConverter) Type() types.Type { return s.getType() } -func (s *rawConverter) Bool() (v bool) { +func (s *rawConverter) Bool() bool { if s.Err() != nil { - return + return false } s.unwrap() return s.bool() } -func (s *rawConverter) Int8() (v int8) { +func (s *rawConverter) Int8() int8 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.int8() } -func (s *rawConverter) Uint8() (v uint8) { +func (s *rawConverter) Uint8() uint8 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.uint8() } -func (s *rawConverter) Int16() (v int16) { +func (s *rawConverter) Int16() int16 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.int16() } -func (s *rawConverter) Uint16() (v uint16) { +func (s *rawConverter) Uint16() uint16 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.uint16() } -func (s *rawConverter) Int32() (v int32) { +func (s *rawConverter) Int32() int32 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.int32() } -func (s *rawConverter) Uint32() (v uint32) { +func (s *rawConverter) Uint32() uint32 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.uint32() } -func (s *rawConverter) Int64() (v int64) { +func (s *rawConverter) Int64() int64 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.int64() } -func (s *rawConverter) Uint64() (v uint64) { +func (s *rawConverter) Uint64() uint64 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.uint64() } -func (s *rawConverter) Float() (v float32) { +func (s *rawConverter) Float() float32 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.float() } -func (s *rawConverter) Double() (v float64) { +func (s *rawConverter) Double() float64 { if s.Err() != nil { - return + return 0 } s.unwrap() return s.double() } -func (s *rawConverter) Date() (v time.Time) { +func (s *rawConverter) Date() time.Time { s.unwrap() return value.DateToTime(s.uint32()) } -func (s *rawConverter) Datetime() (v time.Time) { +func (s *rawConverter) Datetime() time.Time { s.unwrap() return value.DatetimeToTime(s.uint32()) } -func (s *rawConverter) Timestamp() (v time.Time) { +func (s *rawConverter) Timestamp() time.Time { s.unwrap() return value.TimestampToTime(s.uint64()) } -func (s *rawConverter) Interval() (v time.Duration) { +func (s *rawConverter) Interval() time.Duration { s.unwrap() return value.IntervalToDuration(s.int64()) } -func (s *rawConverter) TzDate() (v time.Time) { +func (s *rawConverter) TzDate() time.Time { s.unwrap() if s.isNull() { - return + return time.Time{} } src, err := value.TzDateToTime(s.text()) if err != nil { @@ -207,10 +211,10 @@ func (s *rawConverter) TzDate() (v time.Time) { return src } -func (s *rawConverter) TzDatetime() (v time.Time) { +func (s *rawConverter) TzDatetime() time.Time { s.unwrap() if s.isNull() { - return + return time.Time{} } src, err := value.TzDatetimeToTime(s.text()) if err != nil { @@ -220,10 +224,10 @@ func (s *rawConverter) TzDatetime() (v time.Time) { return src } -func (s *rawConverter) TzTimestamp() (v time.Time) { +func (s *rawConverter) TzTimestamp() time.Time { s.unwrap() if s.isNull() { - return + return time.Time{} } src, err := value.TzTimestampToTime(s.text()) if err != nil { @@ -233,45 +237,45 @@ func (s *rawConverter) TzTimestamp() (v time.Time) { return src } -func (s *rawConverter) UTF8() (v string) { +func (s *rawConverter) UTF8() string { if s.Err() != nil { - return + return "" } s.unwrap() return s.text() } -func (s *rawConverter) YSON() (v []byte) { +func (s *rawConverter) YSON() []byte { s.unwrap() return s.bytes() } -func (s *rawConverter) JSON() (v []byte) { +func (s *rawConverter) JSON() []byte { s.unwrap() return xstring.ToBytes(s.text()) } -func (s *rawConverter) JSONDocument() (v []byte) { +func (s *rawConverter) JSONDocument() []byte { s.unwrap() return xstring.ToBytes(s.text()) } -func (s *rawConverter) UUID() (v [16]byte) { +func (s *rawConverter) UUID() [16]byte { if s.Err() != nil { - return + return [16]byte{} } s.unwrap() return s.uint128() } -func (s *rawConverter) DyNumber() (v string) { +func (s *rawConverter) DyNumber() string { if s.Err() != nil { - return + return "" } s.unwrap() @@ -321,16 +325,17 @@ func (s *rawConverter) IsOptional() bool { // --------non-primitive--------- -func (s *rawConverter) ListIn() (size int) { +func (s *rawConverter) ListIn() int { + var v int if s.Err() != nil { - return 0 + return v } x := s.stack.current() if s.assertTypeList(x.t) != nil { return s.itemsIn() } - return 0 + return v } func (s *rawConverter) ListItem(i int) { @@ -360,16 +365,17 @@ func (s *rawConverter) ListOut() { } } -func (s *rawConverter) TupleIn() (size int) { +func (s *rawConverter) TupleIn() int { + var v int if s.Err() != nil { - return 0 + return v } x := s.stack.current() if s.assertTypeTuple(x.t) != nil { return s.itemsIn() } - return 0 + return v } func (s *rawConverter) TupleItem(i int) { @@ -399,25 +405,27 @@ func (s *rawConverter) TupleOut() { } } -func (s *rawConverter) StructIn() (size int) { +func (s *rawConverter) StructIn() int { + var v int if s.Err() != nil { - return 0 + return v } x := s.stack.current() if s.assertTypeStruct(x.t) != nil { return s.itemsIn() } - return 0 + return v } -func (s *rawConverter) StructField(i int) (name string) { +func (s *rawConverter) StructField(i int) string { + var name string if s.Err() != nil { - return + return name } p := s.stack.parent() if !s.itemsBoundsCheck(p.v.Items, i) { - return + return name } if t := s.assertTypeStruct(p.t); t != nil { m := t.StructType.Members[i] @@ -430,7 +438,7 @@ func (s *rawConverter) StructField(i int) (name string) { }) } - return + return name } func (s *rawConverter) StructOut() { @@ -443,16 +451,17 @@ func (s *rawConverter) StructOut() { } } -func (s *rawConverter) DictIn() (size int) { +func (s *rawConverter) DictIn() int { + var v int if s.Err() != nil { - return 0 + return v } x := s.stack.current() if s.assertTypeDict(x.t) != nil { return s.pairsIn() } - return 0 + return v } func (s *rawConverter) DictKey(i int) { @@ -499,18 +508,18 @@ func (s *rawConverter) DictOut() { } } -func (s *rawConverter) Variant() (name string, index uint32) { +func (s *rawConverter) Variant() (name string, index uint32) { //nolint:nonamedreturns //gocritic more important if s.Err() != nil { - return + return name, index } x := s.stack.current() t := s.assertTypeVariant(x.t) if t == nil { - return + return name, index } v, index := s.variant() if v == nil { - return + return name, index } name, typ := s.unwrapVariantType(t, index) s.stack.scanItem.v = nil @@ -545,26 +554,28 @@ func (s *rawConverter) Unwrap() { }) } -func (s *rawConverter) Decimal(t types.Type) (v [16]byte) { +func (s *rawConverter) Decimal(t types.Type) [16]byte { + v := [16]byte{} if s.Err() != nil { - return + return v } s.unwrap() if !s.assertCurrentTypeDecimal(t) { - return + return v } return s.uint128() } -func (s *rawConverter) UnwrapDecimal() (v types.Decimal) { +func (s *rawConverter) UnwrapDecimal() types.Decimal { + v := types.Decimal{} if s.Err() != nil { - return + return v } s.unwrap() d := s.assertTypeDecimal(s.stack.current().t) if d == nil { - return + return v } return types.Decimal{ @@ -595,14 +606,15 @@ func (s *rawConverter) isCurrentTypeDecimal() bool { return ok } -func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32) (name string, t *Ydb.Type) { +func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32) (string, *Ydb.Type) { i := int(index) + t := Ydb.Type{} switch x := typ.VariantType.Type.(type) { case *Ydb.VariantType_TupleItems: if i >= len(x.TupleItems.Elements) { _ = s.errorf(0, "unimplemented") - return + return "", &t } return "", x.TupleItems.Elements[i] @@ -611,7 +623,7 @@ func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32 if i >= len(x.StructItems.Members) { _ = s.errorf(0, "unimplemented") - return + return "", &t } m := x.StructItems.Members[i] @@ -622,15 +634,15 @@ func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32 } } -func (s *rawConverter) variant() (v *Ydb.Value, index uint32) { - v = s.unwrapValue() +func (s *rawConverter) variant() (*Ydb.Value, uint32) { + v := s.unwrapValue() if v == nil { - return + return &Ydb.Value{}, 0 } x := s.stack.current() // Is not nil if unwrapValue succeeded. - index = x.v.VariantIndex + index := x.v.VariantIndex - return + return v, index } func (s *rawConverter) itemsIn() int { @@ -679,13 +691,13 @@ func (s *rawConverter) boundsCheck(n, i int) bool { return true } -func (s *scanner) assertTypeOptional(typ *Ydb.Type) (t *Ydb.Type_OptionalType) { +func (s *scanner) assertTypeOptional(typ *Ydb.Type) *Ydb.Type_OptionalType { x := typ.Type - if t, _ = x.(*Ydb.Type_OptionalType); t == nil { + if t, _ := x.(*Ydb.Type_OptionalType); t == nil { s.typeError(x, t) } - return + return &Ydb.Type_OptionalType{} } func (s *rawConverter) assertCurrentTypeNullable() bool { @@ -743,58 +755,58 @@ func (s *rawConverter) assertCurrentTypeDecimal(t types.Type) bool { return true } -func (s *rawConverter) assertTypeList(typ *Ydb.Type) (t *Ydb.Type_ListType) { +func (s *rawConverter) assertTypeList(typ *Ydb.Type) *Ydb.Type_ListType { x := typ.Type - if t, _ = x.(*Ydb.Type_ListType); t == nil { + if t, _ := x.(*Ydb.Type_ListType); t == nil { s.typeError(x, t) } - return + return &Ydb.Type_ListType{} } -func (s *rawConverter) assertTypeTuple(typ *Ydb.Type) (t *Ydb.Type_TupleType) { +func (s *rawConverter) assertTypeTuple(typ *Ydb.Type) *Ydb.Type_TupleType { x := typ.Type - if t, _ = x.(*Ydb.Type_TupleType); t == nil { + if t, _ := x.(*Ydb.Type_TupleType); t == nil { s.typeError(x, t) } - return + return &Ydb.Type_TupleType{} } -func (s *rawConverter) assertTypeStruct(typ *Ydb.Type) (t *Ydb.Type_StructType) { +func (s *rawConverter) assertTypeStruct(typ *Ydb.Type) *Ydb.Type_StructType { x := typ.Type - if t, _ = x.(*Ydb.Type_StructType); t == nil { + if t, _ := x.(*Ydb.Type_StructType); t == nil { s.typeError(x, t) } - return + return &Ydb.Type_StructType{} } -func (s *rawConverter) assertTypeDict(typ *Ydb.Type) (t *Ydb.Type_DictType) { +func (s *rawConverter) assertTypeDict(typ *Ydb.Type) *Ydb.Type_DictType { x := typ.Type - if t, _ = x.(*Ydb.Type_DictType); t == nil { + if t, _ := x.(*Ydb.Type_DictType); t == nil { s.typeError(x, t) } - return + return &Ydb.Type_DictType{} } -func (s *rawConverter) assertTypeDecimal(typ *Ydb.Type) (t *Ydb.Type_DecimalType) { +func (s *rawConverter) assertTypeDecimal(typ *Ydb.Type) *Ydb.Type_DecimalType { x := typ.Type - if t, _ = x.(*Ydb.Type_DecimalType); t == nil { + if t, _ := x.(*Ydb.Type_DecimalType); t == nil { s.typeError(x, t) } - return + return &Ydb.Type_DecimalType{} } -func (s *rawConverter) assertTypeVariant(typ *Ydb.Type) (t *Ydb.Type_VariantType) { +func (s *rawConverter) assertTypeVariant(typ *Ydb.Type) *Ydb.Type_VariantType { x := typ.Type - if t, _ = x.(*Ydb.Type_VariantType); t == nil { + if t, _ := x.(*Ydb.Type_VariantType); t == nil { s.typeError(x, t) } - return + return &Ydb.Type_VariantType{} } func (s *rawConverter) boundsError(n, i int) { diff --git a/internal/table/scanner/scanner.go b/internal/table/scanner/scanner.go index 415ebd669..fcd741648 100644 --- a/internal/table/scanner/scanner.go +++ b/internal/table/scanner/scanner.go @@ -99,7 +99,7 @@ func (s *scanner) NextRow() bool { return true } -func (s *scanner) preScanChecks(lenValues int) (err error) { +func (s *scanner) preScanChecks(lenValues int) error { if s.columnIndexes != nil { if len(s.columnIndexes) != lenValues { return s.errorf( @@ -120,21 +120,21 @@ func (s *scanner) preScanChecks(lenValues int) (err error) { return s.Err() } -func (s *scanner) ScanWithDefaults(values ...indexed.Required) (err error) { - if err = s.preScanChecks(len(values)); err != nil { - return +func (s *scanner) ScanWithDefaults(values ...indexed.Required) error { + if err := s.preScanChecks(len(values)); err != nil { + return err } for i := range values { if _, ok := values[i].(named.Value); ok { panic("dont use NamedValue with ScanWithDefaults. Use ScanNamed instead") } if s.columnIndexes == nil { - if err = s.seekItemByID(i); err != nil { - return + if err := s.seekItemByID(i); err != nil { + return err } } else { - if err = s.seekItemByID(s.columnIndexes[i]); err != nil { - return + if err := s.seekItemByID(s.columnIndexes[i]); err != nil { + return err } } if s.isCurrentTypeOptional() { @@ -148,21 +148,21 @@ func (s *scanner) ScanWithDefaults(values ...indexed.Required) (err error) { return s.Err() } -func (s *scanner) Scan(values ...indexed.RequiredOrOptional) (err error) { - if err = s.preScanChecks(len(values)); err != nil { - return +func (s *scanner) Scan(values ...indexed.RequiredOrOptional) error { + if err := s.preScanChecks(len(values)); err != nil { + return err } for i := range values { if _, ok := values[i].(named.Value); ok { panic("dont use NamedValue with Scan. Use ScanNamed instead") } if s.columnIndexes == nil { - if err = s.seekItemByID(i); err != nil { - return + if err := s.seekItemByID(i); err != nil { + return err } } else { - if err = s.seekItemByID(s.columnIndexes[i]); err != nil { - return + if err := s.seekItemByID(s.columnIndexes[i]); err != nil { + return err } } if s.isCurrentTypeOptional() { @@ -269,7 +269,8 @@ func (s *scanner) path() string { return buf.String() } -func (s *scanner) writePathTo(w io.Writer) (n int64, err error) { +func (s *scanner) writePathTo(w io.Writer) (int64, error) { + var n int64 x := s.stack.current() st := x.name m, err := io.WriteString(w, st) @@ -496,25 +497,25 @@ func (s *scanner) unwrap() { s.stack.scanItem.t = t.OptionalType.Item } -func (s *scanner) unwrapValue() (v *Ydb.Value) { +func (s *scanner) unwrapValue() *Ydb.Value { x, _ := s.stack.currentValue().(*Ydb.Value_NestedValue) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return &Ydb.Value{} } return x.NestedValue } -func (s *scanner) unwrapDecimal() (v types.Decimal) { +func (s *scanner) unwrapDecimal() types.Decimal { if s.Err() != nil { - return + return types.Decimal{} } s.unwrap() d := s.assertTypeDecimal(s.stack.current().t) if d == nil { - return + return types.Decimal{} } return types.Decimal{ @@ -524,175 +525,190 @@ func (s *scanner) unwrapDecimal() (v types.Decimal) { } } -func (s *scanner) assertTypeDecimal(typ *Ydb.Type) (t *Ydb.Type_DecimalType) { +func (s *scanner) assertTypeDecimal(typ *Ydb.Type) *Ydb.Type_DecimalType { + var t *Ydb.Type_DecimalType x := typ.Type if t, _ = x.(*Ydb.Type_DecimalType); t == nil { s.typeError(x, t) } - return + return t } -func (s *scanner) bool() (v bool) { +func (s *scanner) bool() bool { x, _ := s.stack.currentValue().(*Ydb.Value_BoolValue) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return false } return x.BoolValue } -func (s *scanner) int8() (v int8) { +func (s *scanner) int8() int8 { + var v int8 d := s.int32() if d < math.MinInt8 || math.MaxInt8 < d { _ = s.overflowError(d, v) - return + return v } return int8(d) } -func (s *scanner) uint8() (v uint8) { +func (s *scanner) uint8() uint8 { + var v uint8 d := s.uint32() if d > math.MaxUint8 { _ = s.overflowError(d, v) - return + return v } return uint8(d) } -func (s *scanner) int16() (v int16) { +func (s *scanner) int16() int16 { + var v int16 d := s.int32() if d < math.MinInt16 || math.MaxInt16 < d { _ = s.overflowError(d, v) - return + return v } return int16(d) } -func (s *scanner) uint16() (v uint16) { +func (s *scanner) uint16() uint16 { + var v uint16 d := s.uint32() if d > math.MaxUint16 { _ = s.overflowError(d, v) - return + return v } return uint16(d) } -func (s *scanner) int32() (v int32) { +func (s *scanner) int32() int32 { + var v int32 x, _ := s.stack.currentValue().(*Ydb.Value_Int32Value) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.Int32Value } -func (s *scanner) uint32() (v uint32) { +func (s *scanner) uint32() uint32 { + var v uint32 x, _ := s.stack.currentValue().(*Ydb.Value_Uint32Value) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.Uint32Value } -func (s *scanner) int64() (v int64) { +func (s *scanner) int64() int64 { + var v int64 x, _ := s.stack.currentValue().(*Ydb.Value_Int64Value) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.Int64Value } -func (s *scanner) uint64() (v uint64) { +func (s *scanner) uint64() uint64 { + var v uint64 x, _ := s.stack.currentValue().(*Ydb.Value_Uint64Value) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.Uint64Value } -func (s *scanner) float() (v float32) { +func (s *scanner) float() float32 { + var v float32 x, _ := s.stack.currentValue().(*Ydb.Value_FloatValue) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.FloatValue } -func (s *scanner) double() (v float64) { +func (s *scanner) double() float64 { + var v float64 x, _ := s.stack.currentValue().(*Ydb.Value_DoubleValue) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.DoubleValue } -func (s *scanner) bytes() (v []byte) { +func (s *scanner) bytes() []byte { + var v []byte x, _ := s.stack.currentValue().(*Ydb.Value_BytesValue) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.BytesValue } -func (s *scanner) text() (v string) { +func (s *scanner) text() string { + var v string x, _ := s.stack.currentValue().(*Ydb.Value_TextValue) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.TextValue } -func (s *scanner) low128() (v uint64) { +func (s *scanner) low128() uint64 { + var v uint64 x, _ := s.stack.currentValue().(*Ydb.Value_Low_128) if x == nil { s.valueTypeError(s.stack.currentValue(), x) - return + return v } return x.Low_128 } -func (s *scanner) uint128() (v [16]byte) { +func (s *scanner) uint128() [16]byte { + var v [16]byte c := s.stack.current() if c.isEmpty() { _ = s.errorf(0, "not implemented convert to [16]byte") - return + return v } lo := s.low128() hi := c.v.High_128 diff --git a/internal/table/scanner/scanner_test.go b/internal/table/scanner/scanner_test.go index cc595229a..ca4d2fdd5 100644 --- a/internal/table/scanner/scanner_test.go +++ b/internal/table/scanner/scanner_test.go @@ -512,8 +512,8 @@ func valueFromPrimitiveTypeID(c *column, r xrand.Rand) (*Ydb.Value, interface{}) } } -func getResultSet(count int, col []*column) (result *Ydb.ResultSet, testValues [][]indexed.RequiredOrOptional) { - result = &Ydb.ResultSet{} +func getResultSet(count int, col []*column) (*Ydb.ResultSet, [][]indexed.RequiredOrOptional) { + result := &Ydb.ResultSet{} for _, c := range col { t := &Ydb.Type{ Type: &Ydb.Type_TypeId{ @@ -539,7 +539,7 @@ func getResultSet(count int, col []*column) (result *Ydb.ResultSet, testValues [ } r := xrand.New(xrand.WithLock()) - testValues = make([][]indexed.RequiredOrOptional, count) + testValues := make([][]indexed.RequiredOrOptional, count) for i := 0; i < count; i++ { var items []*Ydb.Value var vals []indexed.RequiredOrOptional @@ -565,7 +565,8 @@ func TestScanSqlTypes(t *testing.T) { s.reset(set, test.setColumns...) for s.NextRow() { if test.columns[0].testDefault { - if err := s.ScanWithDefaults(func() (values []indexed.Required) { + if err := s.ScanWithDefaults(func() []indexed.Required { + var values []indexed.Required for _, v := range test.values { values = append(values, v) } diff --git a/internal/table/scanner/stats.go b/internal/table/scanner/stats.go index 250205c5b..07ea91f28 100644 --- a/internal/table/scanner/stats.go +++ b/internal/table/scanner/stats.go @@ -19,7 +19,7 @@ func (s *queryStats) ProcessCPUTime() time.Duration { return s.processCPUTime } -func (s *queryStats) Compilation() (c *stats.CompilationStats) { +func (s *queryStats) Compilation() *stats.CompilationStats { if s.stats == nil || s.stats.Compilation == nil { return nil } @@ -49,13 +49,17 @@ func (s *queryStats) TotalDuration() time.Duration { // NextPhase returns next execution phase within query. // If ok flag is false, then there are no more phases and p is invalid. -func (s *queryStats) NextPhase() (p stats.QueryPhase, ok bool) { +func (s *queryStats) NextPhase() (stats.QueryPhase, bool) { + var ( + qPhase stats.QueryPhase + ok bool + ) if s.pos >= len(s.stats.QueryPhases) { - return + return qPhase, ok } x := s.stats.QueryPhases[s.pos] if x == nil { - return + return qPhase, ok } s.pos++ @@ -83,9 +87,9 @@ type queryPhase struct { // // If ok flag is false, then there are no more accessed tables and t is // invalid. -func (q *queryPhase) NextTableAccess() (t *stats.TableAccess, ok bool) { +func (q *queryPhase) NextTableAccess() (*stats.TableAccess, bool) { if q.pos >= len(q.tables) { - return + return &stats.TableAccess{}, false } x := q.tables[q.pos] q.pos++ diff --git a/internal/table/session.go b/internal/table/session.go index 7c904b247..d5525a168 100644 --- a/internal/table/session.go +++ b/internal/table/session.go @@ -115,9 +115,13 @@ func (s *session) isClosing() bool { } func newSession(ctx context.Context, cc grpc.ClientConnInterface, config *config.Config) ( - s *session, err error, + *session, error, ) { - onDone := trace.TableOnSessionNew(config.Trace(), &ctx, stack.FunctionID("")) + var ( + s *session + err error + onDone = trace.TableOnSessionNew(config.Trace(), &ctx, stack.FunctionID("")) + ) defer func() { onDone(s, err) }() @@ -173,11 +177,12 @@ func (s *session) ID() string { return s.id } -func (s *session) Close(ctx context.Context) (err error) { +func (s *session) Close(ctx context.Context) error { if s.isClosed() { return xerrors.WithStackTrace(errSessionClosed) } + var err error s.closeOnce.Do(func() { onDone := trace.TableOnSessionDelete(s.config.Trace(), &ctx, stack.FunctionID(""), @@ -227,8 +232,9 @@ func (s *session) checkCloseHint(md metadata.MD) { } // KeepAlive keeps idle session alive. -func (s *session) KeepAlive(ctx context.Context) (err error) { +func (s *session) KeepAlive(ctx context.Context) error { var ( + err error result Ydb_Table.KeepAliveResult onDone = trace.TableOnSessionKeepAlive( s.config.Trace(), &ctx, @@ -275,7 +281,7 @@ func (s *session) CreateTable( ctx context.Context, path string, opts ...options.CreateTableOption, -) (err error) { +) error { var ( request = Ydb_Table.CreateTableRequest{ SessionId: s.id, @@ -295,7 +301,7 @@ func (s *session) CreateTable( opt.ApplyCreateTableOption((*options.CreateTableDesc)(&request), a) } } - _, err = s.tableService.CreateTable(ctx, &request) + _, err := s.tableService.CreateTable(ctx, &request) if err != nil { return xerrors.WithStackTrace(err) } @@ -308,10 +314,12 @@ func (s *session) DescribeTable( ctx context.Context, path string, opts ...options.DescribeTableOption, -) (desc options.Description, err error) { +) (options.Description, error) { var ( response *Ydb_Table.DescribeTableResponse result Ydb_Table.DescribeTableResult + desc options.Description + err error ) request := Ydb_Table.DescribeTableRequest{ SessionId: s.id, @@ -461,7 +469,7 @@ func (s *session) DropTable( ctx context.Context, path string, opts ...options.DropTableOption, -) (err error) { +) error { request := Ydb_Table.DropTableRequest{ SessionId: s.id, Path: path, @@ -477,7 +485,7 @@ func (s *session) DropTable( opt.ApplyDropTableOption((*options.DropTableDesc)(&request)) } } - _, err = s.tableService.DropTable(ctx, &request) + _, err := s.tableService.DropTable(ctx, &request) return xerrors.WithStackTrace(err) } @@ -496,7 +504,7 @@ func (s *session) AlterTable( ctx context.Context, path string, opts ...options.AlterTableOption, -) (err error) { +) error { var ( request = Ydb_Table.AlterTableRequest{ SessionId: s.id, @@ -516,7 +524,7 @@ func (s *session) AlterTable( opt.ApplyAlterTableOption((*options.AlterTableDesc)(&request), a) } } - _, err = s.tableService.AlterTable(ctx, &request) + _, err := s.tableService.AlterTable(ctx, &request) return xerrors.WithStackTrace(err) } @@ -526,7 +534,7 @@ func (s *session) CopyTable( ctx context.Context, dst, src string, opts ...options.CopyTableOption, -) (err error) { +) error { request := Ydb_Table.CopyTableRequest{ SessionId: s.id, SourcePath: src, @@ -543,7 +551,7 @@ func (s *session) CopyTable( opt((*options.CopyTableDesc)(&request)) } } - _, err = s.tableService.CopyTable(ctx, &request) + _, err := s.tableService.CopyTable(ctx, &request) if err != nil { return xerrors.WithStackTrace(err) } @@ -562,7 +570,7 @@ func copyTables( ) (*Ydb_Table.CopyTablesResponse, error) }, opts ...options.CopyTablesOption, -) (err error) { +) error { request := Ydb_Table.CopyTablesRequest{ SessionId: sessionID, OperationParams: operation.Params( @@ -580,7 +588,7 @@ func copyTables( if len(request.Tables) == 0 { return xerrors.WithStackTrace(fmt.Errorf("no CopyTablesItem: %w", errParamsRequired)) } - _, err = service.CopyTables(ctx, &request) + _, err := service.CopyTables(ctx, &request) if err != nil { return xerrors.WithStackTrace(err) } @@ -592,8 +600,8 @@ func copyTables( func (s *session) CopyTables( ctx context.Context, opts ...options.CopyTablesOption, -) (err error) { - err = copyTables(ctx, s.id, s.config.OperationTimeout(), s.config.OperationCancelAfter(), s.tableService, opts...) +) error { + err := copyTables(ctx, s.id, s.config.OperationTimeout(), s.config.OperationCancelAfter(), s.tableService, opts...) if err != nil { return xerrors.WithStackTrace(err) } @@ -606,12 +614,14 @@ func (s *session) Explain( ctx context.Context, query string, ) ( - exp table.DataQueryExplanation, - err error, + table.DataQueryExplanation, + error, ) { var ( result Ydb_Table.ExplainQueryResult response *Ydb_Table.ExplainDataQueryResponse + exp table.DataQueryExplanation + err error onDone = trace.TableOnSessionQueryExplain( s.config.Trace(), &ctx, stack.FunctionID(""), @@ -656,11 +666,12 @@ func (s *session) Explain( } // Prepare prepares data query within session s. -func (s *session) Prepare(ctx context.Context, queryText string) (_ table.Statement, err error) { +func (s *session) Prepare(ctx context.Context, queryText string) (table.Statement, error) { var ( stmt *statement response *Ydb_Table.PrepareDataQueryResponse result Ydb_Table.PrepareQueryResult + err error onDone = trace.TableOnSessionQueryPrepare( s.config.Trace(), &ctx, stack.FunctionID(""), @@ -713,7 +724,7 @@ func (s *session) Execute( params *table.QueryParameters, opts ...options.ExecuteDataQueryOption, ) ( - txr table.Transaction, r result.Result, err error, + table.Transaction, result.Result, error, ) { var ( a = allocator.New() @@ -723,6 +734,9 @@ func (s *session) Execute( IgnoreTruncated: s.config.IgnoreTruncated(), } callOptions []grpc.CallOption + txr table.Transaction + r result.Result + err error ) defer a.Free() @@ -794,12 +808,13 @@ func (s *session) executeDataQuery( ctx context.Context, a *allocator.Allocator, request *Ydb_Table.ExecuteDataQueryRequest, callOptions ...grpc.CallOption, ) ( - _ *Ydb_Table.ExecuteQueryResult, - err error, + *Ydb_Table.ExecuteQueryResult, + error, ) { var ( result = a.TableExecuteQueryResult() response *Ydb_Table.ExecuteDataQueryResponse + err error ) response, err = s.tableService.ExecuteDataQuery(ctx, request, callOptions...) @@ -820,7 +835,7 @@ func (s *session) ExecuteSchemeQuery( ctx context.Context, query string, opts ...options.ExecuteSchemeQueryOption, -) (err error) { +) error { request := Ydb_Table.ExecuteSchemeQueryRequest{ SessionId: s.id, YqlText: query, @@ -836,19 +851,21 @@ func (s *session) ExecuteSchemeQuery( opt((*options.ExecuteSchemeQueryDesc)(&request)) } } - _, err = s.tableService.ExecuteSchemeQuery(ctx, &request) + _, err := s.tableService.ExecuteSchemeQuery(ctx, &request) return xerrors.WithStackTrace(err) } // DescribeTableOptions describes supported table options. func (s *session) DescribeTableOptions(ctx context.Context) ( - desc options.TableOptionsDescription, - err error, + options.TableOptionsDescription, + error, ) { var ( response *Ydb_Table.DescribeTableOptionsResponse result Ydb_Table.DescribeTableOptionsResult + desc options.TableOptionsDescription + err error ) request := Ydb_Table.DescribeTableOptionsRequest{ OperationParams: operation.Params( @@ -983,7 +1000,7 @@ func (s *session) StreamReadTable( ctx context.Context, path string, opts ...options.ReadTableOption, -) (_ result.StreamResult, err error) { +) (result.StreamResult, error) { var ( onIntermediate = trace.TableOnSessionQueryStreamRead(s.config.Trace(), &ctx, stack.FunctionID(""), @@ -995,6 +1012,7 @@ func (s *session) StreamReadTable( } stream Ydb_Table_V1.TableService_StreamReadTableClient a = allocator.New() + err error ) defer func() { a.Free() @@ -1020,10 +1038,11 @@ func (s *session) StreamReadTable( return scanner.NewStream(ctx, func(ctx context.Context) ( - set *Ydb.ResultSet, - stats *Ydb_TableStats.QueryStats, - err error, + *Ydb.ResultSet, + *Ydb_TableStats.QueryStats, + error, ) { + var err error defer func() { onIntermediate(xerrors.HideEOF(err)) }() @@ -1056,7 +1075,7 @@ func (s *session) ReadRows( path string, keys types.Value, opts ...options.ReadRowsOption, -) (_ result.Result, err error) { +) (result.Result, error) { var ( a = allocator.New() request = Ydb_Table.ReadRowsRequest{ @@ -1076,7 +1095,7 @@ func (s *session) ReadRows( } } - response, err = s.tableService.ReadRows(ctx, &request) + response, err := s.tableService.ReadRows(ctx, &request) if err != nil { return nil, xerrors.WithStackTrace(err) } @@ -1106,7 +1125,7 @@ func (s *session) StreamExecuteScanQuery( query string, params *table.QueryParameters, opts ...options.ExecuteScanQueryOption, -) (_ result.StreamResult, err error) { +) (result.StreamResult, error) { var ( a = allocator.New() q = queryFromText(query) @@ -1122,6 +1141,7 @@ func (s *session) StreamExecuteScanQuery( } stream Ydb_Table_V1.TableService_StreamExecuteScanQueryClient callOptions []grpc.CallOption + err error ) defer func() { a.Free() @@ -1147,10 +1167,11 @@ func (s *session) StreamExecuteScanQuery( return scanner.NewStream(ctx, func(ctx context.Context) ( - set *Ydb.ResultSet, - stats *Ydb_TableStats.QueryStats, - err error, + *Ydb.ResultSet, + *Ydb_TableStats.QueryStats, + error, ) { + var err error defer func() { onIntermediate(xerrors.HideEOF(err)) }() @@ -1182,7 +1203,7 @@ func (s *session) StreamExecuteScanQuery( // BulkUpsert uploads given list of ydb struct values to the table. func (s *session) BulkUpsert(ctx context.Context, table string, rows types.Value, opts ...options.BulkUpsertOption, -) (err error) { +) error { var ( a = allocator.New() callOptions []grpc.CallOption @@ -1191,6 +1212,7 @@ func (s *session) BulkUpsert(ctx context.Context, table string, rows types.Value stack.FunctionID(""), s, ) + err error ) defer func() { defer a.Free() @@ -1226,7 +1248,7 @@ func (s *session) BulkUpsert(ctx context.Context, table string, rows types.Value func (s *session) BeginTransaction( ctx context.Context, txSettings *table.TransactionSettings, -) (x table.Transaction, err error) { +) (table.Transaction, error) { var ( result Ydb_Table.BeginTransactionResult response *Ydb_Table.BeginTransactionResponse @@ -1235,6 +1257,8 @@ func (s *session) BeginTransaction( stack.FunctionID(""), s, ) + x table.Transaction + err error ) defer func() { onDone(x, err) diff --git a/internal/table/session_test.go b/internal/table/session_test.go index cd581a9fd..ced391f1a 100644 --- a/internal/table/session_test.go +++ b/internal/table/session_test.go @@ -356,10 +356,10 @@ func TestSessionOperationModeOnExecuteDataQuery(t *testing.T) { }, }, nil }, - testutil.TableExplainDataQuery: func(request interface{}) (result proto.Message, err error) { + testutil.TableExplainDataQuery: func(request interface{}) (proto.Message, error) { return &Ydb_Table.ExplainQueryResult{}, nil }, - testutil.TablePrepareDataQuery: func(request interface{}) (result proto.Message, err error) { + testutil.TablePrepareDataQuery: func(request interface{}) (proto.Message, error) { return &Ydb_Table.PrepareQueryResult{}, nil }, testutil.TableCreateSession: func(interface{}) (proto.Message, error) { @@ -367,16 +367,16 @@ func TestSessionOperationModeOnExecuteDataQuery(t *testing.T) { SessionId: testutil.SessionID(), }, nil }, - testutil.TableDeleteSession: func(request interface{}) (result proto.Message, err error) { + testutil.TableDeleteSession: func(request interface{}) (proto.Message, error) { return &Ydb_Table.DeleteSessionResponse{}, nil }, - testutil.TableCommitTransaction: func(request interface{}) (result proto.Message, err error) { + testutil.TableCommitTransaction: func(request interface{}) (proto.Message, error) { return &Ydb_Table.CommitTransactionResult{}, nil }, - testutil.TableRollbackTransaction: func(request interface{}) (result proto.Message, err error) { + testutil.TableRollbackTransaction: func(request interface{}) (proto.Message, error) { return &Ydb_Table.RollbackTransactionResponse{}, nil }, - testutil.TableKeepAlive: func(request interface{}) (result proto.Message, err error) { + testutil.TableKeepAlive: func(request interface{}) (proto.Message, error) { return &Ydb_Table.KeepAliveResult{}, nil }, }, @@ -577,7 +577,7 @@ func TestDescribeTableRegression(t *testing.T) { var act options.Description - err = client.Do(ctx, func(ctx context.Context, s table.Session) (err error) { + err = client.Do(ctx, func(ctx context.Context, s table.Session) error { act, err = s.DescribeTable(ctx, "episodes") return err diff --git a/internal/table/statement.go b/internal/table/statement.go index d0cf27c54..184130514 100644 --- a/internal/table/statement.go +++ b/internal/table/statement.go @@ -29,7 +29,7 @@ func (s *statement) Execute( params *table.QueryParameters, opts ...options.ExecuteDataQueryOption, ) ( - txr table.Transaction, r result.Result, err error, + table.Transaction, result.Result, error, ) { var ( a = allocator.New() @@ -38,6 +38,9 @@ func (s *statement) Execute( IgnoreTruncated: s.session.config.IgnoreTruncated(), } callOptions []grpc.CallOption + txr table.Transaction + r result.Result + err error ) defer a.Free() @@ -78,7 +81,7 @@ func (s *statement) execute( request *options.ExecuteDataQueryDesc, txControl *Ydb_Table.TransactionControl, callOptions ...grpc.CallOption, ) ( - txr table.Transaction, r result.Result, err error, + table.Transaction, result.Result, error, ) { res, err := s.session.executeDataQuery(ctx, a, request.ExecuteDataQueryRequest, callOptions...) if err != nil { diff --git a/internal/table/transaction.go b/internal/table/transaction.go index 180784c3a..f74d2a3b6 100644 --- a/internal/table/transaction.go +++ b/internal/table/transaction.go @@ -59,11 +59,15 @@ func (tx *transaction) Execute( ctx context.Context, query string, params *table.QueryParameters, opts ...options.ExecuteDataQueryOption, -) (r result.Result, err error) { - onDone := trace.TableOnSessionTransactionExecute( - tx.s.config.Trace(), &ctx, - stack.FunctionID(""), - tx.s, tx, queryFromText(query), params, +) (result.Result, error) { + var ( + r result.Result + err error + onDone = trace.TableOnSessionTransactionExecute( + tx.s.config.Trace(), &ctx, + stack.FunctionID(""), + tx.s, tx, queryFromText(query), params, + ) ) defer func() { onDone(r, err) @@ -93,17 +97,21 @@ func (tx *transaction) ExecuteStatement( ctx context.Context, stmt table.Statement, params *table.QueryParameters, opts ...options.ExecuteDataQueryOption, -) (r result.Result, err error) { +) (result.Result, error) { if params == nil { params = table.NewQueryParameters() } a := allocator.New() defer a.Free() - onDone := trace.TableOnSessionTransactionExecuteStatement( - tx.s.config.Trace(), &ctx, - stack.FunctionID(""), - tx.s, tx, stmt.(*statement).query, params, + var ( + r result.Result + err error + onDone = trace.TableOnSessionTransactionExecuteStatement( + tx.s.config.Trace(), &ctx, + stack.FunctionID(""), + tx.s, tx, stmt.(*statement).query, params, + ) ) defer func() { onDone(r, err) @@ -132,11 +140,14 @@ func (tx *transaction) ExecuteStatement( func (tx *transaction) CommitTx( ctx context.Context, opts ...options.CommitTransactionOption, -) (r result.Result, err error) { - onDone := trace.TableOnSessionTransactionCommit( - tx.s.config.Trace(), &ctx, - stack.FunctionID(""), - tx.s, tx, +) (result.Result, error) { + var ( + err error + onDone = trace.TableOnSessionTransactionCommit( + tx.s.config.Trace(), &ctx, + stack.FunctionID(""), + tx.s, tx, + ) ) defer func() { onDone(err) @@ -190,11 +201,14 @@ func (tx *transaction) CommitTx( } // Rollback performs a rollback of the specified active transaction. -func (tx *transaction) Rollback(ctx context.Context) (err error) { - onDone := trace.TableOnSessionTransactionRollback( - tx.s.config.Trace(), &ctx, - stack.FunctionID(""), - tx.s, tx, +func (tx *transaction) Rollback(ctx context.Context) error { + var ( + err error + onDone = trace.TableOnSessionTransactionRollback( + tx.s.config.Trace(), &ctx, + stack.FunctionID(""), + tx.s, tx, + ) ) defer func() { onDone(err) diff --git a/internal/topic/retriable_error.go b/internal/topic/retriable_error.go index 23ef3c49c..94e52d0b7 100644 --- a/internal/topic/retriable_error.go +++ b/internal/topic/retriable_error.go @@ -54,8 +54,8 @@ func CheckResetReconnectionCounters(lastTry, now time.Time, connectionTimeout ti } func CheckRetryMode(err error, settings RetrySettings, retriesDuration time.Duration) ( - _ backoff.Backoff, - isRetriable bool, + backoff.Backoff, + bool, ) { // nil is not error and doesn't need retry it. if err == nil { @@ -71,9 +71,11 @@ func CheckRetryMode(err error, settings RetrySettings, retriesDuration time.Dura return nil, false } - mode := retry.Check(err) - - decision := PublicRetryDecisionDefault + var ( + isRetriable bool + mode = retry.Check(err) + decision = PublicRetryDecisionDefault + ) if settings.CheckError != nil { decision = settings.CheckError(NewCheckRetryArgs(err)) } diff --git a/internal/topic/topicclientinternal/client.go b/internal/topic/topicclientinternal/client.go index a023b1471..c5681fb02 100644 --- a/internal/topic/topicclientinternal/client.go +++ b/internal/topic/topicclientinternal/client.go @@ -130,11 +130,15 @@ func (c *Client) Describe( ctx context.Context, path string, opts ...topicoptions.DescribeOption, -) (res topictypes.TopicDescription, _ error) { - req := rawtopic.DescribeTopicRequest{ - OperationParams: c.defaultOperationParams, - Path: path, - } +) (topictypes.TopicDescription, error) { + var ( + describeErr error + res topictypes.TopicDescription + req = rawtopic.DescribeTopicRequest{ + OperationParams: c.defaultOperationParams, + Path: path, + } + ) for _, o := range opts { if o != nil { @@ -144,7 +148,7 @@ func (c *Client) Describe( var rawRes rawtopic.DescribeTopicResult - call := func(ctx context.Context) (describeErr error) { + call := func(ctx context.Context) error { rawRes, describeErr = c.rawClient.DescribeTopic(ctx, req) return describeErr diff --git a/internal/topic/topicreaderinternal/batch.go b/internal/topic/topicreaderinternal/batch.go index e8e00ad01..b0722ac80 100644 --- a/internal/topic/topicreaderinternal/batch.go +++ b/internal/topic/topicreaderinternal/batch.go @@ -147,7 +147,7 @@ func (m *PublicBatch) append(b *PublicBatch) (*PublicBatch, error) { return res, nil } -func (m *PublicBatch) cutMessages(count int) (head, rest *PublicBatch) { +func (m *PublicBatch) cutMessages(count int) (*PublicBatch, *PublicBatch) { switch { case count == 0: return nil, m @@ -156,8 +156,8 @@ func (m *PublicBatch) cutMessages(count int) (head, rest *PublicBatch) { default: // slice[0:count:count] - limit slice capacity and prevent overwrite rest by append messages to head // explicit 0 need for prevent typos, when type slice[count:count] instead of slice[:count:count] - head, _ = newBatch(m.commitRange.partitionSession, m.Messages[0:count:count]) - rest, _ = newBatch(m.commitRange.partitionSession, m.Messages[count:]) + head, _ := newBatch(m.commitRange.partitionSession, m.Messages[0:count:count]) + rest, _ := newBatch(m.commitRange.partitionSession, m.Messages[count:]) return head, rest } diff --git a/internal/topic/topicreaderinternal/batcher.go b/internal/topic/topicreaderinternal/batcher.go index deebbb209..6b5b372cd 100644 --- a/internal/topic/topicreaderinternal/batcher.go +++ b/internal/topic/topicreaderinternal/batcher.go @@ -103,9 +103,9 @@ type batcherGetOptions struct { } func (o batcherGetOptions) cutBatchItemsHead(items batcherMessageOrderItems) ( - head batcherMessageOrderItem, - rest batcherMessageOrderItems, - ok bool, + batcherMessageOrderItem, + batcherMessageOrderItems, + bool, ) { notFound := func() (batcherMessageOrderItem, batcherMessageOrderItems, bool) { return batcherMessageOrderItem{}, batcherMessageOrderItems{}, false @@ -125,8 +125,8 @@ func (o batcherGetOptions) cutBatchItemsHead(items batcherMessageOrderItems) ( return notFound() } - head = newBatcherItemBatch(batchHead) - rest = items.ReplaceHeadItem(newBatcherItemBatch(batchRest)) + head := newBatcherItemBatch(batchHead) + rest := items.ReplaceHeadItem(newBatcherItemBatch(batchRest)) return head, rest, true } @@ -134,7 +134,7 @@ func (o batcherGetOptions) cutBatchItemsHead(items batcherMessageOrderItems) ( return items[0], items[1:], true } -func (o batcherGetOptions) splitBatch(batch *PublicBatch) (head, rest *PublicBatch, ok bool) { +func (o batcherGetOptions) splitBatch(batch *PublicBatch) (*PublicBatch, *PublicBatch, bool) { notFound := func() (*PublicBatch, *PublicBatch, bool) { return nil, nil, false } @@ -147,12 +147,12 @@ func (o batcherGetOptions) splitBatch(batch *PublicBatch) (head, rest *PublicBat return batch, nil, true } - head, rest = batch.cutMessages(o.MaxCount) + head, rest := batch.cutMessages(o.MaxCount) return head, rest, true } -func (b *batcher) Pop(ctx context.Context, opts batcherGetOptions) (_ batcherMessageOrderItem, err error) { +func (b *batcher) Pop(ctx context.Context, opts batcherGetOptions) (batcherMessageOrderItem, error) { counter := atomic.AddInt64(&b.popInFlight, 1) defer atomic.AddInt64(&b.popInFlight, -1) @@ -160,7 +160,7 @@ func (b *batcher) Pop(ctx context.Context, opts batcherGetOptions) (_ batcherMes return batcherMessageOrderItem{}, xerrors.WithStackTrace(errBatcherPopConcurency) } - if err = ctx.Err(); err != nil { + if err := ctx.Err(); err != nil { return batcherMessageOrderItem{}, err } diff --git a/internal/topic/topicreaderinternal/committer.go b/internal/topic/topicreaderinternal/committer.go index c3f22849f..cb44cd509 100644 --- a/internal/topic/topicreaderinternal/committer.go +++ b/internal/topic/topicreaderinternal/committer.go @@ -255,7 +255,7 @@ type commitWaiter struct { Committed empty.Chan } -func (w *commitWaiter) checkCondition(session *partitionSession, offset rawtopicreader.Offset) (finished bool) { +func (w *commitWaiter) checkCondition(session *partitionSession, offset rawtopicreader.Offset) bool { return session == w.Session && offset >= w.EndOffset } diff --git a/internal/topic/topicreaderinternal/message.go b/internal/topic/topicreaderinternal/message.go index fd37be761..d4c8d7a51 100644 --- a/internal/topic/topicreaderinternal/message.go +++ b/internal/topic/topicreaderinternal/message.go @@ -70,7 +70,7 @@ func (m *PublicMessage) UnmarshalTo(dst PublicMessageContentUnmarshaler) error { // Read implements io.Reader // Read uncompressed message content // return topicreader.UnexpectedCodec if message compressed with unknown codec -func (m *PublicMessage) Read(p []byte) (n int, err error) { +func (m *PublicMessage) Read(p []byte) (int, error) { m.dataConsumed = true return m.data.Read(p) @@ -99,7 +99,7 @@ type errorReader struct { err error } -func (u errorReader) Read(p []byte) (n int, err error) { +func (u errorReader) Read(p []byte) (int, error) { return 0, u.err } diff --git a/internal/topic/topicreaderinternal/one_time_reader.go b/internal/topic/topicreaderinternal/one_time_reader.go index 4a54d6f7a..c4332abf7 100644 --- a/internal/topic/topicreaderinternal/one_time_reader.go +++ b/internal/topic/topicreaderinternal/one_time_reader.go @@ -15,13 +15,12 @@ func newOneTimeReader(reader io.Reader) oneTimeReader { } } -func (s *oneTimeReader) Read(p []byte) (n int, err error) { +func (s *oneTimeReader) Read(p []byte) (int, error) { if s.err != nil { return 0, s.err } - n, err = s.reader.Read(p) - + n, err := s.reader.Read(p) if err != nil { s.err = err s.reader = nil diff --git a/internal/topic/topicreaderinternal/reader.go b/internal/topic/topicreaderinternal/reader.go index 030a5ca4b..79a7f07b0 100644 --- a/internal/topic/topicreaderinternal/reader.go +++ b/internal/topic/topicreaderinternal/reader.go @@ -140,8 +140,12 @@ func (r *Reader) ReadMessage(ctx context.Context) (*PublicMessage, error) { // ReadMessageBatch read batch of messages. // Batch is collection of messages, which can be atomically committed -func (r *Reader) ReadMessageBatch(ctx context.Context, opts ...PublicReadBatchOption) (batch *PublicBatch, err error) { - readOptions := r.defaultBatchConfig.clone() +func (r *Reader) ReadMessageBatch(ctx context.Context, opts ...PublicReadBatchOption) (*PublicBatch, error) { + var ( + readOptions = r.defaultBatchConfig.clone() + batch *PublicBatch + err error + ) for _, opt := range opts { if opt != nil { @@ -167,7 +171,7 @@ func (r *Reader) ReadMessageBatch(ctx context.Context, opts ...PublicReadBatchOp } } -func (r *Reader) Commit(ctx context.Context, offsets PublicCommitRangeGetter) (err error) { +func (r *Reader) Commit(ctx context.Context, offsets PublicCommitRangeGetter) error { cr := offsets.getCommitRange().priv if cr.partitionSession.readerID != r.readerID { return xerrors.WithStackTrace(xerrors.Wrap(fmt.Errorf( @@ -248,7 +252,8 @@ func convertNewParamsToStreamConfig( consumer string, readSelectors []PublicReadSelector, opts ...PublicReaderOption, -) (cfg ReaderConfig) { +) ReaderConfig { + var cfg ReaderConfig cfg.topicStreamReaderConfig = newTopicStreamReaderConfig() cfg.Consumer = consumer diff --git a/internal/topic/topicreaderinternal/stream_reader_impl.go b/internal/topic/topicreaderinternal/stream_reader_impl.go index a77bf4fb3..ca125abe8 100644 --- a/internal/topic/topicreaderinternal/stream_reader_impl.go +++ b/internal/topic/topicreaderinternal/stream_reader_impl.go @@ -111,7 +111,8 @@ func newTopicStreamReader( readerID int64, stream RawTopicReaderStream, cfg topicStreamReaderConfig, //nolint:gocritic -) (_ *topicStreamReaderImpl, err error) { +) (*topicStreamReaderImpl, error) { + var err error defer func() { if err != nil { _ = stream.CloseSend() @@ -175,7 +176,11 @@ func (r *topicStreamReaderImpl) WaitInit(_ context.Context) error { func (r *topicStreamReaderImpl) ReadMessageBatch( ctx context.Context, opts ReadMessageBatchOptions, -) (batch *PublicBatch, err error) { +) (*PublicBatch, error) { + var ( + batch *PublicBatch + err error + ) onDone := trace.TopicOnReaderReadMessages( r.cfg.Trace, ctx, @@ -288,7 +293,7 @@ func (r *topicStreamReaderImpl) consumeRawMessageFromBuffer(ctx context.Context) func (r *topicStreamReaderImpl) onStopPartitionSessionRequestFromBuffer( msg *rawtopicreader.StopPartitionSessionRequest, -) (err error) { +) error { session, err := r.sessionController.Get(msg.PartitionSessionID) if err != nil { return err @@ -436,7 +441,8 @@ func (r *topicStreamReaderImpl) setStarted() error { return nil } -func (r *topicStreamReaderImpl) initSession() (err error) { +func (r *topicStreamReaderImpl) initSession() error { + var err error initMessage := r.cfg.initMessage() onDone := trace.TopicOnReaderInit(r.cfg.Trace, r.readConnectionID, initMessage) @@ -614,7 +620,8 @@ func (r *topicStreamReaderImpl) updateTokenLoop(ctx context.Context) { } } -func (r *topicStreamReaderImpl) onReadResponse(msg *rawtopicreader.ReadResponse) (err error) { +func (r *topicStreamReaderImpl) onReadResponse(msg *rawtopicreader.ReadResponse) error { + var err error resCapacity := r.addRestBufferBytes(-msg.BytesSize) onDone := trace.TopicOnReaderReceiveDataResponse(r.cfg.Trace, r.readConnectionID, resCapacity, msg) defer func() { @@ -662,7 +669,8 @@ func (r *topicStreamReaderImpl) onReadResponse(msg *rawtopicreader.ReadResponse) return nil } -func (r *topicStreamReaderImpl) CloseWithError(ctx context.Context, reason error) (closeErr error) { +func (r *topicStreamReaderImpl) CloseWithError(ctx context.Context, reason error) error { + var closeErr error onDone := trace.TopicOnReaderClose(r.cfg.Trace, r.readConnectionID, reason) defer onDone(closeErr) @@ -761,7 +769,7 @@ func (r *topicStreamReaderImpl) onStartPartitionSessionRequest(m *rawtopicreader func (r *topicStreamReaderImpl) onStartPartitionSessionRequestFromBuffer( m *rawtopicreader.StartPartitionSessionRequest, -) (err error) { +) error { session, err := r.sessionController.Get(m.PartitionSession.PartitionSessionID) if err != nil { return err diff --git a/internal/topic/topicreaderinternal/stream_reconnector.go b/internal/topic/topicreaderinternal/stream_reconnector.go index fa3ba6594..a6a21a988 100644 --- a/internal/topic/topicreaderinternal/stream_reconnector.go +++ b/internal/topic/topicreaderinternal/stream_reconnector.go @@ -243,7 +243,8 @@ func (r *readerReconnector) reconnectionLoop(ctx context.Context) { } } -func (r *readerReconnector) reconnect(ctx context.Context, reason error, oldReader batchedStreamReader) (err error) { +func (r *readerReconnector) reconnect(ctx context.Context, reason error, oldReader batchedStreamReader) error { + var err error onDone := trace.TopicOnReaderReconnect(r.tracer, reason) defer func() { onDone(err) @@ -308,16 +309,16 @@ func (r *readerReconnector) isRetriableError(err error) bool { } func (r *readerReconnector) checkErrRetryMode(err error, retriesDuration time.Duration) ( - backoffType backoff.Backoff, - isRetriableErr bool, + backoff.Backoff, + bool, ) { return topic.CheckRetryMode(err, r.retrySettings, retriesDuration) } -func (r *readerReconnector) connectWithTimeout() (_ batchedStreamReader, err error) { +func (r *readerReconnector) connectWithTimeout() (batchedStreamReader, error) { bgContext := r.background.Context() - if err = bgContext.Err(); err != nil { + if err := bgContext.Err(); err != nil { return nil, err } diff --git a/internal/topic/topicwriterinternal/queue.go b/internal/topic/topicwriterinternal/queue.go index 8e15833fc..83ab9f08c 100644 --- a/internal/topic/topicwriterinternal/queue.go +++ b/internal/topic/topicwriterinternal/queue.go @@ -62,16 +62,17 @@ func (q *messageQueue) AddMessages(messages []messageWithDataContent) error { } func (q *messageQueue) AddMessagesWithWaiter(messages []messageWithDataContent) ( - waiter MessageQueueAckWaiter, - err error, + MessageQueueAckWaiter, + error, ) { return q.addMessages(messages, true) } func (q *messageQueue) addMessages(messages []messageWithDataContent, needWaiter bool) ( - waiter MessageQueueAckWaiter, - err error, + MessageQueueAckWaiter, + error, ) { + var waiter MessageQueueAckWaiter q.m.Lock() defer q.m.Unlock() @@ -122,9 +123,9 @@ func (q *messageQueue) checkNewMessagesBeforeAddNeedLock(messages []messageWithD func (q *messageQueue) addMessageNeedLock( mess messageWithDataContent, //nolint:gocritic -) (messageIndex int) { +) int { q.lastWrittenIndex++ - messageIndex = q.lastWrittenIndex + messageIndex := q.lastWrittenIndex if messageIndex == minInt { q.ensureNoSmallIntIndexes() diff --git a/internal/topic/topicwriterinternal/writer.go b/internal/topic/topicwriterinternal/writer.go index d3a74ffd0..8604d2e82 100644 --- a/internal/topic/topicwriterinternal/writer.go +++ b/internal/topic/topicwriterinternal/writer.go @@ -48,7 +48,7 @@ func (w *Writer) Write(ctx context.Context, messages ...PublicMessage) error { return w.streamWriter.Write(ctx, messages) } -func (w *Writer) WaitInit(ctx context.Context) (info InitialInfo, err error) { +func (w *Writer) WaitInit(ctx context.Context) (InitialInfo, error) { return w.streamWriter.WaitInit(ctx) } diff --git a/internal/topic/topicwriterinternal/writer_reconnector.go b/internal/topic/topicwriterinternal/writer_reconnector.go index f4dfc8e71..b29d320e8 100644 --- a/internal/topic/topicwriterinternal/writer_reconnector.go +++ b/internal/topic/topicwriterinternal/writer_reconnector.go @@ -332,8 +332,11 @@ func (w *WriterReconnector) Close(ctx context.Context) error { return w.close(ctx, xerrors.WithStackTrace(errStopWriterReconnector)) } -func (w *WriterReconnector) close(ctx context.Context, reason error) (resErr error) { - onDone := trace.TopicOnWriterClose(w.cfg.tracer, w.writerInstanceID, reason) +func (w *WriterReconnector) close(ctx context.Context, reason error) error { + var ( + resErr error + onDone = trace.TopicOnWriterClose(w.cfg.tracer, w.writerInstanceID, reason) + ) defer func() { onDone(resErr) }() @@ -410,15 +413,18 @@ func (w *WriterReconnector) connectionLoop(ctx context.Context) { } func (w *WriterReconnector) startWriteStream(ctx, streamCtx context.Context, attempt int) ( - writer *SingleStreamWriter, - err error, + *SingleStreamWriter, + error, ) { - traceOnDone := trace.TopicOnWriterReconnect( - w.cfg.tracer, - w.writerInstanceID, - w.cfg.topic, - w.cfg.producerID, - attempt, + var ( + err error + traceOnDone = trace.TopicOnWriterReconnect( + w.cfg.tracer, + w.writerInstanceID, + w.cfg.topic, + w.cfg.producerID, + attempt, + ) ) defer func() { traceOnDone(err) @@ -516,7 +522,7 @@ func (w *WriterReconnector) onWriterChange(writerStream *SingleStreamWriter) { } } -func (w *WriterReconnector) WaitInit(ctx context.Context) (info InitialInfo, err error) { +func (w *WriterReconnector) WaitInit(ctx context.Context) (InitialInfo, error) { if ctx.Err() != nil { return InitialInfo{}, ctx.Err() } @@ -612,11 +618,12 @@ func allMessagesHasSameBufCodec(messages []messageWithDataContent) bool { return true } -func splitMessagesByBufCodec(messages []messageWithDataContent) (res [][]messageWithDataContent) { +func splitMessagesByBufCodec(messages []messageWithDataContent) [][]messageWithDataContent { if len(messages) == 0 { return nil } + var res [][]messageWithDataContent currentGroupStart := 0 currentCodec := messages[0].bufCodec for i := range messages { @@ -632,9 +639,13 @@ func splitMessagesByBufCodec(messages []messageWithDataContent) (res [][]message } func createWriteRequest(messages []messageWithDataContent, targetCodec rawtopiccommon.Codec) ( - res rawtopicwriter.WriteRequest, - err error, + rawtopicwriter.WriteRequest, + error, ) { + var ( + res rawtopicwriter.WriteRequest + err error + ) res.Codec = targetCodec res.Messages = make([]rawtopicwriter.MessageData, len(messages)) for i := range messages { @@ -650,7 +661,12 @@ func createWriteRequest(messages []messageWithDataContent, targetCodec rawtopicc func createRawMessageData( codec rawtopiccommon.Codec, mess *messageWithDataContent, -) (res rawtopicwriter.MessageData, err error) { +) (rawtopicwriter.MessageData, error) { + var ( + res rawtopicwriter.MessageData + err error + ) + res.CreatedAt = mess.CreatedAt res.SeqNo = mess.SeqNo diff --git a/internal/topic/topicwriterinternal/writer_single_stream.go b/internal/topic/topicwriterinternal/writer_single_stream.go index ba140876b..f71d2027d 100644 --- a/internal/topic/topicwriterinternal/writer_single_stream.go +++ b/internal/topic/topicwriterinternal/writer_single_stream.go @@ -121,8 +121,11 @@ func (w *SingleStreamWriter) start() { w.background.Start("topic writer receive messages", w.receiveMessagesLoop) } -func (w *SingleStreamWriter) initStream() (err error) { - traceOnDone := trace.TopicOnWriterInitStream(w.cfg.tracer, w.cfg.reconnectorInstanceID, w.cfg.topic, w.cfg.producerID) +func (w *SingleStreamWriter) initStream() error { + var ( + err error + traceOnDone = trace.TopicOnWriterInitStream(w.cfg.tracer, w.cfg.reconnectorInstanceID, w.cfg.topic, w.cfg.producerID) + ) defer traceOnDone(w.SessionID, err) req := w.createInitRequest() @@ -268,7 +271,7 @@ func (w *SingleStreamWriter) updateTokenLoop(ctx context.Context) { } } -func (w *SingleStreamWriter) sendUpdateToken(ctx context.Context) (err error) { +func (w *SingleStreamWriter) sendUpdateToken(ctx context.Context) error { token, err := w.cfg.cred.Token(ctx) if err != nil { return err diff --git a/internal/value/time.go b/internal/value/time.go index 37f7aa374..c3556eca2 100644 --- a/internal/value/time.go +++ b/internal/value/time.go @@ -58,8 +58,11 @@ func TimestampToTime(n uint64) time.Time { return time.Unix(int64(sec), int64(nsec)) } -func TzDateToTime(s string) (t time.Time, err error) { - ss := strings.Split(s, ",") +func TzDateToTime(s string) (time.Time, error) { + var ( + t time.Time + ss = strings.Split(s, ",") + ) if len(ss) != 2 { return t, xerrors.WithStackTrace(fmt.Errorf("not found timezone location in '%s'", s)) } @@ -75,8 +78,11 @@ func TzDateToTime(s string) (t time.Time, err error) { return t, nil } -func TzDatetimeToTime(s string) (t time.Time, err error) { - ss := strings.Split(s, ",") +func TzDatetimeToTime(s string) (time.Time, error) { + var ( + t time.Time + ss = strings.Split(s, ",") + ) if len(ss) != 2 { return t, xerrors.WithStackTrace(fmt.Errorf("not found timezone location in '%s'", s)) } @@ -92,8 +98,11 @@ func TzDatetimeToTime(s string) (t time.Time, err error) { return t, nil } -func TzTimestampToTime(s string) (t time.Time, err error) { - ss := strings.Split(s, ",") +func TzTimestampToTime(s string) (time.Time, error) { + var ( + t time.Time + ss = strings.Split(s, ",") + ) if len(ss) != 2 { return t, xerrors.WithStackTrace(fmt.Errorf("not found timezone location in '%s'", s)) } diff --git a/internal/value/type.go b/internal/value/type.go index dd2cc3b07..351e6cd42 100644 --- a/internal/value/type.go +++ b/internal/value/type.go @@ -243,7 +243,7 @@ func (v *dictType) toYDB(a *allocator.Allocator) *Ydb.Type { return t } -func Dict(key, value Type) (v *dictType) { +func Dict(key, value Type) *dictType { return &dictType{ keyType: key, valueType: value, @@ -623,7 +623,7 @@ func (v *StructType) toYDB(a *allocator.Allocator) *Ydb.Type { return t } -func Struct(fields ...StructField) (v *StructType) { +func Struct(fields ...StructField) *StructType { return &StructType{ fields: fields, } @@ -701,7 +701,7 @@ func (v *TupleType) toYDB(a *allocator.Allocator) *Ydb.Type { return t } -func Tuple(items ...Type) (v *TupleType) { +func Tuple(items ...Type) *TupleType { return &TupleType{ items: items, } diff --git a/internal/value/value.go b/internal/value/value.go index 4c8e3cbdd..056758a02 100644 --- a/internal/value/value.go +++ b/internal/value/value.go @@ -36,7 +36,8 @@ func ToYDB(v Value, a *allocator.Allocator) *Ydb.TypedValue { } // BigEndianUint128 builds a big-endian uint128 value. -func BigEndianUint128(hi, lo uint64) (v [16]byte) { +func BigEndianUint128(hi, lo uint64) [16]byte { + var v [16]byte binary.BigEndian.PutUint64(v[0:8], hi) binary.BigEndian.PutUint64(v[8:16], lo) @@ -52,7 +53,7 @@ func FromYDB(t *Ydb.Type, v *Ydb.Value) Value { return vv } -func nullValueFromYDB(x *Ydb.Value, t Type) (_ Value, ok bool) { +func nullValueFromYDB(x *Ydb.Value, t Type) (Value, bool) { for { switch xx := x.Value.(type) { case *Ydb.Value_NestedValue: @@ -1948,7 +1949,7 @@ type variantValue struct { idx uint32 } -func (v *variantValue) Variant() (name string, index uint32) { +func (v *variantValue) Variant() (name string, index uint32) { //nolint:nonamedreturns //gocritic more important switch t := v.innerType.(type) { case *variantStructType: return t.fields[v.idx].Name, v.idx diff --git a/internal/version/parse.go b/internal/version/parse.go index e901ed031..3b5db2d49 100644 --- a/internal/version/parse.go +++ b/internal/version/parse.go @@ -68,8 +68,12 @@ func Gte(lhs, rhs string) bool { return true } -func parse(s string) (v version, err error) { - ss := strings.SplitN(s, "-", 2) +func parse(s string) (version, error) { + var ( + v version + err error + ss = strings.SplitN(s, "-", 2) + ) if len(ss) == 2 { v.Suffix = ss[1] } diff --git a/internal/xcontext/context_with_cancel.go b/internal/xcontext/context_with_cancel.go index 1deeac4bb..407ddc595 100644 --- a/internal/xcontext/context_with_cancel.go +++ b/internal/xcontext/context_with_cancel.go @@ -24,7 +24,7 @@ type cancelCtx struct { err error } -func (ctx *cancelCtx) Deadline() (deadline time.Time, ok bool) { +func (ctx *cancelCtx) Deadline() (time.Time, bool) { return ctx.ctx.Deadline() } diff --git a/internal/xcontext/context_with_timeout.go b/internal/xcontext/context_with_timeout.go index 5342798fe..f52950a3c 100644 --- a/internal/xcontext/context_with_timeout.go +++ b/internal/xcontext/context_with_timeout.go @@ -28,7 +28,7 @@ type timeoutCtx struct { err error } -func (ctx *timeoutCtx) Deadline() (deadline time.Time, ok bool) { +func (ctx *timeoutCtx) Deadline() (time.Time, bool) { return ctx.ctx.Deadline() } diff --git a/internal/xcontext/without_deadline.go b/internal/xcontext/without_deadline.go index c0d92045c..57bb87f65 100644 --- a/internal/xcontext/without_deadline.go +++ b/internal/xcontext/without_deadline.go @@ -7,7 +7,7 @@ import ( type valueOnlyContext struct{ context.Context } -func (valueOnlyContext) Deadline() (deadline time.Time, ok bool) { return } +func (valueOnlyContext) Deadline() (time.Time, bool) { return time.Time{}, false } func (valueOnlyContext) Done() <-chan struct{} { return nil } diff --git a/internal/xerrors/check.go b/internal/xerrors/check.go index 47b2b1603..154184b38 100644 --- a/internal/xerrors/check.go +++ b/internal/xerrors/check.go @@ -5,7 +5,7 @@ import ( ) // Check returns retry mode for err. -func Check(err error) ( +func Check(err error) ( //nolint:nonamedreturns //gocritic more important code int64, errType Type, backoffType backoff.Type, diff --git a/internal/xerrors/issues.go b/internal/xerrors/issues.go index f981207b4..f01186dd1 100644 --- a/internal/xerrors/issues.go +++ b/internal/xerrors/issues.go @@ -128,8 +128,11 @@ func (it IssueIterator) Len() int { return len(it) } -func (it IssueIterator) Get(i int) (issue Issue, nested IssueIterator) { - x := it[i] +func (it IssueIterator) Get(i int) (Issue, IssueIterator) { + var ( + x = it[i] + nested IssueIterator + ) if xs := x.Issues; len(xs) > 0 { nested = IssueIterator(xs) } diff --git a/internal/xerrors/operation.go b/internal/xerrors/operation.go index f2383077a..7d8d25a13 100644 --- a/internal/xerrors/operation.go +++ b/internal/xerrors/operation.go @@ -151,7 +151,8 @@ func IsOperationError(err error, codes ...Ydb.StatusIds_StatusCode) bool { const issueCodeTransactionLocksInvalidated = 2001 -func IsOperationErrorTransactionLocksInvalidated(err error) (isTLI bool) { +func IsOperationErrorTransactionLocksInvalidated(err error) bool { + var isTLI bool if IsOperationError(err, Ydb.StatusIds_ABORTED) { IterateByIssues(err, func(_ string, code Ydb.StatusIds_StatusCode, severity uint32) { isTLI = isTLI || (code == issueCodeTransactionLocksInvalidated) diff --git a/internal/xresolver/xresolver.go b/internal/xresolver/xresolver.go index 5d78a7a55..e668452f0 100644 --- a/internal/xresolver/xresolver.go +++ b/internal/xresolver/xresolver.go @@ -31,15 +31,17 @@ func (c *clientConn) Endpoint() string { return strings.TrimPrefix(endpoint, "/") } -func (c *clientConn) UpdateState(state resolver.State) (err error) { +func (c *clientConn) UpdateState(state resolver.State) error { + var err error onDone := trace.DriverOnResolve(c.trace, stack.FunctionID(""), - c.Endpoint(), func() (addrs []string) { + c.Endpoint(), func() []string { + var addrs []string for i := range state.Addresses { addrs = append(addrs, state.Addresses[i].Addr) } - return + return addrs }(), ) defer func() { diff --git a/internal/xsql/conn.go b/internal/xsql/conn.go index 03ffaa1ef..82bbddd5e 100644 --- a/internal/xsql/conn.go +++ b/internal/xsql/conn.go @@ -149,13 +149,16 @@ func (c *conn) isReady() bool { return c.session.Status() == table.SessionReady } -func (c *conn) PrepareContext(ctx context.Context, query string) (_ driver.Stmt, finalErr error) { +func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { if c.currentTx != nil { return c.currentTx.PrepareContext(ctx, query) } - onDone := trace.DatabaseSQLOnConnPrepare(c.trace, &ctx, - stack.FunctionID(""), - query, + var ( + finalErr error + onDone = trace.DatabaseSQLOnConnPrepare(c.trace, &ctx, + stack.FunctionID(""), + query, + ) ) defer func() { onDone(finalErr) @@ -179,7 +182,7 @@ func (c *conn) sinceLastUsage() time.Duration { } func (c *conn) execContext(ctx context.Context, query string, args []driver.NamedValue) ( - _ driver.Result, finalErr error, + driver.Result, error, ) { defer func() { c.lastUsage.Store(time.Now().Unix()) @@ -200,6 +203,7 @@ func (c *conn) execContext(ctx context.Context, query string, args []driver.Name stack.FunctionID(""), query, m.String(), xcontext.IsIdempotent(ctx), c.sinceLastUsage(), ) + finalErr error ) defer func() { onDone(finalErr) @@ -269,7 +273,7 @@ func (c *conn) execContext(ctx context.Context, query string, args []driver.Name } } -func (c *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (_ driver.Result, _ error) { +func (c *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { if !c.isReady() { return nil, badconn.Map(xerrors.WithStackTrace(errNotReadyConn)) } @@ -280,7 +284,7 @@ func (c *conn) ExecContext(ctx context.Context, query string, args []driver.Name return c.execContext(ctx, query, args) } -func (c *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (_ driver.Rows, _ error) { +func (c *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { if !c.isReady() { return nil, badconn.Map(xerrors.WithStackTrace(errNotReadyConn)) } @@ -292,7 +296,7 @@ func (c *conn) QueryContext(ctx context.Context, query string, args []driver.Nam } func (c *conn) queryContext(ctx context.Context, query string, args []driver.NamedValue) ( - _ driver.Rows, finalErr error, + driver.Rows, error, ) { defer func() { c.lastUsage.Store(time.Now().Unix()) @@ -313,6 +317,7 @@ func (c *conn) queryContext(ctx context.Context, query string, args []driver.Nam stack.FunctionID(""), query, m.String(), xcontext.IsIdempotent(ctx), c.sinceLastUsage(), ) + finalErr error ) defer func() { onDone(finalErr) @@ -396,8 +401,11 @@ func (c *conn) queryContext(ctx context.Context, query string, args []driver.Nam } } -func (c *conn) Ping(ctx context.Context) (finalErr error) { - onDone := trace.DatabaseSQLOnConnPing(c.trace, &ctx, stack.FunctionID("")) +func (c *conn) Ping(ctx context.Context) error { + var ( + finalErr error + onDone = trace.DatabaseSQLOnConnPing(c.trace, &ctx, stack.FunctionID("")) + ) defer func() { onDone(finalErr) }() @@ -411,7 +419,8 @@ func (c *conn) Ping(ctx context.Context) (finalErr error) { return nil } -func (c *conn) Close() (finalErr error) { +func (c *conn) Close() error { + var finalErr error if c.closed.CompareAndSwap(false, true) { c.connector.detach(c) onDone := trace.DatabaseSQLOnConnClose( @@ -443,8 +452,9 @@ func (c *conn) Begin() (driver.Tx, error) { return nil, errDeprecated } -func (c *conn) normalize(q string, args ...driver.NamedValue) (query string, _ *table.QueryParameters, _ error) { - return c.connector.Bindings.RewriteQuery(q, func() (ii []interface{}) { +func (c *conn) normalize(q string, args ...driver.NamedValue) (string, *table.QueryParameters, error) { + return c.connector.Bindings.RewriteQuery(q, func() []interface{} { + var ii []interface{} for i := range args { ii = append(ii, args[i]) } @@ -457,9 +467,12 @@ func (c *conn) ID() string { return c.session.ID() } -func (c *conn) BeginTx(ctx context.Context, txOptions driver.TxOptions) (_ driver.Tx, finalErr error) { - var tx currentTx - onDone := trace.DatabaseSQLOnConnBegin(c.trace, &ctx, stack.FunctionID("")) +func (c *conn) BeginTx(ctx context.Context, txOptions driver.TxOptions) (driver.Tx, error) { + var ( + tx currentTx + finalErr error + onDone = trace.DatabaseSQLOnConnBegin(c.trace, &ctx, stack.FunctionID("")) + ) defer func() { onDone(tx, finalErr) }() @@ -505,11 +518,15 @@ func (c *conn) Version(_ context.Context) (_ string, _ error) { return version, nil } -func (c *conn) IsTableExists(ctx context.Context, tableName string) (tableExists bool, finalErr error) { +func (c *conn) IsTableExists(ctx context.Context, tableName string) (bool, error) { tableName = c.normalizePath(tableName) - onDone := trace.DatabaseSQLOnConnIsTableExists(c.trace, &ctx, - stack.FunctionID(""), - tableName, + var ( + tableExists bool + finalErr error + onDone = trace.DatabaseSQLOnConnIsTableExists(c.trace, &ctx, + stack.FunctionID(""), + tableName, + ) ) defer func() { onDone(tableExists, finalErr) @@ -525,8 +542,9 @@ func (c *conn) IsTableExists(ctx context.Context, tableName string) (tableExists return tableExists, nil } -func (c *conn) IsColumnExists(ctx context.Context, tableName, columnName string) (columnExists bool, _ error) { +func (c *conn) IsColumnExists(ctx context.Context, tableName, columnName string) (bool, error) { tableName = c.normalizePath(tableName) + var columnExists bool tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, scheme.EntryTable, scheme.EntryColumnTable, @@ -538,10 +556,10 @@ func (c *conn) IsColumnExists(ctx context.Context, tableName, columnName string) return false, xerrors.WithStackTrace(fmt.Errorf("table '%s' not exist", tableName)) } - err = retry.Retry(ctx, func(ctx context.Context) (err error) { - desc, err := c.session.DescribeTable(ctx, tableName) - if err != nil { - return err + err = retry.Retry(ctx, func(ctx context.Context) error { + desc, errIn := c.session.DescribeTable(ctx, tableName) + if errIn != nil { + return errIn } for i := range desc.Columns { if desc.Columns[i].Name == columnName { @@ -560,7 +578,8 @@ func (c *conn) IsColumnExists(ctx context.Context, tableName, columnName string) return columnExists, nil } -func (c *conn) GetColumns(ctx context.Context, tableName string) (columns []string, _ error) { +func (c *conn) GetColumns(ctx context.Context, tableName string) ([]string, error) { + var columns []string tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -573,10 +592,10 @@ func (c *conn) GetColumns(ctx context.Context, tableName string) (columns []stri return nil, xerrors.WithStackTrace(fmt.Errorf("table '%s' not exist", tableName)) } - err = retry.Retry(ctx, func(ctx context.Context) (err error) { - desc, err := c.session.DescribeTable(ctx, tableName) - if err != nil { - return err + err = retry.Retry(ctx, func(ctx context.Context) error { + desc, errIn := c.session.DescribeTable(ctx, tableName) + if errIn != nil { + return errIn } for i := range desc.Columns { columns = append(columns, desc.Columns[i].Name) @@ -591,7 +610,7 @@ func (c *conn) GetColumns(ctx context.Context, tableName string) (columns []stri return columns, nil } -func (c *conn) GetColumnType(ctx context.Context, tableName, columnName string) (dataType string, _ error) { +func (c *conn) GetColumnType(ctx context.Context, tableName, columnName string) (string, error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -612,10 +631,11 @@ func (c *conn) GetColumnType(ctx context.Context, tableName, columnName string) return "", xerrors.WithStackTrace(fmt.Errorf("column '%s' not exist in table '%s'", columnName, tableName)) } - err = retry.Retry(ctx, func(ctx context.Context) (err error) { - desc, err := c.session.DescribeTable(ctx, tableName) - if err != nil { - return err + var dataType string + err = retry.Retry(ctx, func(ctx context.Context) error { + desc, errIn := c.session.DescribeTable(ctx, tableName) + if errIn != nil { + return errIn } for i := range desc.Columns { if desc.Columns[i].Name == columnName { @@ -634,7 +654,7 @@ func (c *conn) GetColumnType(ctx context.Context, tableName, columnName string) return dataType, nil } -func (c *conn) GetPrimaryKeys(ctx context.Context, tableName string) (pkCols []string, _ error) { +func (c *conn) GetPrimaryKeys(ctx context.Context, tableName string) ([]string, error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -647,10 +667,11 @@ func (c *conn) GetPrimaryKeys(ctx context.Context, tableName string) (pkCols []s return nil, xerrors.WithStackTrace(fmt.Errorf("table '%s' not exist", tableName)) } - err = retry.Retry(ctx, func(ctx context.Context) (err error) { - desc, err := c.session.DescribeTable(ctx, tableName) - if err != nil { - return err + var pkCols []string + err = retry.Retry(ctx, func(ctx context.Context) error { + desc, errIn := c.session.DescribeTable(ctx, tableName) + if errIn != nil { + return errIn } pkCols = append(pkCols, desc.PrimaryKey...) @@ -663,7 +684,7 @@ func (c *conn) GetPrimaryKeys(ctx context.Context, tableName string) (pkCols []s return pkCols, nil } -func (c *conn) IsPrimaryKey(ctx context.Context, tableName, columnName string) (ok bool, _ error) { +func (c *conn) IsPrimaryKey(ctx context.Context, tableName, columnName string) (bool, error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -684,6 +705,7 @@ func (c *conn) IsPrimaryKey(ctx context.Context, tableName, columnName string) ( return false, xerrors.WithStackTrace(fmt.Errorf("column '%s' not exist in table '%s'", columnName, tableName)) } + var ok bool pkCols, err := c.GetPrimaryKeys(ctx, tableName) if err != nil { return false, xerrors.WithStackTrace(err) @@ -699,7 +721,7 @@ func (c *conn) IsPrimaryKey(ctx context.Context, tableName, columnName string) ( return ok, nil } -func (c *conn) normalizePath(folderOrTable string) (absPath string) { +func (c *conn) normalizePath(folderOrTable string) string { return c.connector.pathNormalizer.NormalizePath(folderOrTable) } @@ -717,14 +739,17 @@ func isSysDir(databaseName, dirAbsPath string) bool { } func (c *conn) getTables(ctx context.Context, absPath string, recursive, excludeSysDirs bool) ( - tables []string, _ error, + []string, error, ) { if excludeSysDirs && isSysDir(c.connector.parent.Name(), absPath) { return nil, nil } - var d scheme.Directory - err := retry.Retry(ctx, func(ctx context.Context) (err error) { + var ( + d scheme.Directory + err error + ) + err = retry.Retry(ctx, func(ctx context.Context) error { d, err = c.connector.parent.Scheme().ListDirectory(ctx, absPath) return err @@ -737,6 +762,7 @@ func (c *conn) getTables(ctx context.Context, absPath string, recursive, exclude return nil, xerrors.WithStackTrace(fmt.Errorf("'%s' is not a folder", absPath)) } + var tables []string for i := range d.Children { switch d.Children[i].Type { case scheme.EntryTable, scheme.EntryColumnTable: @@ -756,12 +782,16 @@ func (c *conn) getTables(ctx context.Context, absPath string, recursive, exclude } func (c *conn) GetTables(ctx context.Context, folder string, recursive, excludeSysDirs bool) ( - tables []string, _ error, + []string, error, ) { absPath := c.normalizePath(folder) - var e scheme.Entry - err := retry.Retry(ctx, func(ctx context.Context) (err error) { + var ( + e scheme.Entry + err error + tables []string + ) + err = retry.Retry(ctx, func(ctx context.Context) error { e, err = c.connector.parent.Scheme().DescribePath(ctx, absPath) return err @@ -791,7 +821,7 @@ func (c *conn) GetTables(ctx context.Context, folder string, recursive, excludeS } } -func (c *conn) GetIndexes(ctx context.Context, tableName string) (indexes []string, _ error) { +func (c *conn) GetIndexes(ctx context.Context, tableName string) ([]string, error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -804,10 +834,11 @@ func (c *conn) GetIndexes(ctx context.Context, tableName string) (indexes []stri return nil, xerrors.WithStackTrace(fmt.Errorf("table '%s' not exist", tableName)) } - err = retry.Retry(ctx, func(ctx context.Context) (err error) { - desc, err := c.session.DescribeTable(ctx, tableName) - if err != nil { - return err + var indexes []string + err = retry.Retry(ctx, func(ctx context.Context) error { + desc, errIn := c.session.DescribeTable(ctx, tableName) + if errIn != nil { + return errIn } for i := range desc.Indexes { indexes = append(indexes, desc.Indexes[i].Name) @@ -822,7 +853,7 @@ func (c *conn) GetIndexes(ctx context.Context, tableName string) (indexes []stri return indexes, nil } -func (c *conn) GetIndexColumns(ctx context.Context, tableName, indexName string) (columns []string, _ error) { +func (c *conn) GetIndexColumns(ctx context.Context, tableName, indexName string) ([]string, error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -835,10 +866,11 @@ func (c *conn) GetIndexColumns(ctx context.Context, tableName, indexName string) return nil, xerrors.WithStackTrace(fmt.Errorf("table '%s' not exist", tableName)) } - err = retry.Retry(ctx, func(ctx context.Context) (err error) { - desc, err := c.session.DescribeTable(ctx, tableName) - if err != nil { - return err + var columns []string + err = retry.Retry(ctx, func(ctx context.Context) error { + desc, errIn := c.session.DescribeTable(ctx, tableName) + if errIn != nil { + return errIn } for i := range desc.Indexes { if desc.Indexes[i].Name == indexName { diff --git a/internal/xsql/connector.go b/internal/xsql/connector.go index a00246969..0fb02d3e6 100644 --- a/internal/xsql/connector.go +++ b/internal/xsql/connector.go @@ -195,7 +195,7 @@ type ydbDriver interface { Scheme() scheme.Client } -func Open(parent ydbDriver, opts ...ConnectorOption) (_ *Connector, err error) { +func Open(parent ydbDriver, opts ...ConnectorOption) (*Connector, error) { c := &Connector{ parent: parent, clock: clockwork.NewRealClock(), @@ -207,7 +207,7 @@ func Open(parent ydbDriver, opts ...ConnectorOption) (_ *Connector, err error) { } for _, opt := range opts { if opt != nil { - if err = opt.Apply(c); err != nil { + if err := opt.Apply(c); err != nil { return nil, err } } @@ -257,9 +257,8 @@ var ( _ io.Closer = &Connector{} ) -func (c *Connector) idleCloser() (idleStopper func()) { - var ctx context.Context - ctx, idleStopper = xcontext.WithCancel(context.Background()) +func (c *Connector) idleCloser() func() { + ctx, idleStopper := xcontext.WithCancel(context.Background()) go func() { for { select { @@ -284,7 +283,7 @@ func (c *Connector) idleCloser() (idleStopper func()) { return idleStopper } -func (c *Connector) Close() (err error) { +func (c *Connector) Close() error { defer func() { for _, onClose := range c.onClose { onClose(c) @@ -309,13 +308,14 @@ func (c *Connector) detach(cc *conn) { delete(c.conns, cc) } -func (c *Connector) Connect(ctx context.Context) (_ driver.Conn, err error) { +func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { var ( onDone = trace.DatabaseSQLOnConnectorConnect( c.trace, &ctx, stack.FunctionID(""), ) session table.ClosableSession + err error ) defer func() { onDone(err, session) diff --git a/internal/xsql/context.go b/internal/xsql/context.go index af1516de0..fa07ea3c8 100644 --- a/internal/xsql/context.go +++ b/internal/xsql/context.go @@ -39,7 +39,8 @@ func WithTxControl(ctx context.Context, txc *table.TransactionControl) context.C return context.WithValue(ctx, ctxTransactionControlKey{}, txc) } -func txControl(ctx context.Context, defaultTxControl *table.TransactionControl) (txControl *table.TransactionControl) { +func txControl(ctx context.Context, defaultTxControl *table.TransactionControl) *table.TransactionControl { + var txControl *table.TransactionControl defer func() { if hook, has := ctx.Value(ctxTxControlHookKey{}).(txControlHook); has && hook != nil { hook(txControl) diff --git a/internal/xsql/dsn.go b/internal/xsql/dsn.go index 508308995..8a5e3a482 100644 --- a/internal/xsql/dsn.go +++ b/internal/xsql/dsn.go @@ -16,11 +16,15 @@ import ( const tablePathPrefixTransformer = "table_path_prefix" -func Parse(dataSourceName string) (opts []config.Option, connectorOpts []ConnectorOption, _ error) { +func Parse(dataSourceName string) ([]config.Option, []ConnectorOption, error) { info, err := dsn.Parse(dataSourceName) if err != nil { return nil, nil, xerrors.WithStackTrace(err) } + var ( + opts []config.Option + connectorOpts []ConnectorOption + ) opts = append(opts, info.Options...) if token := info.Params.Get("token"); token != "" { opts = append(opts, config.WithCredentials(credentials.NewAccessTokenCredentials(token))) diff --git a/internal/xsql/isolation/isolation.go b/internal/xsql/isolation/isolation.go index e7f6a7b9d..6461dff6a 100644 --- a/internal/xsql/isolation/isolation.go +++ b/internal/xsql/isolation/isolation.go @@ -13,7 +13,7 @@ import ( // This caused by ydb logic that prevents start actual transaction with OnlineReadOnly mode and ReadCommitted // and ReadUncommitted isolation levels should use tx_control in every query request. // It returns error on unsupported options. -func ToYDB(opts driver.TxOptions) (txcControl table.TxOption, err error) { +func ToYDB(opts driver.TxOptions) (table.TxOption, error) { level := sql.IsolationLevel(opts.Isolation) switch level { case sql.LevelDefault, sql.LevelSerializable: diff --git a/internal/xsql/rows.go b/internal/xsql/rows.go index 01dccaeb3..d20f9319c 100644 --- a/internal/xsql/rows.go +++ b/internal/xsql/rows.go @@ -75,7 +75,7 @@ func (r *rows) ColumnTypeDatabaseTypeName(index int) string { // TODO: Need to store column nullables to internal rows cache. // //nolint:godox -func (r *rows) ColumnTypeNullable(index int) (nullable, ok bool) { +func (r *rows) ColumnTypeNullable(index int) (nullable, ok bool) { //nolint:nonamedreturns //gocritic more important r.nextSet.Do(func() { r.result.NextResultSet(context.Background()) }) @@ -92,7 +92,7 @@ func (r *rows) ColumnTypeNullable(index int) (nullable, ok bool) { return nullables[index], true } -func (r *rows) NextResultSet() (finalErr error) { +func (r *rows) NextResultSet() error { r.nextSet.Do(func() {}) err := r.result.NextResultSetErr(context.Background()) if err != nil { @@ -146,7 +146,8 @@ type single struct { readAll bool } -func (r *single) Columns() (columns []string) { +func (r *single) Columns() []string { + columns := make([]string, 0, len(r.values)) for i := range r.values { columns = append(columns, r.values[i].Name) } diff --git a/internal/xsql/stmt.go b/internal/xsql/stmt.go index 82d80a916..9cc9c340c 100644 --- a/internal/xsql/stmt.go +++ b/internal/xsql/stmt.go @@ -29,10 +29,13 @@ var ( _ driver.StmtExecContext = &stmt{} ) -func (s *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (_ driver.Rows, finalErr error) { - onDone := trace.DatabaseSQLOnStmtQuery(s.trace, &ctx, - stack.FunctionID(""), - s.stmtCtx, s.query, +func (s *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { + var ( + finalErr error + onDone = trace.DatabaseSQLOnStmtQuery(s.trace, &ctx, + stack.FunctionID(""), + s.stmtCtx, s.query, + ) ) defer func() { onDone(finalErr) @@ -48,10 +51,13 @@ func (s *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (_ dr } } -func (s *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (_ driver.Result, finalErr error) { - onDone := trace.DatabaseSQLOnStmtExec(s.trace, &ctx, - stack.FunctionID(""), - s.stmtCtx, s.query, +func (s *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { + var ( + finalErr error + onDone = trace.DatabaseSQLOnStmtExec(s.trace, &ctx, + stack.FunctionID(""), + s.stmtCtx, s.query, + ) ) defer func() { onDone(finalErr) @@ -71,8 +77,11 @@ func (s *stmt) NumInput() int { return -1 } -func (s *stmt) Close() (finalErr error) { - onDone := trace.DatabaseSQLOnStmtClose(s.trace, &s.stmtCtx, stack.FunctionID("")) +func (s *stmt) Close() error { + var ( + finalErr error + onDone = trace.DatabaseSQLOnStmtClose(s.trace, &s.stmtCtx, stack.FunctionID("")) + ) defer func() { onDone(finalErr) }() diff --git a/internal/xsql/tx.go b/internal/xsql/tx.go index 24eab6e73..d00d97a9b 100644 --- a/internal/xsql/tx.go +++ b/internal/xsql/tx.go @@ -72,10 +72,13 @@ func (tx *tx) checkTxState() error { ) } -func (tx *tx) Commit() (finalErr error) { - onDone := trace.DatabaseSQLOnTxCommit(tx.conn.trace, &tx.txCtx, - stack.FunctionID(""), - tx, +func (tx *tx) Commit() error { + var ( + finalErr error + onDone = trace.DatabaseSQLOnTxCommit(tx.conn.trace, &tx.txCtx, + stack.FunctionID(""), + tx, + ) ) defer func() { onDone(finalErr) @@ -94,10 +97,13 @@ func (tx *tx) Commit() (finalErr error) { return nil } -func (tx *tx) Rollback() (finalErr error) { - onDone := trace.DatabaseSQLOnTxRollback(tx.conn.trace, &tx.txCtx, - stack.FunctionID(""), - tx, +func (tx *tx) Rollback() error { + var ( + finalErr error + onDone = trace.DatabaseSQLOnTxRollback(tx.conn.trace, &tx.txCtx, + stack.FunctionID(""), + tx, + ) ) defer func() { onDone(finalErr) @@ -117,11 +123,14 @@ func (tx *tx) Rollback() (finalErr error) { } func (tx *tx) QueryContext(ctx context.Context, query string, args []driver.NamedValue) ( - _ driver.Rows, finalErr error, + driver.Rows, error, ) { - onDone := trace.DatabaseSQLOnTxQuery(tx.conn.trace, &ctx, - stack.FunctionID(""), - tx.txCtx, tx, query, true, + var ( + finalErr error + onDone = trace.DatabaseSQLOnTxQuery(tx.conn.trace, &ctx, + stack.FunctionID(""), + tx.txCtx, tx, query, true, + ) ) defer func() { onDone(finalErr) @@ -159,11 +168,14 @@ func (tx *tx) QueryContext(ctx context.Context, query string, args []driver.Name } func (tx *tx) ExecContext(ctx context.Context, query string, args []driver.NamedValue) ( - _ driver.Result, finalErr error, + driver.Result, error, ) { - onDone := trace.DatabaseSQLOnTxExec(tx.conn.trace, &ctx, - stack.FunctionID(""), - tx.txCtx, tx, query, true, + var ( + finalErr error + onDone = trace.DatabaseSQLOnTxExec(tx.conn.trace, &ctx, + stack.FunctionID(""), + tx.txCtx, tx, query, true, + ) ) defer func() { onDone(finalErr) @@ -194,10 +206,13 @@ func (tx *tx) ExecContext(ctx context.Context, query string, args []driver.Named return resultNoRows{}, nil } -func (tx *tx) PrepareContext(ctx context.Context, query string) (_ driver.Stmt, finalErr error) { - onDone := trace.DatabaseSQLOnTxPrepare(tx.conn.trace, &ctx, - stack.FunctionID(""), - &tx.txCtx, tx, query, +func (tx *tx) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + var ( + finalErr error + onDone = trace.DatabaseSQLOnTxPrepare(tx.conn.trace, &ctx, + stack.FunctionID(""), + &tx.txCtx, tx, query, + ) ) defer func() { onDone(finalErr) diff --git a/internal/xsql/tx_fake.go b/internal/xsql/tx_fake.go index 662fcd078..14f60ce9c 100644 --- a/internal/xsql/tx_fake.go +++ b/internal/xsql/tx_fake.go @@ -18,10 +18,13 @@ type txFake struct { ctx context.Context } -func (tx *txFake) PrepareContext(ctx context.Context, query string) (_ driver.Stmt, finalErr error) { - onDone := trace.DatabaseSQLOnTxPrepare(tx.conn.trace, &ctx, - stack.FunctionID(""), - &tx.beginCtx, tx, query, +func (tx *txFake) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + var ( + finalErr error + onDone = trace.DatabaseSQLOnTxPrepare(tx.conn.trace, &ctx, + stack.FunctionID(""), + &tx.beginCtx, tx, query, + ) ) defer func() { onDone(finalErr) @@ -57,10 +60,13 @@ func (tx *txFake) ID() string { return "FAKE" } -func (tx *txFake) Commit() (err error) { - onDone := trace.DatabaseSQLOnTxCommit(tx.conn.trace, &tx.ctx, - stack.FunctionID(""), - tx, +func (tx *txFake) Commit() error { + var ( + err error + onDone = trace.DatabaseSQLOnTxCommit(tx.conn.trace, &tx.ctx, + stack.FunctionID(""), + tx, + ) ) defer func() { onDone(err) @@ -75,10 +81,13 @@ func (tx *txFake) Commit() (err error) { return nil } -func (tx *txFake) Rollback() (err error) { - onDone := trace.DatabaseSQLOnTxRollback(tx.conn.trace, &tx.ctx, - stack.FunctionID(""), - tx, +func (tx *txFake) Rollback() error { + var ( + err error + onDone = trace.DatabaseSQLOnTxRollback(tx.conn.trace, &tx.ctx, + stack.FunctionID(""), + tx, + ) ) defer func() { onDone(err) @@ -94,17 +103,20 @@ func (tx *txFake) Rollback() (err error) { } func (tx *txFake) QueryContext(ctx context.Context, query string, args []driver.NamedValue) ( - rows driver.Rows, err error, + driver.Rows, error, ) { - onDone := trace.DatabaseSQLOnTxQuery( - tx.conn.trace, &ctx, - stack.FunctionID(""), - tx.ctx, tx, query, xcontext.IsIdempotent(ctx), + var ( + err error + onDone = trace.DatabaseSQLOnTxQuery( + tx.conn.trace, &ctx, + stack.FunctionID(""), + tx.ctx, tx, query, xcontext.IsIdempotent(ctx), + ) ) defer func() { onDone(err) }() - rows, err = tx.conn.QueryContext(ctx, query, args) + rows, err := tx.conn.QueryContext(ctx, query, args) if err != nil { return nil, xerrors.WithStackTrace(err) } @@ -113,17 +125,20 @@ func (tx *txFake) QueryContext(ctx context.Context, query string, args []driver. } func (tx *txFake) ExecContext(ctx context.Context, query string, args []driver.NamedValue) ( - result driver.Result, err error, + driver.Result, error, ) { - onDone := trace.DatabaseSQLOnTxExec( - tx.conn.trace, &ctx, - stack.FunctionID(""), - tx.ctx, tx, query, xcontext.IsIdempotent(ctx), + var ( + err error + onDone = trace.DatabaseSQLOnTxExec( + tx.conn.trace, &ctx, + stack.FunctionID(""), + tx.ctx, tx, query, xcontext.IsIdempotent(ctx), + ) ) defer func() { onDone(err) }() - result, err = tx.conn.ExecContext(ctx, query, args) + result, err := tx.conn.ExecContext(ctx, query, args) if err != nil { return nil, xerrors.WithStackTrace(err) } diff --git a/internal/xsql/unwrap.go b/internal/xsql/unwrap.go index 5f54b0252..de1464d19 100644 --- a/internal/xsql/unwrap.go +++ b/internal/xsql/unwrap.go @@ -8,7 +8,11 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/internal/xsql/badconn" ) -func Unwrap[T *sql.DB | *sql.Conn](v T) (connector *Connector, err error) { +func Unwrap[T *sql.DB | *sql.Conn](v T) (*Connector, error) { + var ( + connector *Connector + err error + ) switch vv := any(v).(type) { case *sql.DB: d := vv.Driver() diff --git a/internal/xstring/convert.go b/internal/xstring/convert.go index eb7ee4b05..62416bfa0 100644 --- a/internal/xstring/convert.go +++ b/internal/xstring/convert.go @@ -15,7 +15,7 @@ func FromBytes(b []byte) string { return unsafe.String(&b[0], len(b)) } -func ToBytes(s string) (b []byte) { +func ToBytes(s string) []byte { if s == "" { return nil } diff --git a/log/coordination.go b/log/coordination.go index 1485118de..a6e881d53 100644 --- a/log/coordination.go +++ b/log/coordination.go @@ -5,6 +5,6 @@ import ( ) // Coordination makes trace.Coordination with logging events from details -func Coordination(l Logger, d trace.Detailer, opts ...Option) (t trace.Coordination) { - return t +func Coordination(l Logger, d trace.Detailer, opts ...Option) trace.Coordination { + return trace.Coordination{} } diff --git a/log/discovery.go b/log/discovery.go index 452c61876..aa20b8352 100644 --- a/log/discovery.go +++ b/log/discovery.go @@ -7,11 +7,12 @@ import ( ) // Discovery makes trace.Discovery with logging events from details -func Discovery(l Logger, d trace.Detailer, opts ...Option) (t trace.Discovery) { +func Discovery(l Logger, d trace.Detailer, opts ...Option) trace.Discovery { return internalDiscovery(wrapLogger(l, opts...), d) } -func internalDiscovery(l Logger, d trace.Detailer) (t trace.Discovery) { +func internalDiscovery(l *wrapper, d trace.Detailer) trace.Discovery { //nolint:interfacer //deprecated + var t trace.Discovery t.OnDiscover = func(info trace.DiscoveryDiscoverStartInfo) func(trace.DiscoveryDiscoverDoneInfo) { if d.Details()&trace.DiscoveryEvents == 0 { return nil diff --git a/log/driver.go b/log/driver.go index a94ffb262..9c32d087e 100644 --- a/log/driver.go +++ b/log/driver.go @@ -9,11 +9,13 @@ import ( ) // Driver makes trace.Driver with logging events from details -func Driver(l Logger, d trace.Detailer, opts ...Option) (t trace.Driver) { +func Driver(l Logger, d trace.Detailer, opts ...Option) trace.Driver { return internalDriver(wrapLogger(l, opts...), d) } -func internalDriver(l Logger, d trace.Detailer) (t trace.Driver) { //nolint:gocyclo +//nolint:gocyclo +func internalDriver(l *wrapper, d trace.Detailer) trace.Driver { //nolint:interfacer //deprecated + var t trace.Driver t.OnResolve = func( info trace.DriverResolveStartInfo, ) func( diff --git a/log/field.go b/log/field.go index af6f65598..912b029d4 100644 --- a/log/field.go +++ b/log/field.go @@ -313,7 +313,8 @@ const ( endType ) -func (ft FieldType) String() (typeName string) { +func (ft FieldType) String() string { + var typeName string switch ft { case InvalidType: typeName = "invalid" diff --git a/log/ratelimiter.go b/log/ratelimiter.go index 55a7dc162..a637aa3c8 100644 --- a/log/ratelimiter.go +++ b/log/ratelimiter.go @@ -5,6 +5,6 @@ import ( ) // Ratelimiter returns trace.Ratelimiter with logging events from details -func Ratelimiter(l Logger, d trace.Detailer, opts ...Option) (t trace.Ratelimiter) { - return t +func Ratelimiter(l Logger, d trace.Detailer, opts ...Option) trace.Ratelimiter { + return trace.Ratelimiter{} } diff --git a/log/retry.go b/log/retry.go index 8b52911b7..512372574 100644 --- a/log/retry.go +++ b/log/retry.go @@ -9,11 +9,12 @@ import ( ) // Retry returns trace.Retry with logging events from details -func Retry(l Logger, d trace.Detailer, opts ...Option) (t trace.Retry) { +func Retry(l Logger, d trace.Detailer, opts ...Option) trace.Retry { return internalRetry(wrapLogger(l, opts...), d) } -func internalRetry(l Logger, d trace.Detailer) (t trace.Retry) { +func internalRetry(l *wrapper, d trace.Detailer) trace.Retry { //nolint:interfacer //deprecated + var t trace.Retry t.OnRetry = func( info trace.RetryLoopStartInfo, ) func( diff --git a/log/scheme.go b/log/scheme.go index 586bf0797..21cba0a68 100644 --- a/log/scheme.go +++ b/log/scheme.go @@ -5,6 +5,6 @@ import ( ) // Scheme returns trace.Scheme with logging events from details -func Scheme(l Logger, d trace.Detailer, opts ...Option) (t trace.Scheme) { - return t +func Scheme(l Logger, d trace.Detailer, opts ...Option) trace.Scheme { + return trace.Scheme{} } diff --git a/log/scripting.go b/log/scripting.go index 4af256cb1..778726fad 100644 --- a/log/scripting.go +++ b/log/scripting.go @@ -7,11 +7,12 @@ import ( ) // Scripting returns trace.Scripting with logging events from details -func Scripting(l Logger, d trace.Detailer, opts ...Option) (t trace.Scripting) { +func Scripting(l Logger, d trace.Detailer, opts ...Option) trace.Scripting { return internalScripting(wrapLogger(l, opts...), d) } -func internalScripting(l *wrapper, d trace.Detailer) (t trace.Scripting) { +func internalScripting(l *wrapper, d trace.Detailer) trace.Scripting { + var t trace.Scripting t.OnExecute = func(info trace.ScriptingExecuteStartInfo) func(trace.ScriptingExecuteDoneInfo) { if d.Details()&trace.ScriptingEvents == 0 { return nil diff --git a/log/sql.go b/log/sql.go index 3a71f3cb7..779814c4c 100644 --- a/log/sql.go +++ b/log/sql.go @@ -9,11 +9,12 @@ import ( ) // DatabaseSQL makes trace.DatabaseSQL with logging events from details -func DatabaseSQL(l Logger, d trace.Detailer, opts ...Option) (t trace.DatabaseSQL) { +func DatabaseSQL(l Logger, d trace.Detailer, opts ...Option) trace.DatabaseSQL { return internalDatabaseSQL(wrapLogger(l, opts...), d) } -func internalDatabaseSQL(l *wrapper, d trace.Detailer) (t trace.DatabaseSQL) { +func internalDatabaseSQL(l *wrapper, d trace.Detailer) trace.DatabaseSQL { + var t trace.DatabaseSQL t.OnConnectorConnect = func( info trace.DatabaseSQLConnectorConnectStartInfo, ) func( diff --git a/log/table.go b/log/table.go index 5afa72bee..b85cbfc57 100644 --- a/log/table.go +++ b/log/table.go @@ -10,12 +10,13 @@ import ( ) // Table makes trace.Table with logging events from details -func Table(l Logger, d trace.Detailer, opts ...Option) (t trace.Table) { +func Table(l Logger, d trace.Detailer, opts ...Option) trace.Table { return internalTable(wrapLogger(l, opts...), d) } //nolint:gocyclo -func internalTable(l *wrapper, d trace.Detailer) (t trace.Table) { +func internalTable(l *wrapper, d trace.Detailer) trace.Table { + var t trace.Table t.OnDo = func( info trace.TableDoStartInfo, ) func( diff --git a/log/topic.go b/log/topic.go index 87d645d9b..da6e79d27 100644 --- a/log/topic.go +++ b/log/topic.go @@ -8,11 +8,13 @@ import ( ) // Topic returns trace.Topic with logging events from details -func Topic(l Logger, d trace.Detailer, opts ...Option) (t trace.Topic) { +func Topic(l Logger, d trace.Detailer, opts ...Option) trace.Topic { return internalTopic(wrapLogger(l, opts...), d) } -func internalTopic(l Logger, d trace.Detailer) (t trace.Topic) { //nolint:gocyclo +//nolint:gocyclo +func internalTopic(l *wrapper, d trace.Detailer) trace.Topic { //nolint:interfacer //deprecated + var t trace.Topic t.OnReaderReconnect = func( info trace.TopicReaderReconnectStartInfo, ) func(doneInfo trace.TopicReaderReconnectDoneInfo) { diff --git a/meta/consumed_units.go b/meta/consumed_units.go index ea4617962..43f004b33 100644 --- a/meta/consumed_units.go +++ b/meta/consumed_units.go @@ -8,7 +8,8 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/internal/meta" ) -func ConsumedUnits(md metadata.MD) (consumedUnits uint64) { +func ConsumedUnits(md metadata.MD) uint64 { + var consumedUnits uint64 for header, values := range md { if header != meta.HeaderConsumedUnits { continue diff --git a/meta/example_test.go b/meta/example_test.go index 97ae1e67b..f352cf0ef 100644 --- a/meta/example_test.go +++ b/meta/example_test.go @@ -29,10 +29,10 @@ func Example_consumedUnitsCount() { meta.WithTrailerCallback(ctx, func(md metadata.MD) { totalConsumedUnits += meta.ConsumedUnits(md) }), - func(ctx context.Context, s table.Session) (err error) { // retry operation - _, res, err := s.Execute(ctx, table.DefaultTxControl(), query, nil) - if err != nil { - return err // for auto-retry with driver + func(ctx context.Context, s table.Session) error { // retry operation + _, res, errIn := s.Execute(ctx, table.DefaultTxControl(), query, nil) + if errIn != nil { + return errIn // for auto-retry with driver } defer res.Close() // cleanup resources if err = res.NextResultSetErr(ctx); err != nil { // check single result set and switch to it diff --git a/metrics/coordination.go b/metrics/coordination.go index 75e7a5537..cc6b50719 100644 --- a/metrics/coordination.go +++ b/metrics/coordination.go @@ -4,6 +4,6 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ) -func coordination(config Config) (t trace.Coordination) { - return t +func coordination(config Config) trace.Coordination { + return trace.Coordination{} } diff --git a/metrics/discovery.go b/metrics/discovery.go index 01d94a5b8..ab3feafb8 100644 --- a/metrics/discovery.go +++ b/metrics/discovery.go @@ -4,6 +4,6 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ) -func discovery(config Config) (t trace.Discovery) { - return t +func discovery(config Config) trace.Discovery { + return trace.Discovery{} } diff --git a/metrics/driver.go b/metrics/driver.go index f20e7ae09..0aac033c1 100644 --- a/metrics/driver.go +++ b/metrics/driver.go @@ -9,7 +9,7 @@ import ( ) // driver makes driver with New publishing -func driver(config Config) (t trace.Driver) { +func driver(config Config) trace.Driver { config = config.WithSystem("driver") endpoints := config.WithSystem("balancer").GaugeVec("endpoints", "local_dc", "az") balancersDiscoveries := config.WithSystem("balancer").CounterVec("discoveries", "status", "cause") @@ -18,6 +18,7 @@ func driver(config Config) (t trace.Driver) { banned := config.WithSystem("conn").GaugeVec("banned", "endpoint", "node_id", "cause") requests := config.WithSystem("conn").CounterVec("requests", "status", "method", "endpoint", "node_id") tli := config.CounterVec("transaction_locks_invalidated") + var t trace.Driver type endpointKey struct { localDC bool diff --git a/metrics/ratelimiter.go b/metrics/ratelimiter.go index da06d7561..491bc4ece 100644 --- a/metrics/ratelimiter.go +++ b/metrics/ratelimiter.go @@ -4,6 +4,6 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ) -func ratelimiter(config Config) (t trace.Ratelimiter) { - return t +func ratelimiter(config Config) trace.Ratelimiter { + return trace.Ratelimiter{} } diff --git a/metrics/retry.go b/metrics/retry.go index 35b0fe9a0..7ea38f907 100644 --- a/metrics/retry.go +++ b/metrics/retry.go @@ -6,11 +6,12 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ) -func retry(config Config) (t trace.Retry) { +func retry(config Config) trace.Retry { config = config.WithSystem("retry") errs := config.CounterVec("errors", "status", "retry_label", "final") attempts := config.HistogramVec("attempts", []float64{0, 1, 2, 3, 4, 5, 7, 10}, "retry_label") latency := config.TimerVec("latency", "retry_label") + var t trace.Retry t.OnRetry = func(info trace.RetryLoopStartInfo) func(trace.RetryLoopIntermediateInfo) func(trace.RetryLoopDoneInfo) { label := info.Label if label == "" { diff --git a/metrics/scheme.go b/metrics/scheme.go index 6e8506524..b4f94401c 100644 --- a/metrics/scheme.go +++ b/metrics/scheme.go @@ -4,6 +4,6 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ) -func scheme(config Config) (t trace.Scheme) { - return t +func scheme(config Config) trace.Scheme { + return trace.Scheme{} } diff --git a/metrics/scripting.go b/metrics/scripting.go index 6f288c637..a4ab7a439 100644 --- a/metrics/scripting.go +++ b/metrics/scripting.go @@ -4,6 +4,6 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ) -func scripting(config Config) (t trace.Scripting) { - return t +func scripting(config Config) trace.Scripting { + return trace.Scripting{} } diff --git a/metrics/sql.go b/metrics/sql.go index 66b1303a2..b67a95334 100644 --- a/metrics/sql.go +++ b/metrics/sql.go @@ -7,7 +7,7 @@ import ( ) // databaseSQL makes trace.DatabaseSQL with measuring `database/sql` events -func databaseSQL(config Config) (t trace.DatabaseSQL) { +func databaseSQL(config Config) trace.DatabaseSQL { config = config.WithSystem("database").WithSystem("sql") conns := config.GaugeVec("conns") inflight := config.WithSystem("conns").GaugeVec("inflight") @@ -27,6 +27,7 @@ func databaseSQL(config Config) (t trace.DatabaseSQL) { txCommitLatency := config.WithSystem("commit").TimerVec("latency") txRollback := config.CounterVec("rollback", "status") txRollbackLatency := config.WithSystem("rollback").TimerVec("latency") + var t trace.DatabaseSQL t.OnConnectorConnect = func(info trace.DatabaseSQLConnectorConnectStartInfo) func( trace.DatabaseSQLConnectorConnectDoneInfo, ) { diff --git a/metrics/table.go b/metrics/table.go index 80dda3cec..a3ab0a1fb 100644 --- a/metrics/table.go +++ b/metrics/table.go @@ -8,7 +8,7 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ) -func table(config Config) (t trace.Table) { +func table(config Config) trace.Table { config = config.WithSystem("table") alive := config.GaugeVec("sessions", "node_id") config = config.WithSystem("pool") @@ -18,6 +18,7 @@ func table(config Config) (t trace.Table) { inflightLatency := config.WithSystem("inflight").TimerVec("latency") wait := config.GaugeVec("wait") waitLatency := config.WithSystem("wait").TimerVec("latency") + var t trace.Table t.OnInit = func(info trace.TableInitStartInfo) func(trace.TableInitDoneInfo) { return func(info trace.TableInitDoneInfo) { limit.With(nil).Set(float64(info.Limit)) diff --git a/retry/retry.go b/retry/retry.go index d936fd5a2..d01993696 100644 --- a/retry/retry.go +++ b/retry/retry.go @@ -336,7 +336,7 @@ func Retry(ctx context.Context, op retryOperation, opts ...Option) (finalErr err } // Check returns retry mode for queryErr. -func Check(err error) (m retryMode) { +func Check(err error) retryMode { code, errType, backoffType, deleteSession := xerrors.Check(err) return retryMode{ diff --git a/retry/retryable_error.go b/retry/retryable_error.go index e0778c1df..b62abaa19 100644 --- a/retry/retryable_error.go +++ b/retry/retryable_error.go @@ -28,7 +28,8 @@ func WithDeleteSession() retryableErrorOption { func RetryableError(err error, opts ...retryableErrorOption) error { return xerrors.Retryable( err, - func() (retryableErrorOptions []xerrors.RetryableErrorOption) { + func() []xerrors.RetryableErrorOption { + var retryableErrorOptions []xerrors.RetryableErrorOption for _, o := range opts { if o != nil { retryableErrorOptions = append(retryableErrorOptions, xerrors.RetryableErrorOption(o)) diff --git a/scheme/scheme.go b/scheme/scheme.go index c7a3e9274..946e60c5b 100644 --- a/scheme/scheme.go +++ b/scheme/scheme.go @@ -145,7 +145,8 @@ func entryType(t Ydb_Scheme.Entry_Type) EntryType { } } -func makePermissions(src []*Ydb_Scheme.Permissions) (dst []Permissions) { +func makePermissions(src []*Ydb_Scheme.Permissions) []Permissions { + dst := make([]Permissions, 0, len(src)) for _, p := range src { dst = append(dst, from(p)) } @@ -153,7 +154,7 @@ func makePermissions(src []*Ydb_Scheme.Permissions) (dst []Permissions) { return dst } -func from(y *Ydb_Scheme.Permissions) (p Permissions) { +func from(y *Ydb_Scheme.Permissions) Permissions { return Permissions{ Subject: y.Subject, PermissionNames: y.PermissionNames, diff --git a/scripting/example_test.go b/scripting/example_test.go index aa96dd85a..84ac2a62e 100644 --- a/scripting/example_test.go +++ b/scripting/example_test.go @@ -19,14 +19,14 @@ func Example_execute() { return } defer db.Close(ctx) // cleanup resources - if err = retry.Retry(ctx, func(ctx context.Context) (err error) { - res, err := db.Scripting().Execute( + if err = retry.Retry(ctx, func(ctx context.Context) error { + res, errIn := db.Scripting().Execute( ctx, "SELECT 1+1", table.NewQueryParameters(), ) - if err != nil { - return err + if errIn != nil { + return errIn } defer res.Close() // cleanup resources if !res.NextResultSet(ctx) { @@ -64,14 +64,14 @@ func Example_streamExecute() { return } defer db.Close(ctx) // cleanup resources - if err = retry.Retry(ctx, func(ctx context.Context) (err error) { - res, err := db.Scripting().StreamExecute( + if err = retry.Retry(ctx, func(ctx context.Context) error { + res, errIn := db.Scripting().StreamExecute( ctx, "SELECT 1+1", table.NewQueryParameters(), ) - if err != nil { - return err + if errIn != nil { + return errIn } defer res.Close() // cleanup resources if !res.NextResultSet(ctx) { @@ -137,14 +137,14 @@ func Example_explainValidate() { return } defer db.Close(ctx) // cleanup resources - if err = retry.Retry(ctx, func(ctx context.Context) (err error) { - res, err := db.Scripting().Explain( + if err = retry.Retry(ctx, func(ctx context.Context) error { + res, errIn := db.Scripting().Explain( ctx, "SELECT 1+1", scripting.ExplainModeValidate, ) - if err != nil { - return err + if errIn != nil { + return errIn } if len(res.ParameterTypes) > 0 { return retry.RetryableError(fmt.Errorf("unexpected parameter types")) diff --git a/sugar/certificates.go b/sugar/certificates.go index 5ab386c34..b530515f2 100644 --- a/sugar/certificates.go +++ b/sugar/certificates.go @@ -20,10 +20,11 @@ func LoadCertificatesFromFile(caFile string) ([]*x509.Certificate, error) { } // LoadCertificatesFromPem parse bytes and returns certificates -func LoadCertificatesFromPem(bytes []byte) (certs []*x509.Certificate) { +func LoadCertificatesFromPem(bytes []byte) []*x509.Certificate { var ( - cert *x509.Certificate - err error + cert *x509.Certificate + certs []*x509.Certificate + err error ) for len(bytes) > 0 { var block *pem.Block @@ -42,5 +43,5 @@ func LoadCertificatesFromPem(bytes []byte) (certs []*x509.Certificate) { certs = append(certs, cert) } - return + return certs } diff --git a/sugar/check_exists.go b/sugar/check_exists.go index 59d27e56a..eb985d3ab 100644 --- a/sugar/check_exists.go +++ b/sugar/check_exists.go @@ -8,7 +8,7 @@ import ( "github.com/ydb-platform/ydb-go-sdk/v3/scheme" ) -func IsTableExists(ctx context.Context, c scheme.Client, absTablePath string) (exists bool, _ error) { +func IsTableExists(ctx context.Context, c scheme.Client, absTablePath string) (bool, error) { exists, err := helpers.IsEntryExists(ctx, c, absTablePath, scheme.EntryTable) if err != nil { return exists, xerrors.WithStackTrace(err) @@ -17,7 +17,7 @@ func IsTableExists(ctx context.Context, c scheme.Client, absTablePath string) (e return exists, nil } -func IsColumnTableExists(ctx context.Context, c scheme.Client, absTablePath string) (exists bool, _ error) { +func IsColumnTableExists(ctx context.Context, c scheme.Client, absTablePath string) (bool, error) { exists, err := helpers.IsEntryExists(ctx, c, absTablePath, scheme.EntryColumnTable) if err != nil { return exists, xerrors.WithStackTrace(err) @@ -27,7 +27,7 @@ func IsColumnTableExists(ctx context.Context, c scheme.Client, absTablePath stri } func IsEntryExists(ctx context.Context, c scheme.Client, absPath string, entryTypes ...scheme.EntryType) ( - exists bool, _ error, + bool, error, ) { exists, err := helpers.IsEntryExists(ctx, c, absPath, entryTypes...) if err != nil { @@ -37,7 +37,7 @@ func IsEntryExists(ctx context.Context, c scheme.Client, absPath string, entryTy return exists, nil } -func IsDirectoryExists(ctx context.Context, c scheme.Client, absTablePath string) (exists bool, _ error) { +func IsDirectoryExists(ctx context.Context, c scheme.Client, absTablePath string) (bool, error) { exists, err := helpers.IsDirectoryExists(ctx, c, absTablePath) if err != nil { return exists, xerrors.WithStackTrace(err) diff --git a/sugar/dsn.go b/sugar/dsn.go index b94e5fc57..741defcaf 100644 --- a/sugar/dsn.go +++ b/sugar/dsn.go @@ -9,7 +9,7 @@ import "net/url" // ) // DSN makes connection string (data source name) by endpoint, database and secure -func DSN(endpoint, database string, secure bool) (s string) { +func DSN(endpoint, database string, secure bool) string { qp := url.Values{} dsn := url.URL{ diff --git a/sugar/params.go b/sugar/params.go index 24c7f897c..15a33579c 100644 --- a/sugar/params.go +++ b/sugar/params.go @@ -22,7 +22,8 @@ func GenerateDeclareSection[T *table.QueryParameters | []table.ParameterOption | case []table.ParameterOption: return internal.GenerateDeclareSection(table.NewQueryParameters(v...)) case []sql.NamedArg: - values, err := bind.Params(func() (newArgs []interface{}) { + values, err := bind.Params(func() []interface{} { + var newArgs []interface{} for i := range v { newArgs = append(newArgs, v[i]) } diff --git a/sugar/params_test.go b/sugar/params_test.go index 8ef2d46bb..deb839d86 100644 --- a/sugar/params_test.go +++ b/sugar/params_test.go @@ -17,7 +17,8 @@ import ( ) func TestGenerateDeclareSection(t *testing.T) { - splitDeclares := func(declaresSection string) (declares []string) { + splitDeclares := func(declaresSection string) []string { + var declares []string for _, s := range strings.Split(declaresSection, ";") { s = strings.TrimSpace(s) if s != "" { @@ -117,7 +118,8 @@ func TestGenerateDeclareSection(t *testing.T) { func TestGenerateDeclareSection_ParameterOption(t *testing.T) { b := testutil.QueryBind(bind.AutoDeclare{}) - getDeclares := func(declaresSection string) (declares []string) { + getDeclares := func(declaresSection string) []string { + var declares []string for _, s := range strings.Split(declaresSection, "\n") { s = strings.TrimSpace(s) if s != "" && !strings.HasPrefix(s, "--") { @@ -224,7 +226,8 @@ func TestGenerateDeclareSection_ParameterOption(t *testing.T) { func TestGenerateDeclareSection_NamedArg(t *testing.T) { b := testutil.QueryBind(bind.AutoDeclare{}) - getDeclares := func(declaresSection string) (declares []string) { + getDeclares := func(declaresSection string) []string { + var declares []string for _, s := range strings.Split(declaresSection, "\n") { s = strings.TrimSpace(s) if s != "" && !strings.HasPrefix(s, "--") { diff --git a/sugar/path.go b/sugar/path.go index cc22e15aa..440733a17 100644 --- a/sugar/path.go +++ b/sugar/path.go @@ -133,7 +133,7 @@ func RemoveRecursive(ctx context.Context, db dbFoRemoveRecursive, pathToRemove s } case scheme.EntryTable, scheme.EntryColumnTable: - err = db.Table().Do(ctx, func(ctx context.Context, session table.Session) (err error) { + err = db.Table().Do(ctx, func(ctx context.Context, session table.Session) error { return session.DropTable(ctx, pt) }, table.WithIdempotent()) if err != nil { diff --git a/table/example_test.go b/table/example_test.go index 430c28f84..bb277257a 100644 --- a/table/example_test.go +++ b/table/example_test.go @@ -33,10 +33,10 @@ func Example_select() { ) err = db.Table().Do( // Do retry operation on errors with best effort ctx, // context manage exiting from Do - func(ctx context.Context, s table.Session) (err error) { // retry operation - _, res, err := s.Execute(ctx, table.DefaultTxControl(), query, nil) - if err != nil { - return err // for auto-retry with driver + func(ctx context.Context, s table.Session) error { // retry operation + _, res, errIn := s.Execute(ctx, table.DefaultTxControl(), query, nil) + if errIn != nil { + return errIn // for auto-retry with driver } defer res.Close() // cleanup resources if err = res.NextResultSetErr(ctx); err != nil { // check single result set and switch to it @@ -72,7 +72,7 @@ func Example_createTable() { } defer db.Close(ctx) // cleanup resources err = db.Table().Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path.Join(db.Name(), "series"), options.WithColumn("series_id", types.Optional(types.TypeUint64)), options.WithColumn("title", types.Optional(types.TypeText)), @@ -128,7 +128,7 @@ func Example_bulkUpsert() { // execute bulk upsert with native ydb data err = db.Table().Do( // Do retry operation on errors with best effort ctx, // context manage exiting from Do - func(ctx context.Context, s table.Session) (err error) { // retry operation + func(ctx context.Context, s table.Session) error { // retry operation rows := make([]types.Value, 0, len(logs)) for _, msg := range logs { rows = append(rows, types.StructValue( @@ -159,7 +159,7 @@ func Example_alterTable() { } defer db.Close(ctx) // cleanup resources err = db.Table().Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { return s.AlterTable(ctx, path.Join(db.Name(), "series"), options.WithAddColumn("series_id", types.Optional(types.TypeUint64)), options.WithAddColumn("title", types.Optional(types.TypeText)), @@ -195,9 +195,9 @@ func Example_lazyTransaction() { } defer db.Close(ctx) err = db.Table().Do(ctx, - func(ctx context.Context, session table.Session) (err error) { + func(ctx context.Context, session table.Session) error { // execute query with opening lazy transaction - tx, result, err := session.Execute(ctx, + tx, result, errIn := session.Execute(ctx, table.SerializableReadWriteTxControl(), "DECLARE $id AS Uint64; "+ "SELECT `title`, `description` FROM `path/to/mytable` WHERE id = $id", @@ -205,8 +205,8 @@ func Example_lazyTransaction() { table.ValueParam("$id", types.Uint64Value(1)), ), ) - if err != nil { - return err + if errIn != nil { + return errIn } defer func() { _ = tx.Rollback(ctx) @@ -288,7 +288,7 @@ func Example_bulkUpsertWithCompression() { // execute bulk upsert with native ydb data err = db.Table().Do( // Do retry operation on errors with best effort ctx, // context manage exiting from Do - func(ctx context.Context, s table.Session) (err error) { // retry operation + func(ctx context.Context, s table.Session) error { // retry operation rows := make([]types.Value, 0, len(logs)) for _, msg := range logs { rows = append(rows, types.StructValue( @@ -327,14 +327,14 @@ func Example_dataQueryWithCompression() { ) err = db.Table().Do( // Do retry operation on errors with best effort ctx, // context manage exiting from Do - func(ctx context.Context, s table.Session) (err error) { // retry operation - _, res, err := s.Execute(ctx, table.DefaultTxControl(), query, nil, + func(ctx context.Context, s table.Session) error { // retry operation + _, res, errIn := s.Execute(ctx, table.DefaultTxControl(), query, nil, options.WithCallOptions( grpc.UseCompressor(gzip.Name), ), ) - if err != nil { - return err // for auto-retry with driver + if errIn != nil { + return errIn // for auto-retry with driver } defer res.Close() // cleanup resources if err = res.NextResultSetErr(ctx); err != nil { // check single result set and switch to it @@ -376,14 +376,14 @@ func Example_scanQueryWithCompression() { ) err = db.Table().Do( // Do retry operation on errors with best effort ctx, // context manage exiting from Do - func(ctx context.Context, s table.Session) (err error) { // retry operation - res, err := s.StreamExecuteScanQuery(ctx, query, nil, + func(ctx context.Context, s table.Session) error { // retry operation + res, errIn := s.StreamExecuteScanQuery(ctx, query, nil, options.WithCallOptions( grpc.UseCompressor(gzip.Name), ), ) - if err != nil { - return err // for auto-retry with driver + if errIn != nil { + return errIn // for auto-retry with driver } defer res.Close() // cleanup resources if err = res.NextResultSetErr(ctx); err != nil { // check single result set and switch to it @@ -419,7 +419,7 @@ func Example_copyTables() { } defer db.Close(ctx) // cleanup resources err = db.Table().Do(ctx, - func(ctx context.Context, s table.Session) (err error) { + func(ctx context.Context, s table.Session) error { return s.CopyTables(ctx, options.CopyTablesItem( path.Join(db.Name(), "from", "series"), diff --git a/table/types/cast.go b/table/types/cast.go index 71d8476ea..739c1ebcf 100644 --- a/table/types/cast.go +++ b/table/types/cast.go @@ -20,7 +20,7 @@ func CastTo(v Value, dst interface{}) error { } // IsOptional checks if type is optional and returns innerType if it is. -func IsOptional(t Type) (isOptional bool, innerType Type) { +func IsOptional(t Type) (bool, Type) { if optionalType, isOptional := t.(interface { IsOptional() InnerType() Type @@ -78,7 +78,8 @@ func StructFields(v Value) (map[string]Value, error) { } // VariantValue returns variant value from abstract Value -func VariantValue(v Value) (name string, idx uint32, _ Value, _ error) { +func VariantValue(v Value) (name string, idx uint32, _ Value, _ error) { //nolint:nonamedreturns + // gocritic more important if vv, has := v.(interface { Variant() (name string, index uint32) Value() Value diff --git a/tests/slo/database/sql/main.go b/tests/slo/database/sql/main.go index 6244e917a..e4370dc05 100644 --- a/tests/slo/database/sql/main.go +++ b/tests/slo/database/sql/main.go @@ -63,15 +63,15 @@ func main() { g := errgroup.Group{} for i := uint64(0); i < cfg.InitialDataCount; i++ { - g.Go(func() (err error) { - e, err := gen.Generate() - if err != nil { - return err + g.Go(func() error { + e, errIn := gen.Generate() + if errIn != nil { + return errIn } - _, err = s.Write(ctx, e) - if err != nil { - return err + _, errIn = s.Write(ctx, e) + if errIn != nil { + return errIn } return nil diff --git a/tests/slo/database/sql/storage.go b/tests/slo/database/sql/storage.go index 1fe6a2c38..f9a6d17e2 100755 --- a/tests/slo/database/sql/storage.go +++ b/tests/slo/database/sql/storage.go @@ -76,10 +76,15 @@ type Storage struct { selectQuery string } -func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (s *Storage, err error) { +func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (*Storage, error) { ctx, cancel := context.WithTimeout(ctx, time.Minute*5) defer cancel() + var ( + s *Storage + err error + ) + s = &Storage{ cfg: cfg, createQuery: fmt.Sprintf(createTemplate, cfg.Table, @@ -114,7 +119,12 @@ func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (s *Stora return s, nil } -func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (res generator.Row, attempts int, err error) { +func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (generator.Row, int, error) { + var ( + res generator.Row + attempts int + err error + ) if err = ctx.Err(); err != nil { return generator.Row{}, attempts, err } @@ -123,7 +133,7 @@ func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (res genera defer cancel() err = retry.Do(ydb.WithTxControl(ctx, readTx), s.db, - func(ctx context.Context, cc *sql.Conn) (err error) { + func(ctx context.Context, cc *sql.Conn) error { if err = ctx.Err(); err != nil { return err } @@ -153,7 +163,12 @@ func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (res genera return res, attempts, err } -func (s *Storage) Write(ctx context.Context, e generator.Row) (attempts int, err error) { +func (s *Storage) Write(ctx context.Context, e generator.Row) (int, error) { + var ( + attempts int + err error + ) + if err = ctx.Err(); err != nil { return attempts, err } @@ -162,7 +177,7 @@ func (s *Storage) Write(ctx context.Context, e generator.Row) (attempts int, err defer cancel() err = retry.Do(ydb.WithTxControl(ctx, writeTx), s.db, - func(ctx context.Context, cc *sql.Conn) (err error) { + func(ctx context.Context, cc *sql.Conn) error { if err = ctx.Err(); err != nil { return err } diff --git a/tests/slo/gorm/main.go b/tests/slo/gorm/main.go index ef4a9a079..51b28ab07 100644 --- a/tests/slo/gorm/main.go +++ b/tests/slo/gorm/main.go @@ -63,15 +63,15 @@ func main() { g := errgroup.Group{} for i := uint64(0); i < cfg.InitialDataCount; i++ { - g.Go(func() (err error) { - e, err := gen.Generate() - if err != nil { - return err + g.Go(func() error { + e, errIn := gen.Generate() + if errIn != nil { + return errIn } - _, err = s.Write(ctx, e) - if err != nil { - return err + _, errIn = s.Write(ctx, e) + if errIn != nil { + return errIn } return nil diff --git a/tests/slo/gorm/storage.go b/tests/slo/gorm/storage.go index 2481014f1..8f76fcdb5 100644 --- a/tests/slo/gorm/storage.go +++ b/tests/slo/gorm/storage.go @@ -74,7 +74,12 @@ func NewStorage(cfg *config.Config, poolSize int) (*Storage, error) { return s, nil } -func (s *Storage) Read(ctx context.Context, id generator.RowID) (r generator.Row, attempts int, err error) { +func (s *Storage) Read(ctx context.Context, id generator.RowID) (generator.Row, int, error) { + var ( + r generator.Row + attempts int + err error + ) if err = ctx.Err(); err != nil { return generator.Row{}, attempts, err } @@ -88,7 +93,7 @@ func (s *Storage) Read(ctx context.Context, id generator.RowID) (r generator.Row } err = retry.Do(ydbSDK.WithTxControl(ctx, readTx), db, - func(ctx context.Context, cc *sql.Conn) (err error) { + func(ctx context.Context, cc *sql.Conn) error { if err = ctx.Err(); err != nil { return err } @@ -124,7 +129,11 @@ func (s *Storage) Read(ctx context.Context, id generator.RowID) (r generator.Row return r, attempts, err } -func (s *Storage) Write(ctx context.Context, row generator.Row) (attempts int, err error) { +func (s *Storage) Write(ctx context.Context, row generator.Row) (int, error) { + var ( + attempts int + err error + ) if err = ctx.Err(); err != nil { return attempts, err } @@ -138,7 +147,7 @@ func (s *Storage) Write(ctx context.Context, row generator.Row) (attempts int, e } err = retry.Do(ydbSDK.WithTxControl(ctx, writeTx), db, - func(ctx context.Context, cc *sql.Conn) (err error) { + func(ctx context.Context, cc *sql.Conn) error { if err = ctx.Err(); err != nil { return err } diff --git a/tests/slo/internal/workers/read.go b/tests/slo/internal/workers/read.go index 3fb8212e3..95e7ce1c0 100644 --- a/tests/slo/internal/workers/read.go +++ b/tests/slo/internal/workers/read.go @@ -23,10 +23,13 @@ func (w *Workers) Read(ctx context.Context, wg *sync.WaitGroup, rl *rate.Limiter } } -func (w *Workers) read(ctx context.Context) (err error) { +func (w *Workers) read(ctx context.Context) error { id := uint64(rand.Intn(int(w.cfg.InitialDataCount))) //nolint:gosec // speed more important - var attempts int + var ( + attempts int + err error + ) m := w.m.Start(metrics.JobRead) defer func() { diff --git a/tests/slo/internal/workers/write.go b/tests/slo/internal/workers/write.go index e9c7b7cae..36ecfb2ad 100644 --- a/tests/slo/internal/workers/write.go +++ b/tests/slo/internal/workers/write.go @@ -23,8 +23,11 @@ func (w *Workers) Write(ctx context.Context, wg *sync.WaitGroup, rl *rate.Limite } } -func (w *Workers) write(ctx context.Context, gen *generator.Generator) (err error) { - var row generator.Row +func (w *Workers) write(ctx context.Context, gen *generator.Generator) error { + var ( + row generator.Row + err error + ) row, err = gen.Generate() if err != nil { fmt.Printf("generate error: %v\n", err) diff --git a/tests/slo/native/main.go b/tests/slo/native/main.go index 9d5df4e72..6c7cc008d 100644 --- a/tests/slo/native/main.go +++ b/tests/slo/native/main.go @@ -63,15 +63,15 @@ func main() { g := errgroup.Group{} for i := uint64(0); i < cfg.InitialDataCount; i++ { - g.Go(func() (err error) { - e, err := gen.Generate() - if err != nil { - return err + g.Go(func() error { + e, errIn := gen.Generate() + if errIn != nil { + return errIn } - _, err = s.Write(ctx, e) - if err != nil { - return err + _, errIn = s.Write(ctx, e) + if errIn != nil { + return errIn } return nil diff --git a/tests/slo/native/storage.go b/tests/slo/native/storage.go index 4a438bf10..1b8c65f0e 100755 --- a/tests/slo/native/storage.go +++ b/tests/slo/native/storage.go @@ -90,7 +90,11 @@ func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (*Storage return s, nil } -func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (_ generator.Row, attempts int, err error) { +func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (generator.Row, int, error) { + var ( + attempts int + err error + ) if err = ctx.Err(); err != nil { return generator.Row{}, attempts, err } @@ -101,7 +105,7 @@ func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (_ generato e := generator.Row{} err = s.db.Table().Do(ctx, - func(ctx context.Context, session table.Session) (err error) { + func(ctx context.Context, session table.Session) error { if err = ctx.Err(); err != nil { return err } @@ -155,21 +159,26 @@ func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (_ generato return e, attempts, err } -func (s *Storage) Write(ctx context.Context, e generator.Row) (attempts int, _ error) { - if err := ctx.Err(); err != nil { +func (s *Storage) Write(ctx context.Context, e generator.Row) (int, error) { + var ( + attempts int + err error + ) + if err = ctx.Err(); err != nil { return attempts, err } ctx, cancel := context.WithTimeout(ctx, time.Duration(s.cfg.WriteTimeout)*time.Millisecond) defer cancel() - err := s.db.Table().Do(ctx, + err = s.db.Table().Do(ctx, func(ctx context.Context, session table.Session) error { - if err := ctx.Err(); err != nil { + if err = ctx.Err(); err != nil { return err } - _, res, err := session.Execute(ctx, writeTx, s.upsertQuery, + var res result.Result + _, res, err = session.Execute(ctx, writeTx, s.upsertQuery, table.NewQueryParameters( table.ValueParam("$id", types.Uint64Value(e.ID)), table.ValueParam("$payload_str", types.UTF8Value(*e.PayloadStr)), @@ -241,7 +250,7 @@ func (s *Storage) dropTable(ctx context.Context) error { defer cancel() return s.db.Table().Do(ctx, - func(ctx context.Context, session table.Session) (err error) { + func(ctx context.Context, session table.Session) error { return session.DropTable(ctx, path.Join(s.prefix, s.cfg.Table)) }, table.WithIdempotent(), diff --git a/tests/slo/xorm/main.go b/tests/slo/xorm/main.go index 9d5df4e72..6c7cc008d 100644 --- a/tests/slo/xorm/main.go +++ b/tests/slo/xorm/main.go @@ -63,15 +63,15 @@ func main() { g := errgroup.Group{} for i := uint64(0); i < cfg.InitialDataCount; i++ { - g.Go(func() (err error) { - e, err := gen.Generate() - if err != nil { - return err + g.Go(func() error { + e, errIn := gen.Generate() + if errIn != nil { + return errIn } - _, err = s.Write(ctx, e) - if err != nil { - return err + _, errIn = s.Write(ctx, e) + if errIn != nil { + return errIn } return nil diff --git a/tests/slo/xorm/storage.go b/tests/slo/xorm/storage.go index 87409a738..5eee28b50 100644 --- a/tests/slo/xorm/storage.go +++ b/tests/slo/xorm/storage.go @@ -62,13 +62,15 @@ type Storage struct { cfg *config.Config } -func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (_ *Storage, err error) { +func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (*Storage, error) { s := &Storage{ cfg: cfg, } dsn := s.cfg.Endpoint + s.cfg.DB + var err error + s.cc, err = ydb.Open( ctx, dsn, @@ -116,7 +118,12 @@ func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (_ *Stora return s, nil } -func (s *Storage) Read(ctx context.Context, id generator.RowID) (row generator.Row, attempts int, err error) { +func (s *Storage) Read(ctx context.Context, id generator.RowID) (generator.Row, int, error) { + var ( + row generator.Row + attempts int + err error + ) if err = ctx.Err(); err != nil { return generator.Row{}, attempts, err } @@ -127,8 +134,9 @@ func (s *Storage) Read(ctx context.Context, id generator.RowID) (row generator.R row.ID = id err = retry.Do(ydb.WithTxControl(ctx, readTx), s.x.DB().DB, - func(ctx context.Context, _ *sql.Conn) (err error) { - has, err := s.x.Context(ctx).Where("hash = Digest::NumericHash(?)", id).Get(&row) + func(ctx context.Context, _ *sql.Conn) error { + var has bool + has, err = s.x.Context(ctx).Where("hash = Digest::NumericHash(?)", id).Get(&row) if err != nil { return fmt.Errorf("get entry error: %w", err) } @@ -155,7 +163,11 @@ func (s *Storage) Read(ctx context.Context, id generator.RowID) (row generator.R return row, attempts, err } -func (s *Storage) Write(ctx context.Context, row generator.Row) (attempts int, err error) { +func (s *Storage) Write(ctx context.Context, row generator.Row) (int, error) { + var ( + attempts int + err error + ) if err = ctx.Err(); err != nil { return attempts, err } @@ -164,7 +176,7 @@ func (s *Storage) Write(ctx context.Context, row generator.Row) (attempts int, e defer cancel() err = retry.Do(ydb.WithTxControl(ctx, writeTx), s.x.DB().DB, - func(ctx context.Context, _ *sql.Conn) (err error) { + func(ctx context.Context, _ *sql.Conn) error { if err = ctx.Err(); err != nil { return err } diff --git a/testutil/driver.go b/testutil/driver.go index 48b82d4ca..32ff2e97b 100644 --- a/testutil/driver.go +++ b/testutil/driver.go @@ -148,7 +148,7 @@ func (b *balancerStub) Invoke( args interface{}, reply interface{}, opts ...grpc.CallOption, -) (err error) { +) error { if b.onInvoke == nil { return fmt.Errorf("database.onInvoke() not defined") } @@ -161,7 +161,7 @@ func (b *balancerStub) NewStream( desc *grpc.StreamDesc, method string, opts ...grpc.CallOption, -) (_ grpc.ClientStream, err error) { +) (grpc.ClientStream, error) { if b.onNewStream == nil { return nil, fmt.Errorf("database.onNewStream() not defined") } @@ -169,7 +169,7 @@ func (b *balancerStub) NewStream( return b.onNewStream(ctx, desc, method, opts...) } -func (b *balancerStub) Get(context.Context) (conn grpc.ClientConnInterface, err error) { +func (b *balancerStub) Get(context.Context) (grpc.ClientConnInterface, error) { cc := &clientConn{ onInvoke: b.onInvoke, onNewStream: b.onNewStream, @@ -201,10 +201,10 @@ func WithInvokeHandlers(invokeHandlers InvokeHandlers) balancerOption { args interface{}, reply interface{}, opts ...grpc.CallOption, - ) (err error) { + ) error { if handler, ok := invokeHandlers[Method(method).Code()]; ok { var result proto.Message - result, err = handler(args) + result, err := handler(args) if err != nil { return xerrors.WithStackTrace(err) } @@ -236,7 +236,7 @@ func WithNewStreamHandlers(newStreamHandlers NewStreamHandlers) balancerOption { desc *grpc.StreamDesc, method string, opts ...grpc.CallOption, - ) (_ grpc.ClientStream, err error) { + ) (grpc.ClientStream, error) { if handler, ok := newStreamHandlers[Method(method).Code()]; ok { return handler(desc) } diff --git a/topic/topicoptions/topicoptions_alter.go b/topic/topicoptions/topicoptions_alter.go index 52700a7f4..fda69a958 100644 --- a/topic/topicoptions/topicoptions_alter.go +++ b/topic/topicoptions/topicoptions_alter.go @@ -118,8 +118,8 @@ func ensureAlterConsumer( consumers []rawtopic.AlterConsumer, name string, ) ( - newConsumers []rawtopic.AlterConsumer, - index int, + []rawtopic.AlterConsumer, + int, ) { for i := range consumers { if consumers[i].Name == name { diff --git a/topic/topicwriter/topicwriter.go b/topic/topicwriter/topicwriter.go index a9b5971f3..0865efb97 100644 --- a/topic/topicwriter/topicwriter.go +++ b/topic/topicwriter/topicwriter.go @@ -45,8 +45,8 @@ func (w *Writer) Write(ctx context.Context, messages ...Message) error { // WaitInit waits until the reader is initialized // or an error occurs, return PublicInitialInfo and err -func (w *Writer) WaitInit(ctx context.Context) (err error) { - _, err = w.inner.WaitInit(ctx) +func (w *Writer) WaitInit(ctx context.Context) error { + _, err := w.inner.WaitInit(ctx) if err != nil { return err } @@ -56,7 +56,7 @@ func (w *Writer) WaitInit(ctx context.Context) (err error) { // WaitInitInfo waits until the reader is initialized // or an error occurs, return PublicInitialInfo and err -func (w *Writer) WaitInitInfo(ctx context.Context) (info PublicInitialInfo, err error) { +func (w *Writer) WaitInitInfo(ctx context.Context) (PublicInitialInfo, error) { privateInfo, err := w.inner.WaitInit(ctx) if err != nil { return PublicInitialInfo{}, err diff --git a/trace/details.go b/trace/details.go index d2a65ff89..d92bc5cb4 100644 --- a/trace/details.go +++ b/trace/details.go @@ -182,8 +182,9 @@ func WithPOSIXMatch() matchDetailsOption { } } -func MatchDetails(pattern string, opts ...matchDetailsOption) (d Details) { +func MatchDetails(pattern string, opts ...matchDetailsOption) Details { var ( + d Details h = &matchDetailsOptionsHolder{ defaultDetails: defaultDetails, } diff --git a/trace/driver.go b/trace/driver.go index 9e954874c..da5f5c0a8 100644 --- a/trace/driver.go +++ b/trace/driver.go @@ -88,17 +88,17 @@ type ( type Method string // Name returns the rpc method name. -func (m Method) Name() (s string) { - _, s = m.Split() +func (m Method) Name() string { + _, s := m.Split() - return + return s } // Service returns the rpc service name. -func (m Method) Service() (s string) { - s, _ = m.Split() +func (m Method) Service() string { + s, _ := m.Split() - return + return s } // Issue declare interface of operation error issues @@ -109,7 +109,7 @@ type Issue interface { } // Split returns service name and method. -func (m Method) Split() (service, method string) { +func (m Method) Split() (service, method string) { //nolint:nonamedreturns //gocritic more important i := strings.LastIndex(string(m), "/") if i == -1 { return string(m), string(m) From 7ed5a335de75b42b3eebd7e4312c9cf97fe1ea03 Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Tue, 13 Feb 2024 19:33:13 +0300 Subject: [PATCH 02/10] fix owner's comment about CHANGELOG file --- CHANGELOG.md | 155 --------------------------------------------------- 1 file changed, 155 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c44db3f5a..8cc8d8da0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,161 +7,6 @@ * Fixed topic writer infinite reconnections in some cases * Refactored nil on err `internal/grpcwrapper/rawydb/issues.go`, when golangci-lint nilerr enabled * Refactored nil on err `internal/grpcwrapper/rawtopic/describe_topic.go`, when golangci-lint nilerr enabled -* Refactored `config/defaults.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/basic/database_sql/data.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/basic/database_sql/series.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/basic/gorm/models.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/basic/native/series.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/basic/xorm/data.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/ddl/ddl.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/decimal/main.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/describe/main.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/pagination/cities.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/read_table/orders.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/serverless/healthcheck/service.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/serverless/url_shortener/service.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/topic/cdc-fill-and-read/tables.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/topic/topicreader/stubs.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/topic/topicreader/topicreader_advanced.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/topic/topicreader/topicreader_trace.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/ttl/series.go`, when golangci-lint nonamedreturns enabled -* Refactored `examples/ttl_readtable/series.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/allocator/allocator.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/backoff/backoff_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/balancer/balancer.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/balancer/connections_state.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/balancer/ctx.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/balancer/local_dc.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/bind/auto_declare.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/bind/bind.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/bind/numeric_args.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/bind/params.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/bind/positional_args.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/bind/table_path_prefix.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/certificates/certificates.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/cmd/gtrace/main.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/cmd/gtrace/writer.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/conn/conn.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/conn/grpc_client_stream.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/conn/pool.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/coordination/client.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/credentials/static.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/decimal/decimal.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/discovery/discovery.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/dsn/dsn.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/endpoint/endpoint.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/grpcwrapper/rawtopic/client.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/grpcwrapper/rawtopic/rawtopicreader/messages.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/grpcwrapper/rawtopic/rawtopicwriter/messages.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/meta/meta.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/mock/conn.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/operation/context.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/ratelimiter/client.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/repeater/repeater.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/repeater/repeater_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/scheme/client.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/scheme/helpers/check_exists.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/scheme/helpers/check_exists_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/scripting/client.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/stack/record.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/client.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/client_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/retry.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/retry_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/scanner/result.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/scanner/scan_raw.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/scanner/scanner.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/scanner/scanner_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/scanner/stats.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/session.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/session_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/statement.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/table/transaction.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/retriable_error.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicclientinternal/client.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/batch.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/batcher.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/committer.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/message.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/one_time_reader.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/reader.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/stream_reader_impl.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicreaderinternal/stream_reconnector.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicwriterinternal/queue.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicwriterinternal/writer.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicwriterinternal/writer_reconnector.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/topic/topicwriterinternal/writer_single_stream.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/value/time.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/value/type.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/value/value.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/version/parse.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xcontext/context_with_cancel.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xcontext/context_with_timeout.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xcontext/without_deadline.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xerrors/check.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xerrors/issues.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xerrors/operation.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xresolver/xresolver.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/conn.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/connector.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/context.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/dsn.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/isolation/isolation.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/rows.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/stmt.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/tx.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/tx_fake.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xsql/unwrap.go`, when golangci-lint nonamedreturns enabled -* Refactored `internal/xstring/convert.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/coordination.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/discovery.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/driver.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/field.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/ratelimiter.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/retry.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/scheme.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/scripting.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/sql.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/table.go`, when golangci-lint nonamedreturns enabled -* Refactored `log/topic.go`, when golangci-lint nonamedreturns enabled -* Refactored `meta/consumed_units.go`, when golangci-lint nonamedreturns enabled -* Refactored `meta/example_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/coordination.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/discovery.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/driver.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/ratelimiter.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/retry.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/scheme.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/scripting.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/sql.go`, when golangci-lint nonamedreturns enabled -* Refactored `metrics/table.go`, when golangci-lint nonamedreturns enabled -* Refactored `retry/retry.go`, when golangci-lint nonamedreturns enabled -* Refactored `retry/retryable_error.go`, when golangci-lint nonamedreturns enabled -* Refactored `scheme/scheme.go`, when golangci-lint nonamedreturns enabled -* Refactored `scripting/example_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `sugar/certificates.go`, when golangci-lint nonamedreturns enabled -* Refactored `sugar/check_exists.go`, when golangci-lint nonamedreturns enabled -* Refactored `sugar/dsn.go`, when golangci-lint nonamedreturns enabled -* Refactored `sugar/params.go`, when golangci-lint nonamedreturns enabled -* Refactored `sugar/params_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `sugar/path.go`, when golangci-lint nonamedreturns enabled -* Refactored `table/example_test.go`, when golangci-lint nonamedreturns enabled -* Refactored `table/types/cast.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/database/sql/main.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/database/sql/storage.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/gorm/main.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/gorm/storage.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/internal/workers/read.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/internal/workers/write.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/native/main.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/native/storage.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/xorm/main.go`, when golangci-lint nonamedreturns enabled -* Refactored `tests/slo/xorm/storage.go`, when golangci-lint nonamedreturns enabled -* Refactored `testutil/driver.go`, when golangci-lint nonamedreturns enabled -* Refactored `topic/topicoptions/topicoptions_alter.go`, when golangci-lint nonamedreturns enabled -* Refactored `topic/topicwriter/topicwriter.go`, when golangci-lint nonamedreturns enabled -* Refactored `trace/details.go`, when golangci-lint nonamedreturns enabled -* Refactored `trace/driver.go`, when golangci-lint nonamedreturns enabled ## v3.55.3 * Fixed handle of operational errors in topic streams (backported fix only) From 5c3b04debf2da59ebdda0e5a32e9e2d30b00318e Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Tue, 20 Feb 2024 19:54:14 +0300 Subject: [PATCH 03/10] fix PR comments --- config/defaults.go | 2 +- examples/basic/database_sql/data.go | 42 +++++++++++------------------ 2 files changed, 17 insertions(+), 27 deletions(-) diff --git a/config/defaults.go b/config/defaults.go index 92f7a9b53..a6ec97c3d 100644 --- a/config/defaults.go +++ b/config/defaults.go @@ -31,7 +31,7 @@ var ( ) func defaultGrpcOptions(t *trace.Driver, secure bool, tlsConfig *tls.Config) []grpc.DialOption { - var opts []grpc.DialOption + opts := make([]grpc.DialOption, 0, 5) // capacity is 5 because later will be append 5 objects opts = append(opts, // keep-aliving all connections grpc.WithKeepaliveParams( diff --git a/examples/basic/database_sql/data.go b/examples/basic/database_sql/data.go index a62620e40..e46068f28 100644 --- a/examples/basic/database_sql/data.go +++ b/examples/basic/database_sql/data.go @@ -48,12 +48,8 @@ func episodeData(seriesID, seasonID, episodeID, title string, date time.Time) ty ) } -func getData() ([]types.Value, []types.Value, []types.Value) { - var ( - series = make([]types.Value, 0) - seasons = make([]types.Value, 0) - episodes = make([]types.Value, 0) - ) +//nolint:nonamedreturns +func getData() (series, seasons, episodes []types.Value) { for seriesID, fill := range map[string]func(seriesID string) ( seriesData types.Value, seasons []types.Value, episodes []types.Value, ){ @@ -69,16 +65,13 @@ func getData() ([]types.Value, []types.Value, []types.Value) { return series, seasons, episodes } -func getDataForITCrowd(seriesID string) (types.Value, []types.Value, []types.Value) { - var ( - series = seriesData( - seriesID, date("2006-02-03"), "IT Crowd", ""+ - "The IT Crowd is a British sitcom produced by Channel 4, written by Graham Linehan, produced by "+ - "Ash Atalla and starring Chris O'Dowd, Richard Ayoade, Katherine Parkinson, and Matt Berry.", - "", // NULL comment. - ) - seasons = make([]types.Value, 0) - episodes = make([]types.Value, 0) +//nolint:nonamedreturns +func getDataForITCrowd(seriesID string) (series types.Value, seasons, episodes []types.Value) { + series = seriesData( + seriesID, date("2006-02-03"), "IT Crowd", ""+ + "The IT Crowd is a British sitcom produced by Channel 4, written by Graham Linehan, produced by "+ + "Ash Atalla and starring Chris O'Dowd, Richard Ayoade, Katherine Parkinson, and Matt Berry.", + "", // NULL comment. ) for _, season := range []struct { //nolint:gocritic title string @@ -129,16 +122,13 @@ func getDataForITCrowd(seriesID string) (types.Value, []types.Value, []types.Val return series, seasons, episodes } -func getDataForSiliconValley(seriesID string) (types.Value, []types.Value, []types.Value) { - var ( - series = seriesData( - seriesID, date("2014-04-06"), "Silicon Valley", ""+ - "Silicon Valley is an American comedy television series created by Mike Judge, John Altschuler and "+ - "Dave Krinsky. The series focuses on five young men who founded a startup company in Silicon Valley.", - "Some comment here", - ) - seasons = make([]types.Value, 0) - episodes = make([]types.Value, 0) +//nolint:nonamedreturns +func getDataForSiliconValley(seriesID string) (series types.Value, seasons, episodes []types.Value) { + series = seriesData( + seriesID, date("2014-04-06"), "Silicon Valley", ""+ + "Silicon Valley is an American comedy television series created by Mike Judge, John Altschuler and "+ + "Dave Krinsky. The series focuses on five young men who founded a startup company in Silicon Valley.", + "Some comment here", ) for _, season := range []struct { //nolint:gocritic title string From 27069a25ef19682c02b80da19efdc5630cdcc87b Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Sun, 25 Feb 2024 18:33:11 +0300 Subject: [PATCH 04/10] fixed native/xorm example client tests --- internal/table/client.go | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/internal/table/client.go b/internal/table/client.go index 7ad66049a..977045a21 100644 --- a/internal/table/client.go +++ b/internal/table/client.go @@ -122,11 +122,9 @@ func withCreateSessionOnClose(onClose func(s *session)) createSessionOption { } } -func (c *Client) createSession(ctx context.Context, opts ...createSessionOption) (*session, error) { - var ( - s *session - options = createSessionOptions{} - ) +//nolint:nonamedreturns //because FAIL native example test +func (c *Client) createSession(ctx context.Context, opts ...createSessionOption) (s *session, _ error) { + options := createSessionOptions{} for _, o := range opts { if o != nil { o(&options) @@ -373,7 +371,8 @@ func withTrace(t *trace.Table) getOption { } } -func (c *Client) internalPoolGet(ctx context.Context, opts ...getOption) (*session, error) { +//nolint:nonamedreturns //because FAIL native example test +func (c *Client) internalPoolGet(ctx context.Context, opts ...getOption) (s *session, err error) { if c.isClosed() { return nil, xerrors.WithStackTrace(errClosedClient) } @@ -389,11 +388,7 @@ func (c *Client) internalPoolGet(ctx context.Context, opts ...getOption) (*sessi } } - var ( - s *session - err error - onDone = trace.TableOnPoolGet(o.t, &ctx, stack.FunctionID("")) - ) + onDone := trace.TableOnPoolGet(o.t, &ctx, stack.FunctionID("")) defer func() { onDone(s, i, err) }() @@ -832,6 +827,7 @@ func (c *Client) internalPoolPutWaitCh(ch *chan *session) { //nolint:gocritic c.waitChPool.Put(ch) } +// FAIL native // c.mu must be held. func (c *Client) internalPoolPeekFirstIdle() (*session, time.Time) { var ( From b80e7709d02b05c558807ec950411efaf4597681 Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Sun, 25 Feb 2024 22:54:21 +0300 Subject: [PATCH 05/10] fix test's erorrs --- driver_string_test.go | 4 ++-- internal/repeater/repeater.go | 4 ++-- internal/table/client.go | 12 +++++------- .../topic/topicreaderinternal/stream_reader_impl.go | 7 ++----- 4 files changed, 11 insertions(+), 16 deletions(-) diff --git a/driver_string_test.go b/driver_string_test.go index cc4e1cbe9..89f645eff 100644 --- a/driver_string_test.go +++ b/driver_string_test.go @@ -23,7 +23,7 @@ func TestDriver_String(t *testing.T) { config.WithDatabase("local"), config.WithSecure(false), )}, - s: `Driver{Endpoint:"localhost",Database:"local",Secure:false,Credentials:Anonymous{From:"github.com/ydb-platform/ydb-go-sdk/v3/config.defaultConfig(defaults.go:90)"}}`, //nolint:lll + s: `Driver{Endpoint:"localhost",Database:"local",Secure:false,Credentials:Anonymous{From:"github.com/ydb-platform/ydb-go-sdk/v3/config.defaultConfig(defaults.go:91)"}}`, //nolint:lll }, { name: xtest.CurrentFileLine(), @@ -32,7 +32,7 @@ func TestDriver_String(t *testing.T) { config.WithDatabase("local"), config.WithSecure(true), )}, - s: `Driver{Endpoint:"localhost",Database:"local",Secure:true,Credentials:Anonymous{From:"github.com/ydb-platform/ydb-go-sdk/v3/config.defaultConfig(defaults.go:90)"}}`, //nolint:lll + s: `Driver{Endpoint:"localhost",Database:"local",Secure:true,Credentials:Anonymous{From:"github.com/ydb-platform/ydb-go-sdk/v3/config.defaultConfig(defaults.go:91)"}}`, //nolint:lll }, { name: xtest.CurrentFileLine(), diff --git a/internal/repeater/repeater.go b/internal/repeater/repeater.go index 7562e656e..ffd344499 100644 --- a/internal/repeater/repeater.go +++ b/internal/repeater/repeater.go @@ -139,8 +139,8 @@ func (r *repeater) Force() { } } -func (r *repeater) wakeUp(ctx context.Context, e Event) error { - var err error +func (r *repeater) wakeUp(ctx context.Context, e Event) (err error) { + // FAIL TestRepeaterForceLogBackoff by timeout (10m) if err = ctx.Err(); err != nil { return err } diff --git a/internal/table/client.go b/internal/table/client.go index 977045a21..3d795fc66 100644 --- a/internal/table/client.go +++ b/internal/table/client.go @@ -546,13 +546,11 @@ func (c *Client) internalPoolWaitFromCh(ctx context.Context, t *trace.Table) (*s // Note that Put() must be called only once after being created or received by // Get() or Take() calls. In other way it will produce unexpected behavior or // panic. -func (c *Client) Put(ctx context.Context, s *session) error { - var ( - err error - onDone = trace.TableOnPoolPut(c.config.Trace(), &ctx, - stack.FunctionID(""), - s, - ) +func (c *Client) Put(ctx context.Context, s *session) (err error) { //nolint:nonamedreturns + // because FAIL TestSessionPoolClose + onDone := trace.TableOnPoolPut(c.config.Trace(), &ctx, + stack.FunctionID(""), + s, ) defer func() { onDone(err) diff --git a/internal/topic/topicreaderinternal/stream_reader_impl.go b/internal/topic/topicreaderinternal/stream_reader_impl.go index 7e213ae99..d1080d085 100644 --- a/internal/topic/topicreaderinternal/stream_reader_impl.go +++ b/internal/topic/topicreaderinternal/stream_reader_impl.go @@ -176,11 +176,8 @@ func (r *topicStreamReaderImpl) WaitInit(_ context.Context) error { func (r *topicStreamReaderImpl) ReadMessageBatch( ctx context.Context, opts ReadMessageBatchOptions, -) (*PublicBatch, error) { - var ( - batch *PublicBatch - err error - ) +) (batch *PublicBatch, err error) { + // FAIL TestTopicStreamReaderImpl_BufferCounterOnStopPartition onDone := trace.TopicOnReaderReadMessages( r.cfg.Trace, ctx, From 2a55b1e8b5edd2b6abb38f096fc6e820db9e82ca Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Mon, 26 Feb 2024 21:47:37 +0300 Subject: [PATCH 06/10] fixed integration tests --- internal/repeater/repeater.go | 2 +- internal/table/session.go | 13 ++++--------- internal/table/statement.go | 7 ++----- .../topic/topicreaderinternal/stream_reader_impl.go | 2 +- internal/types/types.go | 6 +++--- 5 files changed, 11 insertions(+), 19 deletions(-) diff --git a/internal/repeater/repeater.go b/internal/repeater/repeater.go index ffd344499..534ec1883 100644 --- a/internal/repeater/repeater.go +++ b/internal/repeater/repeater.go @@ -139,7 +139,7 @@ func (r *repeater) Force() { } } -func (r *repeater) wakeUp(ctx context.Context, e Event) (err error) { +func (r *repeater) wakeUp(ctx context.Context, e Event) (err error) { //nolint:nonamedreturns // FAIL TestRepeaterForceLogBackoff by timeout (10m) if err = ctx.Err(); err != nil { return err diff --git a/internal/table/session.go b/internal/table/session.go index b70f01d45..84c7cbc59 100644 --- a/internal/table/session.go +++ b/internal/table/session.go @@ -717,14 +717,14 @@ func (s *session) Prepare(ctx context.Context, queryText string) (table.Statemen } // Execute executes given data query represented by text. -func (s *session) Execute( +func (s *session) Execute( //nolint:nonamedreturns //because FAIL: TestBasicExampleNative ctx context.Context, txControl *table.TransactionControl, query string, params *table.QueryParameters, opts ...options.ExecuteDataQueryOption, ) ( - table.Transaction, result.Result, error, + txr table.Transaction, r result.Result, err error, ) { var ( a = allocator.New() @@ -734,9 +734,6 @@ func (s *session) Execute( IgnoreTruncated: s.config.IgnoreTruncated(), } callOptions []grpc.CallOption - txr table.Transaction - r result.Result - err error ) defer a.Free() @@ -1243,10 +1240,10 @@ func (s *session) BulkUpsert(ctx context.Context, table string, rows value.Value // BeginTransaction begins new transaction within given session with given // settings. -func (s *session) BeginTransaction( +func (s *session) BeginTransaction( //nolint:nonamedreturns //because FAIL: TestBasicExampleNative ctx context.Context, txSettings *table.TransactionSettings, -) (table.Transaction, error) { +) (x table.Transaction, err error) { var ( result Ydb_Table.BeginTransactionResult response *Ydb_Table.BeginTransactionResponse @@ -1255,8 +1252,6 @@ func (s *session) BeginTransaction( stack.FunctionID(""), s, ) - x table.Transaction - err error ) defer func() { onDone(x, err) diff --git a/internal/table/statement.go b/internal/table/statement.go index 184130514..488d56574 100644 --- a/internal/table/statement.go +++ b/internal/table/statement.go @@ -24,12 +24,12 @@ type statement struct { } // Execute executes prepared data query. -func (s *statement) Execute( +func (s *statement) Execute( //nolint:nonamedreturns //because FAIL: TestBasicExampleNative ctx context.Context, txControl *table.TransactionControl, params *table.QueryParameters, opts ...options.ExecuteDataQueryOption, ) ( - table.Transaction, result.Result, error, + txr table.Transaction, r result.Result, err error, ) { var ( a = allocator.New() @@ -38,9 +38,6 @@ func (s *statement) Execute( IgnoreTruncated: s.session.config.IgnoreTruncated(), } callOptions []grpc.CallOption - txr table.Transaction - r result.Result - err error ) defer a.Free() diff --git a/internal/topic/topicreaderinternal/stream_reader_impl.go b/internal/topic/topicreaderinternal/stream_reader_impl.go index d1080d085..29943ffea 100644 --- a/internal/topic/topicreaderinternal/stream_reader_impl.go +++ b/internal/topic/topicreaderinternal/stream_reader_impl.go @@ -173,7 +173,7 @@ func (r *topicStreamReaderImpl) WaitInit(_ context.Context) error { return nil } -func (r *topicStreamReaderImpl) ReadMessageBatch( +func (r *topicStreamReaderImpl) ReadMessageBatch( //nolint:nonamedreturns ctx context.Context, opts ReadMessageBatchOptions, ) (batch *PublicBatch, err error) { diff --git a/internal/types/types.go b/internal/types/types.go index 719b5341d..ceeefbc60 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -259,7 +259,7 @@ func (v *Dict) ToYDB(a *allocator.Allocator) *Ydb.Type { return t } -func NewDict(key, value Type) (v *Dict) { +func NewDict(key, value Type) *Dict { return &Dict{ keyType: key, valueType: value, @@ -655,7 +655,7 @@ func (v *Struct) ToYDB(a *allocator.Allocator) *Ydb.Type { return t } -func NewStruct(fields ...StructField) (v *Struct) { +func NewStruct(fields ...StructField) *Struct { return &Struct{ fields: fields, } @@ -741,7 +741,7 @@ func (v *Tuple) ToYDB(a *allocator.Allocator) *Ydb.Type { return t } -func NewTuple(items ...Type) (v *Tuple) { +func NewTuple(items ...Type) *Tuple { return &Tuple{ innerTypes: items, } From cf8ffa5b868523f697bdf393c9c5644cd180a99f Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Tue, 27 Feb 2024 22:41:37 +0300 Subject: [PATCH 07/10] fix integration tests --- internal/balancer/balancer.go | 7 ++----- internal/xsql/context.go | 4 ++-- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/internal/balancer/balancer.go b/internal/balancer/balancer.go index 08b02f190..50441e280 100644 --- a/internal/balancer/balancer.go +++ b/internal/balancer/balancer.go @@ -378,11 +378,8 @@ func (b *Balancer) connections() *connectionsState { return b.connectionsState } -func (b *Balancer) getConn(ctx context.Context) (conn.Conn, error) { - var ( - c conn.Conn - err error - ) +//nolint:nonamedreturns // FAIL integration test TestDatabaseSqlWithTxControl +func (b *Balancer) getConn(ctx context.Context) (c conn.Conn, err error) { onDone := trace.DriverOnBalancerChooseEndpoint( b.driverConfig.Trace(), &ctx, stack.FunctionID(""), diff --git a/internal/xsql/context.go b/internal/xsql/context.go index fa07ea3c8..a9f0b6b52 100644 --- a/internal/xsql/context.go +++ b/internal/xsql/context.go @@ -39,8 +39,8 @@ func WithTxControl(ctx context.Context, txc *table.TransactionControl) context.C return context.WithValue(ctx, ctxTransactionControlKey{}, txc) } -func txControl(ctx context.Context, defaultTxControl *table.TransactionControl) *table.TransactionControl { - var txControl *table.TransactionControl +//nolint:nonamedreturns // FAIL integration test TestDatabaseSqlWithTxControl +func txControl(ctx context.Context, defaultTxControl *table.TransactionControl) (txControl *table.TransactionControl) { defer func() { if hook, has := ctx.Value(ctxTxControlHookKey{}).(txControlHook); has && hook != nil { hook(txControl) From 7142fbcb4117af9bb4f8009e7eac38af66a13be1 Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Fri, 1 Mar 2024 22:45:59 +0300 Subject: [PATCH 08/10] fix integration tests --- internal/balancer/balancer.go | 5 +- internal/balancer/connections_state.go | 8 +- internal/bind/bind.go | 11 +-- internal/certificates/certificates.go | 9 +-- internal/cmd/gtrace/writer.go | 10 +-- internal/coordination/client.go | 12 +-- internal/discovery/discovery.go | 16 ++-- internal/ratelimiter/client.go | 14 ++-- internal/repeater/repeater.go | 2 +- internal/scripting/client.go | 16 ++-- internal/table/client.go | 19 ++--- internal/table/client_test.go | 7 +- internal/table/scanner/scan_raw.go | 80 +++++++++++-------- internal/table/scanner/scanner.go | 6 +- internal/table/scanner/scanner_test.go | 10 +-- internal/table/session.go | 9 +-- internal/table/transaction.go | 32 +++----- internal/topic/topicreaderinternal/reader.go | 10 +-- .../topicwriterinternal/writer_reconnector.go | 6 +- internal/xerrors/issues.go | 8 +- internal/xsql/conn.go | 24 +++--- internal/xsql/dsn.go | 7 +- sugar/certificates.go | 2 +- sugar/params_test.go | 6 +- tests/slo/database/sql/storage.go | 7 +- 25 files changed, 148 insertions(+), 188 deletions(-) diff --git a/internal/balancer/balancer.go b/internal/balancer/balancer.go index 50441e280..ab7cccf9e 100644 --- a/internal/balancer/balancer.go +++ b/internal/balancer/balancer.go @@ -230,12 +230,13 @@ func (b *Balancer) Close(ctx context.Context) error { return nil } +//nolint:nonamedreturns // potential error func New( ctx context.Context, driverConfig *config.Config, pool *conn.Pool, opts ...discoveryConfig.Option, -) (*Balancer, error) { +) (b *Balancer, finalErr error) { var ( onDone = trace.DriverOnBalancerInit( driverConfig.Trace(), &ctx, @@ -249,8 +250,6 @@ func New( discoveryConfig.WithSecure(driverConfig.Secure()), discoveryConfig.WithMeta(driverConfig.Meta()), )...) - b *Balancer - finalErr error ) defer func() { onDone(finalErr) diff --git a/internal/balancer/connections_state.go b/internal/balancer/connections_state.go index e35dc55ed..f009d0b9e 100644 --- a/internal/balancer/connections_state.go +++ b/internal/balancer/connections_state.go @@ -117,8 +117,8 @@ func (s *connectionsState) selectRandomConnection(conns []conn.Conn, allowBanned return nil, failedConns } -func connsToNodeIDMap(conns []conn.Conn) map[uint32]conn.Conn { - var nodes map[uint32]conn.Conn +//nolint:nonamedreturns // potential error +func connsToNodeIDMap(conns []conn.Conn) (nodes map[uint32]conn.Conn) { if len(conns) == 0 { return nil } @@ -130,13 +130,13 @@ func connsToNodeIDMap(conns []conn.Conn) map[uint32]conn.Conn { return nodes } +//nolint:nonamedreturns // potential error func sortPreferConnections( conns []conn.Conn, filter balancerConfig.Filter, info balancerConfig.Info, allowFallback bool, -) ([]conn.Conn, []conn.Conn) { - var prefer, fallback []conn.Conn +) (prefer, fallback []conn.Conn) { if filter == nil { return conns, nil } diff --git a/internal/bind/bind.go b/internal/bind/bind.go index f059611b3..1ad263dfc 100644 --- a/internal/bind/bind.go +++ b/internal/bind/bind.go @@ -26,11 +26,12 @@ type Bind interface { type Bindings []Bind +//nolint:nonamedreturns // potential error func (bindings Bindings) RewriteQuery(query string, args ...interface{}) ( - string, []*params.Parameter, error, + yql string, parameters []*params.Parameter, err error, ) { if len(bindings) == 0 { - parameters, err := Params(args...) + parameters, err = Params(args...) if err != nil { return "", nil, xerrors.WithStackTrace(err) } @@ -38,11 +39,7 @@ func (bindings Bindings) RewriteQuery(query string, args ...interface{}) ( return query, parameters, nil } - var ( - parameters []*params.Parameter - err error - buffer = xstring.Buffer() - ) + buffer := xstring.Buffer() defer buffer.Free() for i := range bindings { diff --git a/internal/certificates/certificates.go b/internal/certificates/certificates.go index 5ce0686ff..2faa98528 100644 --- a/internal/certificates/certificates.go +++ b/internal/certificates/certificates.go @@ -173,12 +173,9 @@ func FromPemNoCache(noCache bool) FromPemOption { // FromPem parses one or more certificate from pem blocks in bytes. // It returns nil error if at least one certificate was successfully parsed. // This function uses cached parseCertificate. -func FromPem(bytes []byte, opts ...FromPemOption) ([]*x509.Certificate, error) { - var ( - block *pem.Block - certs []*x509.Certificate - err error - ) +func FromPem(bytes []byte, opts ...FromPemOption) (certs []*x509.Certificate, err error) { //nolint:nonamedreturns + // potential error without named return + var block *pem.Block for len(bytes) > 0 { block, bytes = pem.Decode(bytes) diff --git a/internal/cmd/gtrace/writer.go b/internal/cmd/gtrace/writer.go index fa474ef62..438d92d1e 100644 --- a/internal/cmd/gtrace/writer.go +++ b/internal/cmd/gtrace/writer.go @@ -170,12 +170,10 @@ func forEachField(s *types.Struct, fn func(*types.Var)) { } } -func unwrapStruct(t types.Type) (*types.Named, *types.Struct) { - var ( - ok bool - s *types.Struct - ) - n, ok := t.(*types.Named) +//nolint:nonamedreturns // potential error +func unwrapStruct(t types.Type) (n *types.Named, s *types.Struct) { + var ok bool + n, ok = t.(*types.Named) if ok { s, _ = n.Underlying().(*types.Struct) } diff --git a/internal/coordination/client.go b/internal/coordination/client.go index bd5ccc220..61d59cc0c 100644 --- a/internal/coordination/client.go +++ b/internal/coordination/client.go @@ -156,19 +156,15 @@ func (c *Client) dropNode(ctx context.Context, path string) error { return xerrors.WithStackTrace(err) } +//nolint:nonamedreturns // potential error func (c *Client) DescribeNode( ctx context.Context, path string, ) ( - *scheme.Entry, - *coordination.NodeConfig, - error, + entry *scheme.Entry, + config *coordination.NodeConfig, + err error, ) { - var ( - entry *scheme.Entry - config *coordination.NodeConfig - err error - ) if c == nil { return nil, nil, xerrors.WithStackTrace(errNilClient) } diff --git a/internal/discovery/discovery.go b/internal/discovery/discovery.go index 94c9934e4..a4f7f9853 100644 --- a/internal/discovery/discovery.go +++ b/internal/discovery/discovery.go @@ -36,7 +36,8 @@ type Client struct { } // Discover cluster endpoints -func (c *Client) Discover(ctx context.Context) ([]endpoint.Endpoint, error) { +func (c *Client) Discover(ctx context.Context) (endpoints []endpoint.Endpoint, err error) { //nolint:nonamedreturns + // FAIL integration tests var ( onDone = trace.DiscoveryOnDiscover( c.config.Trace(), &ctx, @@ -46,11 +47,9 @@ func (c *Client) Discover(ctx context.Context) ([]endpoint.Endpoint, error) { request = Ydb_Discovery.ListEndpointsRequest{ Database: c.config.Database(), } - response *Ydb_Discovery.ListEndpointsResponse - result Ydb_Discovery.ListEndpointsResult - location string - endpoints = make([]endpoint.Endpoint, 0, len(result.Endpoints)) - err error + response *Ydb_Discovery.ListEndpointsResponse + result Ydb_Discovery.ListEndpointsResult + location string ) defer func() { nodes := make([]trace.EndpointInfo, 0, len(endpoints)) @@ -99,14 +98,13 @@ func (c *Client) Discover(ctx context.Context) ([]endpoint.Endpoint, error) { return endpoints, nil } -func (c *Client) WhoAmI(ctx context.Context) (*discovery.WhoAmI, error) { +//nolint:nonamedreturns // FAIL integration tests +func (c *Client) WhoAmI(ctx context.Context) (whoAmI *discovery.WhoAmI, err error) { var ( onDone = trace.DiscoveryOnWhoAmI(c.config.Trace(), &ctx, stack.FunctionID("")) request = Ydb_Discovery.WhoAmIRequest{} response *Ydb_Discovery.WhoAmIResponse whoAmIResultResult Ydb_Discovery.WhoAmIResult - whoAmI *discovery.WhoAmI - err error ) defer func() { if err != nil { diff --git a/internal/ratelimiter/client.go b/internal/ratelimiter/client.go index 179a511b4..081b3c41e 100644 --- a/internal/ratelimiter/client.go +++ b/internal/ratelimiter/client.go @@ -183,13 +183,13 @@ func (c *Client) dropResource( return err } +//nolint:nonamedreturns // potential errors func (c *Client) ListResource( ctx context.Context, coordinationNodePath string, resourcePath string, recursive bool, -) ([]string, error) { - var list []string +) (list []string, _ error) { if c == nil { return list, xerrors.WithStackTrace(errNilClient) } @@ -249,11 +249,7 @@ func (c *Client) DescribeResource( ctx context.Context, coordinationNodePath string, resourcePath string, -) (*ratelimiter.Resource, error) { - var ( - resource *ratelimiter.Resource - err error - ) +) (resource *ratelimiter.Resource, err error) { if c == nil { return resource, xerrors.WithStackTrace(errNilClient) } @@ -265,7 +261,7 @@ func (c *Client) DescribeResource( if !c.config.AutoRetry() { err = call(ctx) - return resource, err + return } err = retry.Retry(ctx, call, retry.WithIdempotent(true), @@ -273,7 +269,7 @@ func (c *Client) DescribeResource( retry.WithTrace(c.config.TraceRetry()), ) - return resource, err + return } func (c *Client) describeResource( diff --git a/internal/repeater/repeater.go b/internal/repeater/repeater.go index 534ec1883..11be27b53 100644 --- a/internal/repeater/repeater.go +++ b/internal/repeater/repeater.go @@ -142,7 +142,7 @@ func (r *repeater) Force() { func (r *repeater) wakeUp(ctx context.Context, e Event) (err error) { //nolint:nonamedreturns // FAIL TestRepeaterForceLogBackoff by timeout (10m) if err = ctx.Err(); err != nil { - return err + return } ctx = WithEvent(ctx, e) diff --git a/internal/scripting/client.go b/internal/scripting/client.go index df8bafb04..147f418d5 100644 --- a/internal/scripting/client.go +++ b/internal/scripting/client.go @@ -39,15 +39,12 @@ type ( } ) +//nolint:nonamedreturns // FAIL integration tests func (c *Client) Execute( ctx context.Context, query string, parameters *params.Parameters, -) (result.Result, error) { - var ( - r result.Result - err error - ) +) (r result.Result, err error) { if c == nil { return r, xerrors.WithStackTrace(errNilClient) } @@ -59,7 +56,7 @@ func (c *Client) Execute( if !c.config.AutoRetry() { err = call(ctx) - return r, err + return } err = retry.Retry(ctx, call, retry.WithStackTrace(), @@ -69,14 +66,13 @@ func (c *Client) Execute( return r, xerrors.WithStackTrace(err) } +//nolint:nonamedreturns // FAIL integration tests func (c *Client) execute( ctx context.Context, query string, parameters *params.Parameters, -) (result.Result, error) { +) (r result.Result, err error) { var ( - r result.Result - err error onDone = trace.ScriptingOnExecute(c.config.Trace(), &ctx, stack.FunctionID(""), query, parameters, @@ -240,6 +236,7 @@ func (c *Client) streamExecute( parameters *params.Parameters, ) (result.StreamResult, error) { var ( + err error onIntermediate = trace.ScriptingOnStreamExecute(c.config.Trace(), &ctx, stack.FunctionID(""), query, parameters, @@ -255,7 +252,6 @@ func (c *Client) streamExecute( operation.ModeSync, ), } - err error ) defer func() { a.Free() diff --git a/internal/table/client.go b/internal/table/client.go index 3d795fc66..33ae5bef2 100644 --- a/internal/table/client.go +++ b/internal/table/client.go @@ -472,13 +472,12 @@ func (c *Client) Get(ctx context.Context) (*session, error) { return c.internalPoolGet(ctx) } -func (c *Client) internalPoolWaitFromCh(ctx context.Context, t *trace.Table) (*session, error) { +//nolint:nonamedreturns //because FAIL native example test +func (c *Client) internalPoolWaitFromCh(ctx context.Context, t *trace.Table) (s *session, err error) { var ( - ch *chan *session - el *list.Element // Element in the wait queue. - ok bool - s *session - err error + ch *chan *session + el *list.Element // Element in the wait queue. + ok bool ) c.mu.WithLock(func() { @@ -825,13 +824,9 @@ func (c *Client) internalPoolPutWaitCh(ch *chan *session) { //nolint:gocritic c.waitChPool.Put(ch) } -// FAIL native // c.mu must be held. -func (c *Client) internalPoolPeekFirstIdle() (*session, time.Time) { - var ( - s *session - touched time.Time - ) +func (c *Client) internalPoolPeekFirstIdle() (s *session, touched time.Time) { //nolint:nonamedreturns + // FAIL native el := c.idle.Front() if el == nil { return s, touched diff --git a/internal/table/client_test.go b/internal/table/client_test.go index 908c307b0..4d3cf7510 100644 --- a/internal/table/client_test.go +++ b/internal/table/client_test.go @@ -887,11 +887,8 @@ func newClientWithStubBuilder( return c } -func (s *StubBuilder) createSession(ctx context.Context) (*session, error) { - var ( - session *session - err error - ) +//nolint:nonamedreturns //potential error +func (s *StubBuilder) createSession(ctx context.Context) (session *session, err error) { defer s.mu.WithLock(func() { if session != nil { s.actual++ diff --git a/internal/table/scanner/scan_raw.go b/internal/table/scanner/scan_raw.go index 40be8542e..a2d2a5f6d 100644 --- a/internal/table/scanner/scan_raw.go +++ b/internal/table/scanner/scan_raw.go @@ -21,7 +21,8 @@ type rawConverter struct { *valueScanner } -func (s *rawConverter) String() []byte { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) String() (v []byte) { s.unwrap() return s.bytes() @@ -247,19 +248,22 @@ func (s *rawConverter) UTF8() string { return s.text() } -func (s *rawConverter) YSON() []byte { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) YSON() (v []byte) { s.unwrap() return s.bytes() } -func (s *rawConverter) JSON() []byte { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) JSON() (v []byte) { s.unwrap() return xstring.ToBytes(s.text()) } -func (s *rawConverter) JSONDocument() []byte { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) JSONDocument() (v []byte) { s.unwrap() return xstring.ToBytes(s.text()) @@ -606,15 +610,15 @@ func (s *rawConverter) isCurrentTypeDecimal() bool { return ok } -func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32) (string, *Ydb.Type) { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32) (name string, t *Ydb.Type) { i := int(index) - t := Ydb.Type{} switch x := typ.VariantType.GetType().(type) { case *Ydb.VariantType_TupleItems: if i >= len(x.TupleItems.GetElements()) { _ = s.errorf(0, "unimplemented") - return "", &t + return } return "", x.TupleItems.GetElements()[i] @@ -623,7 +627,7 @@ func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32 if i >= len(x.StructItems.GetMembers()) { _ = s.errorf(0, "unimplemented") - return "", &t + return } m := x.StructItems.GetMembers()[i] @@ -634,15 +638,16 @@ func (s *rawConverter) unwrapVariantType(typ *Ydb.Type_VariantType, index uint32 } } -func (s *rawConverter) variant() (*Ydb.Value, uint32) { - v := s.unwrapValue() +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) variant() (v *Ydb.Value, index uint32) { + v = s.unwrapValue() if v == nil { - return &Ydb.Value{}, 0 + return } x := s.stack.current() // Is not nil if unwrapValue succeeded. - index := x.v.GetVariantIndex() + index = x.v.GetVariantIndex() - return v, index + return } func (s *rawConverter) itemsIn() int { @@ -691,13 +696,14 @@ func (s *rawConverter) boundsCheck(n, i int) bool { return true } -func (s *valueScanner) assertTypeOptional(typ *Ydb.Type) *Ydb.Type_OptionalType { +//nolint:nonamedreturns // FAIL integration tests +func (s *valueScanner) assertTypeOptional(typ *Ydb.Type) (t *Ydb.Type_OptionalType) { x := typ.GetType() - if t, _ := x.(*Ydb.Type_OptionalType); t == nil { + if t, _ = x.(*Ydb.Type_OptionalType); t == nil { s.typeError(x, t) } - return &Ydb.Type_OptionalType{} + return } func (s *rawConverter) assertCurrentTypeNullable() bool { @@ -755,58 +761,64 @@ func (s *rawConverter) assertCurrentTypeDecimal(t types.Type) bool { return true } -func (s *rawConverter) assertTypeList(typ *Ydb.Type) *Ydb.Type_ListType { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) assertTypeList(typ *Ydb.Type) (t *Ydb.Type_ListType) { x := typ.GetType() - if t, _ := x.(*Ydb.Type_ListType); t == nil { + if t, _ = x.(*Ydb.Type_ListType); t == nil { s.typeError(x, t) } - return &Ydb.Type_ListType{} + return } -func (s *rawConverter) assertTypeTuple(typ *Ydb.Type) *Ydb.Type_TupleType { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) assertTypeTuple(typ *Ydb.Type) (t *Ydb.Type_TupleType) { x := typ.GetType() - if t, _ := x.(*Ydb.Type_TupleType); t == nil { + if t, _ = x.(*Ydb.Type_TupleType); t == nil { s.typeError(x, t) } - return &Ydb.Type_TupleType{} + return } -func (s *rawConverter) assertTypeStruct(typ *Ydb.Type) *Ydb.Type_StructType { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) assertTypeStruct(typ *Ydb.Type) (t *Ydb.Type_StructType) { x := typ.GetType() - if t, _ := x.(*Ydb.Type_StructType); t == nil { + if t, _ = x.(*Ydb.Type_StructType); t == nil { s.typeError(x, t) } - return &Ydb.Type_StructType{} + return } -func (s *rawConverter) assertTypeDict(typ *Ydb.Type) *Ydb.Type_DictType { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) assertTypeDict(typ *Ydb.Type) (t *Ydb.Type_DictType) { x := typ.GetType() - if t, _ := x.(*Ydb.Type_DictType); t == nil { + if t, _ = x.(*Ydb.Type_DictType); t == nil { s.typeError(x, t) } - return &Ydb.Type_DictType{} + return } -func (s *rawConverter) assertTypeDecimal(typ *Ydb.Type) *Ydb.Type_DecimalType { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) assertTypeDecimal(typ *Ydb.Type) (t *Ydb.Type_DecimalType) { x := typ.GetType() - if t, _ := x.(*Ydb.Type_DecimalType); t == nil { + if t, _ = x.(*Ydb.Type_DecimalType); t == nil { s.typeError(x, t) } - return &Ydb.Type_DecimalType{} + return } -func (s *rawConverter) assertTypeVariant(typ *Ydb.Type) *Ydb.Type_VariantType { +//nolint:nonamedreturns // FAIL integration tests +func (s *rawConverter) assertTypeVariant(typ *Ydb.Type) (t *Ydb.Type_VariantType) { x := typ.GetType() - if t, _ := x.(*Ydb.Type_VariantType); t == nil { + if t, _ = x.(*Ydb.Type_VariantType); t == nil { s.typeError(x, t) } - return &Ydb.Type_VariantType{} + return } func (s *rawConverter) boundsError(n, i int) { diff --git a/internal/table/scanner/scanner.go b/internal/table/scanner/scanner.go index 5834913d3..5f7cbf9ec 100644 --- a/internal/table/scanner/scanner.go +++ b/internal/table/scanner/scanner.go @@ -527,14 +527,14 @@ func (s *valueScanner) unwrapDecimal() decimal.Decimal { } } -func (s *valueScanner) assertTypeDecimal(typ *Ydb.Type) *Ydb.Type_DecimalType { - var t *Ydb.Type_DecimalType +//nolint:nonamedreturns // FAIL integration tests +func (s *valueScanner) assertTypeDecimal(typ *Ydb.Type) (t *Ydb.Type_DecimalType) { x := typ.GetType() if t, _ = x.(*Ydb.Type_DecimalType); t == nil { s.typeError(x, t) } - return t + return } func (s *valueScanner) bool() bool { diff --git a/internal/table/scanner/scanner_test.go b/internal/table/scanner/scanner_test.go index 3876ba727..c80209c43 100644 --- a/internal/table/scanner/scanner_test.go +++ b/internal/table/scanner/scanner_test.go @@ -512,8 +512,9 @@ func valueFromPrimitiveTypeID(c *column, r xrand.Rand) (*Ydb.Value, interface{}) } } -func getResultSet(count int, col []*column) (*Ydb.ResultSet, [][]indexed.RequiredOrOptional) { - result := &Ydb.ResultSet{} +//nolint:nonamedreturns // potential error +func getResultSet(count int, col []*column) (result *Ydb.ResultSet, testValues [][]indexed.RequiredOrOptional) { + result = &Ydb.ResultSet{} for _, c := range col { t := &Ydb.Type{ Type: &Ydb.Type_TypeId{ @@ -539,7 +540,7 @@ func getResultSet(count int, col []*column) (*Ydb.ResultSet, [][]indexed.Require } r := xrand.New(xrand.WithLock()) - testValues := make([][]indexed.RequiredOrOptional, count) + testValues = make([][]indexed.RequiredOrOptional, count) for i := 0; i < count; i++ { var items []*Ydb.Value var vals []indexed.RequiredOrOptional @@ -565,8 +566,7 @@ func TestScanSqlTypes(t *testing.T) { s.reset(set, test.setColumns...) for s.NextRow() { if test.columns[0].testDefault { - if err := s.ScanWithDefaults(func() []indexed.Required { - var values []indexed.Required + if err := s.ScanWithDefaults(func() (values []indexed.Required) { //nolint:nonamedreturns for _, v := range test.values { values = append(values, v) } diff --git a/internal/table/session.go b/internal/table/session.go index eedaa91dc..f059236a1 100644 --- a/internal/table/session.go +++ b/internal/table/session.go @@ -115,14 +115,11 @@ func (s *session) isClosing() bool { return s.Status() == table.SessionClosing } +//nolint:nonamedreturns // potential error func newSession(ctx context.Context, cc grpc.ClientConnInterface, config *config.Config) ( - *session, error, + s *session, err error, ) { - var ( - s *session - err error - onDone = trace.TableOnSessionNew(config.Trace(), &ctx, stack.FunctionID("")) - ) + onDone := trace.TableOnSessionNew(config.Trace(), &ctx, stack.FunctionID("")) defer func() { onDone(s, err) }() diff --git a/internal/table/transaction.go b/internal/table/transaction.go index 37017c637..bef987df8 100644 --- a/internal/table/transaction.go +++ b/internal/table/transaction.go @@ -56,19 +56,15 @@ func (tx *transaction) ID() string { } // Execute executes query represented by text within transaction tx. -func (tx *transaction) Execute( +func (tx *transaction) Execute( //nolint:nonamedreturns // potential error ctx context.Context, query string, parameters *params.Parameters, opts ...options.ExecuteDataQueryOption, -) (result.Result, error) { - var ( - r result.Result - err error - onDone = trace.TableOnSessionTransactionExecute( - tx.s.config.Trace(), &ctx, - stack.FunctionID(""), - tx.s, tx, queryFromText(query), parameters, - ) +) (r result.Result, err error) { + onDone := trace.TableOnSessionTransactionExecute( + tx.s.config.Trace(), &ctx, + stack.FunctionID(""), + tx.s, tx, queryFromText(query), parameters, ) defer func() { onDone(r, err) @@ -94,22 +90,18 @@ func (tx *transaction) Execute( } // ExecuteStatement executes prepared statement stmt within transaction tx. -func (tx *transaction) ExecuteStatement( +func (tx *transaction) ExecuteStatement( //nolint:nonamedreturns // potential error ctx context.Context, stmt table.Statement, parameters *params.Parameters, opts ...options.ExecuteDataQueryOption, -) (result.Result, error) { +) (r result.Result, err error) { a := allocator.New() defer a.Free() - var ( - r result.Result - err error - onDone = trace.TableOnSessionTransactionExecuteStatement( - tx.s.config.Trace(), &ctx, - stack.FunctionID(""), - tx.s, tx, stmt.(*statement).query, parameters, - ) + onDone := trace.TableOnSessionTransactionExecuteStatement( + tx.s.config.Trace(), &ctx, + stack.FunctionID(""), + tx.s, tx, stmt.(*statement).query, parameters, ) defer func() { onDone(r, err) diff --git a/internal/topic/topicreaderinternal/reader.go b/internal/topic/topicreaderinternal/reader.go index 79a7f07b0..84f49d7b6 100644 --- a/internal/topic/topicreaderinternal/reader.go +++ b/internal/topic/topicreaderinternal/reader.go @@ -140,12 +140,10 @@ func (r *Reader) ReadMessage(ctx context.Context) (*PublicMessage, error) { // ReadMessageBatch read batch of messages. // Batch is collection of messages, which can be atomically committed -func (r *Reader) ReadMessageBatch(ctx context.Context, opts ...PublicReadBatchOption) (*PublicBatch, error) { - var ( - readOptions = r.defaultBatchConfig.clone() - batch *PublicBatch - err error - ) +// +//nolint:nonamedreturns // potential error +func (r *Reader) ReadMessageBatch(ctx context.Context, opts ...PublicReadBatchOption) (batch *PublicBatch, err error) { + readOptions := r.defaultBatchConfig.clone() for _, opt := range opts { if opt != nil { diff --git a/internal/topic/topicwriterinternal/writer_reconnector.go b/internal/topic/topicwriterinternal/writer_reconnector.go index 013bb5fd2..3b4c0a75e 100644 --- a/internal/topic/topicwriterinternal/writer_reconnector.go +++ b/internal/topic/topicwriterinternal/writer_reconnector.go @@ -618,12 +618,12 @@ func allMessagesHasSameBufCodec(messages []messageWithDataContent) bool { return true } -func splitMessagesByBufCodec(messages []messageWithDataContent) [][]messageWithDataContent { +//nolint:nonamedreturns // potential error +func splitMessagesByBufCodec(messages []messageWithDataContent) (res [][]messageWithDataContent) { if len(messages) == 0 { return nil } - var res [][]messageWithDataContent currentGroupStart := 0 currentCodec := messages[0].bufCodec for i := range messages { @@ -635,7 +635,7 @@ func splitMessagesByBufCodec(messages []messageWithDataContent) [][]messageWithD } res = append(res, messages[currentGroupStart:len(messages):len(messages)]) - return res + return } func createWriteRequest(messages []messageWithDataContent, targetCodec rawtopiccommon.Codec) ( diff --git a/internal/xerrors/issues.go b/internal/xerrors/issues.go index 961f2930d..4bfde016c 100644 --- a/internal/xerrors/issues.go +++ b/internal/xerrors/issues.go @@ -128,11 +128,9 @@ func (it IssueIterator) Len() int { return len(it) } -func (it IssueIterator) Get(i int) (Issue, IssueIterator) { - var ( - x = it[i] - nested IssueIterator - ) +//nolint:nonamedreturns // potential error +func (it IssueIterator) Get(i int) (issue Issue, nested IssueIterator) { + x := it[i] if xs := x.GetIssues(); len(xs) > 0 { nested = IssueIterator(xs) } diff --git a/internal/xsql/conn.go b/internal/xsql/conn.go index b7560789d..09f72f1d5 100644 --- a/internal/xsql/conn.go +++ b/internal/xsql/conn.go @@ -576,8 +576,8 @@ func (c *conn) IsColumnExists(ctx context.Context, tableName, columnName string) return columnExists, nil } -func (c *conn) GetColumns(ctx context.Context, tableName string) ([]string, error) { - var columns []string +//nolint:nonamedreturns // potential error +func (c *conn) GetColumns(ctx context.Context, tableName string) (columns []string, _ error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -652,7 +652,8 @@ func (c *conn) GetColumnType(ctx context.Context, tableName, columnName string) return dataType, nil } -func (c *conn) GetPrimaryKeys(ctx context.Context, tableName string) ([]string, error) { +//nolint:nonamedreturns // potential error +func (c *conn) GetPrimaryKeys(ctx context.Context, tableName string) (pkCols []string, _ error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -665,7 +666,6 @@ func (c *conn) GetPrimaryKeys(ctx context.Context, tableName string) ([]string, return nil, xerrors.WithStackTrace(fmt.Errorf("table '%s' not exist", tableName)) } - var pkCols []string err = retry.Retry(ctx, func(ctx context.Context) error { desc, errIn := c.session.DescribeTable(ctx, tableName) if errIn != nil { @@ -736,8 +736,9 @@ func isSysDir(databaseName, dirAbsPath string) bool { return false } +//nolint:nonamedreturns // potential error func (c *conn) getTables(ctx context.Context, absPath string, recursive, excludeSysDirs bool) ( - []string, error, + tables []string, _ error, ) { if excludeSysDirs && isSysDir(c.connector.parent.Name(), absPath) { return nil, nil @@ -760,7 +761,6 @@ func (c *conn) getTables(ctx context.Context, absPath string, recursive, exclude return nil, xerrors.WithStackTrace(fmt.Errorf("'%s' is not a folder", absPath)) } - var tables []string for i := range d.Children { switch d.Children[i].Type { case scheme.EntryTable, scheme.EntryColumnTable: @@ -779,15 +779,15 @@ func (c *conn) getTables(ctx context.Context, absPath string, recursive, exclude return tables, nil } +//nolint:nonamedreturns // potential error func (c *conn) GetTables(ctx context.Context, folder string, recursive, excludeSysDirs bool) ( - []string, error, + tables []string, _ error, ) { absPath := c.normalizePath(folder) var ( - e scheme.Entry - err error - tables []string + e scheme.Entry + err error ) err = retry.Retry(ctx, func(ctx context.Context) error { e, err = c.connector.parent.Scheme().DescribePath(ctx, absPath) @@ -819,7 +819,8 @@ func (c *conn) GetTables(ctx context.Context, folder string, recursive, excludeS } } -func (c *conn) GetIndexes(ctx context.Context, tableName string) ([]string, error) { +//nolint:nonamedreturns // potential error +func (c *conn) GetIndexes(ctx context.Context, tableName string) (indexes []string, _ error) { tableName = c.normalizePath(tableName) tableExists, err := helpers.IsEntryExists(ctx, c.connector.parent.Scheme(), tableName, @@ -832,7 +833,6 @@ func (c *conn) GetIndexes(ctx context.Context, tableName string) ([]string, erro return nil, xerrors.WithStackTrace(fmt.Errorf("table '%s' not exist", tableName)) } - var indexes []string err = retry.Retry(ctx, func(ctx context.Context) error { desc, errIn := c.session.DescribeTable(ctx, tableName) if errIn != nil { diff --git a/internal/xsql/dsn.go b/internal/xsql/dsn.go index 8a5e3a482..351be3d79 100644 --- a/internal/xsql/dsn.go +++ b/internal/xsql/dsn.go @@ -16,15 +16,12 @@ import ( const tablePathPrefixTransformer = "table_path_prefix" -func Parse(dataSourceName string) ([]config.Option, []ConnectorOption, error) { +//nolint:nonamedreturns // potential error +func Parse(dataSourceName string) (opts []config.Option, connectorOpts []ConnectorOption, _ error) { info, err := dsn.Parse(dataSourceName) if err != nil { return nil, nil, xerrors.WithStackTrace(err) } - var ( - opts []config.Option - connectorOpts []ConnectorOption - ) opts = append(opts, info.Options...) if token := info.Params.Get("token"); token != "" { opts = append(opts, config.WithCredentials(credentials.NewAccessTokenCredentials(token))) diff --git a/sugar/certificates.go b/sugar/certificates.go index b530515f2..7f08854f7 100644 --- a/sugar/certificates.go +++ b/sugar/certificates.go @@ -23,7 +23,7 @@ func LoadCertificatesFromFile(caFile string) ([]*x509.Certificate, error) { func LoadCertificatesFromPem(bytes []byte) []*x509.Certificate { var ( cert *x509.Certificate - certs []*x509.Certificate + certs = make([]*x509.Certificate, 0) err error ) for len(bytes) > 0 { diff --git a/sugar/params_test.go b/sugar/params_test.go index deb839d86..1bc5a2672 100644 --- a/sugar/params_test.go +++ b/sugar/params_test.go @@ -18,7 +18,7 @@ import ( func TestGenerateDeclareSection(t *testing.T) { splitDeclares := func(declaresSection string) []string { - var declares []string + declares := make([]string, 0) for _, s := range strings.Split(declaresSection, ";") { s = strings.TrimSpace(s) if s != "" { @@ -119,7 +119,7 @@ func TestGenerateDeclareSection(t *testing.T) { func TestGenerateDeclareSection_ParameterOption(t *testing.T) { b := testutil.QueryBind(bind.AutoDeclare{}) getDeclares := func(declaresSection string) []string { - var declares []string + declares := make([]string, 0) for _, s := range strings.Split(declaresSection, "\n") { s = strings.TrimSpace(s) if s != "" && !strings.HasPrefix(s, "--") { @@ -227,7 +227,7 @@ func TestGenerateDeclareSection_ParameterOption(t *testing.T) { func TestGenerateDeclareSection_NamedArg(t *testing.T) { b := testutil.QueryBind(bind.AutoDeclare{}) getDeclares := func(declaresSection string) []string { - var declares []string + declares := make([]string, 0) for _, s := range strings.Split(declaresSection, "\n") { s = strings.TrimSpace(s) if s != "" && !strings.HasPrefix(s, "--") { diff --git a/tests/slo/database/sql/storage.go b/tests/slo/database/sql/storage.go index f9a6d17e2..02917e05e 100755 --- a/tests/slo/database/sql/storage.go +++ b/tests/slo/database/sql/storage.go @@ -80,12 +80,9 @@ func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (*Storage ctx, cancel := context.WithTimeout(ctx, time.Minute*5) defer cancel() - var ( - s *Storage - err error - ) + var err error - s = &Storage{ + s := &Storage{ cfg: cfg, createQuery: fmt.Sprintf(createTemplate, cfg.Table, cfg.PartitionSize, cfg.MinPartitionsCount, cfg.MaxPartitionsCount, cfg.MinPartitionsCount), From 1fac9de5546a7e261dedcf6bb38e35e0c8f37b58 Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Fri, 1 Mar 2024 23:49:54 +0300 Subject: [PATCH 09/10] fix linter after sync --- internal/allocator/allocator.go | 52 ++++++++-------- internal/query/client.go | 5 +- internal/query/result.go | 8 ++- internal/query/scanner_named_test.go | 3 +- internal/query/transaction.go | 5 +- internal/ratelimiter/client.go | 1 + query/do_options.go | 3 +- query/do_tx_options.go | 3 +- query/example_test.go | 89 ++++++++++++++-------------- query/execute_options.go | 8 +-- query/named.go | 3 +- sugar/params.go | 3 +- 12 files changed, 95 insertions(+), 88 deletions(-) diff --git a/internal/allocator/allocator.go b/internal/allocator/allocator.go index 378ec6f6c..9276235bf 100644 --- a/internal/allocator/allocator.go +++ b/internal/allocator/allocator.go @@ -925,10 +925,8 @@ type queryExecuteQueryRequestAllocator struct { allocations []*Ydb_Query.ExecuteQueryRequest } -func (a *queryExecuteQueryRequestAllocator) QueryExecuteQueryRequest() ( - v *Ydb_Query.ExecuteQueryRequest, -) { - v = queryExecuteQueryRequestPool.Get() +func (a *queryExecuteQueryRequestAllocator) QueryExecuteQueryRequest() *Ydb_Query.ExecuteQueryRequest { + v := queryExecuteQueryRequestPool.Get() a.allocations = append(a.allocations, v) return v @@ -946,10 +944,8 @@ type queryExecuteQueryResponsePartAllocator struct { allocations []*Ydb_Query.ExecuteQueryResponsePart } -func (a *queryExecuteQueryResponsePartAllocator) QueryExecuteQueryResponsePart() ( - v *Ydb_Query.ExecuteQueryResponsePart, -) { - v = queryExecuteQueryResponsePartPool.Get() +func (a *queryExecuteQueryResponsePartAllocator) QueryExecuteQueryResponsePart() *Ydb_Query.ExecuteQueryResponsePart { + v := queryExecuteQueryResponsePartPool.Get() a.allocations = append(a.allocations, v) return v @@ -967,10 +963,10 @@ type queryExecuteQueryRequestQueryContentAllocator struct { allocations []*Ydb_Query.ExecuteQueryRequest_QueryContent } -func (a *queryExecuteQueryRequestQueryContentAllocator) QueryExecuteQueryRequestQueryContent() ( - v *Ydb_Query.ExecuteQueryRequest_QueryContent, -) { - v = queryExecuteQueryRequestQueryContentPool.Get() +func ( + a *queryExecuteQueryRequestQueryContentAllocator, +) QueryExecuteQueryRequestQueryContent() *Ydb_Query.ExecuteQueryRequest_QueryContent { + v := queryExecuteQueryRequestQueryContentPool.Get() a.allocations = append(a.allocations, v) return v @@ -987,8 +983,8 @@ type queryTransactionControlAllocator struct { allocations []*Ydb_Query.TransactionControl } -func (a *queryTransactionControlAllocator) QueryTransactionControl() (v *Ydb_Query.TransactionControl) { - v = queryTransactionControlPool.Get() +func (a *queryTransactionControlAllocator) QueryTransactionControl() *Ydb_Query.TransactionControl { + v := queryTransactionControlPool.Get() a.allocations = append(a.allocations, v) return v @@ -1006,10 +1002,10 @@ type queryTransactionControlBeginTxAllocator struct { allocations []*Ydb_Query.TransactionControl_BeginTx } -func (a *queryTransactionControlBeginTxAllocator) QueryTransactionControlBeginTx() ( - v *Ydb_Query.TransactionControl_BeginTx, -) { - v = queryTransactionControlBeginTxPool.Get() +func ( + a *queryTransactionControlBeginTxAllocator, +) QueryTransactionControlBeginTx() *Ydb_Query.TransactionControl_BeginTx { + v := queryTransactionControlBeginTxPool.Get() a.allocations = append(a.allocations, v) return v @@ -1026,8 +1022,8 @@ type queryTransactionControlTxIDAllocator struct { allocations []*Ydb_Query.TransactionControl_TxId } -func (a *queryTransactionControlTxIDAllocator) QueryTransactionControlTxID() (v *Ydb_Query.TransactionControl_TxId) { - v = queryTransactionControlTxIDPool.Get() +func (a *queryTransactionControlTxIDAllocator) QueryTransactionControlTxID() *Ydb_Query.TransactionControl_TxId { + v := queryTransactionControlTxIDPool.Get() a.allocations = append(a.allocations, v) return v @@ -1044,8 +1040,8 @@ type queryTransactionSettingsAllocator struct { allocations []*Ydb_Query.TransactionSettings } -func (a *queryTransactionSettingsAllocator) QueryTransactionSettings() (v *Ydb_Query.TransactionSettings) { - v = queryTransactionSettingsPool.Get() +func (a *queryTransactionSettingsAllocator) QueryTransactionSettings() *Ydb_Query.TransactionSettings { + v := queryTransactionSettingsPool.Get() a.allocations = append(a.allocations, v) return v @@ -1063,10 +1059,10 @@ type queryTransactionSettingsSerializableReadWriteAllocator struct { allocations []*Ydb_Query.TransactionSettings_SerializableReadWrite } -func (a *queryTransactionSettingsSerializableReadWriteAllocator) QueryTransactionSettingsSerializableReadWrite() ( - v *Ydb_Query.TransactionSettings_SerializableReadWrite, -) { - v = queryTransactionSettingsSerializableReadWritePool.Get() +func ( + a *queryTransactionSettingsSerializableReadWriteAllocator, +) QueryTransactionSettingsSerializableReadWrite() *Ydb_Query.TransactionSettings_SerializableReadWrite { + v := queryTransactionSettingsSerializableReadWritePool.Get() a.allocations = append(a.allocations, v) return v @@ -1083,8 +1079,8 @@ type queryQueryContentAllocator struct { allocations []*Ydb_Query.QueryContent } -func (a *queryQueryContentAllocator) QueryQueryContent() (v *Ydb_Query.QueryContent) { - v = queryQueryContentPool.Get() +func (a *queryQueryContentAllocator) QueryQueryContent() *Ydb_Query.QueryContent { + v := queryQueryContentPool.Get() a.allocations = append(a.allocations, v) return v diff --git a/internal/query/client.go b/internal/query/client.go index da29fa186..8b9165f03 100644 --- a/internal/query/client.go +++ b/internal/query/client.go @@ -135,8 +135,9 @@ type createSessionSettings struct { func createSession( ctx context.Context, client Ydb_Query_V1.QueryServiceClient, settings createSessionSettings, -) (_ *Session, finalErr error) { +) (*Session, error) { var ( + finalErr error createSessionCtx context.Context cancelCreateSession context.CancelFunc ) @@ -233,7 +234,7 @@ func New(ctx context.Context, balancer balancer, config *config.Config) (*Client return &Client{ grpcClient: grpcClient, pool: newStubPool( - func(ctx context.Context) (_ *Session, err error) { + func(ctx context.Context) (*Session, error) { s, err := createSession(ctx, grpcClient, createSessionSettings{ createSessionTimeout: config.CreateSessionTimeout(), }) diff --git a/internal/query/result.go b/internal/query/result.go index 0af810e3d..d6077c612 100644 --- a/internal/query/result.go +++ b/internal/query/result.go @@ -31,8 +31,9 @@ func newResult( ctx context.Context, stream Ydb_Query_V1.QueryService_ExecuteQueryClient, stop func(), -) (_ *result, txID string, _ error) { +) (*result, string, error) { interrupted := make(chan struct{}) + var txID string r := result{ stream: stream, resultSetIndex: -1, @@ -85,7 +86,8 @@ func (r *result) Close(ctx context.Context) error { return nil } -func (r *result) nextResultSet(ctx context.Context) (_ *resultSet, err error) { +func (r *result) nextResultSet(ctx context.Context) (*resultSet, error) { + var err error defer func() { if err != nil && !xerrors.Is(err, io.EOF, errClosedResult, context.Canceled, @@ -108,7 +110,7 @@ func (r *result) nextResultSet(ctx context.Context) (_ *resultSet, err error) { if resultSetIndex := r.lastPart.GetResultSetIndex(); resultSetIndex >= nextResultSetIndex { //nolint:nestif r.resultSetIndex = resultSetIndex - return newResultSet(func() (_ *Ydb_Query.ExecuteQueryResponsePart, err error) { + return newResultSet(func() (*Ydb_Query.ExecuteQueryResponsePart, error) { defer func() { if err != nil && !xerrors.Is(err, io.EOF, context.Canceled, diff --git a/internal/query/scanner_named_test.go b/internal/query/scanner_named_test.go index 697401e18..cfbe3cf84 100644 --- a/internal/query/scanner_named_test.go +++ b/internal/query/scanner_named_test.go @@ -645,7 +645,8 @@ func TestScannerNamed(t *testing.T) { } { for i := range tt.dst { t.Run(tt.name+"→"+reflect.TypeOf(tt.dst[i][0]).Elem().String(), func(t *testing.T) { - err := tt.s.ScanNamed(func() (dst []query.NamedDestination) { + err := tt.s.ScanNamed(func() []query.NamedDestination { + dst := make([]query.NamedDestination, 0) for j := range tt.dst[i] { dst = append(dst, query.Named("a", tt.dst[i][j])) } diff --git a/internal/query/transaction.go b/internal/query/transaction.go index 5984ecaca..c19f9c923 100644 --- a/internal/query/transaction.go +++ b/internal/query/transaction.go @@ -34,6 +34,7 @@ func fromTxOptions(txID string, txOpts ...query.TxExecuteOption) executeSettings return query.ExecuteSettings(opts...) } +//nolint:nonamedreturns //potential error func (tx transaction) Execute(ctx context.Context, q string, opts ...query.TxExecuteOption) ( r query.Result, err error, ) { @@ -60,7 +61,7 @@ func commitTx(ctx context.Context, client Ydb_Query_V1.QueryServiceClient, sessi return nil } -func (tx transaction) CommitTx(ctx context.Context) (err error) { +func (tx transaction) CommitTx(ctx context.Context) error { return commitTx(ctx, tx.s.queryClient, tx.s.id, tx.id) } @@ -79,6 +80,6 @@ func rollback(ctx context.Context, client Ydb_Query_V1.QueryServiceClient, sessi return nil } -func (tx transaction) Rollback(ctx context.Context) (err error) { +func (tx transaction) Rollback(ctx context.Context) error { return rollback(ctx, tx.s.queryClient, tx.s.id, tx.id) } diff --git a/internal/ratelimiter/client.go b/internal/ratelimiter/client.go index 081b3c41e..fd93b683e 100644 --- a/internal/ratelimiter/client.go +++ b/internal/ratelimiter/client.go @@ -245,6 +245,7 @@ func (c *Client) listResource( return result.GetResourcePaths(), nil } +//nolint:nonamedreturns //potential error func (c *Client) DescribeResource( ctx context.Context, coordinationNodePath string, diff --git a/query/do_options.go b/query/do_options.go index ee6429dbd..155187983 100644 --- a/query/do_options.go +++ b/query/do_options.go @@ -14,7 +14,8 @@ func (idempotentOption) applyDoOption(opts *DoOptions) { opts.RetryOptions = append(opts.RetryOptions, retry.WithIdempotent(true)) } -func NewDoOptions(opts ...DoOption) (doOptions DoOptions) { +func NewDoOptions(opts ...DoOption) DoOptions { + doOptions := DoOptions{} for _, opt := range opts { opt.applyDoOption(&doOptions) } diff --git a/query/do_tx_options.go b/query/do_tx_options.go index f04fc3c0f..1d584b6fa 100644 --- a/query/do_tx_options.go +++ b/query/do_tx_options.go @@ -25,7 +25,8 @@ func WithTxSettings(txSettings TransactionSettings) doTxSettingsOption { return doTxSettingsOption{txSettings: txSettings} } -func NewDoTxOptions(opts ...DoTxOption) (doTxOptions DoTxOptions) { +func NewDoTxOptions(opts ...DoTxOption) DoTxOptions { + doTxOptions := DoTxOptions{} doTxOptions.TxSettings = TxSettings(WithDefaultTxMode()) for _, opt := range opts { opt.applyDoTxOption(&doTxOptions) diff --git a/query/example_test.go b/query/example_test.go index 8f926018f..736ab0fad 100644 --- a/query/example_test.go +++ b/query/example_test.go @@ -25,34 +25,35 @@ func Example_selectWithoutParameters() { ) // Do retry operation on errors with best effort err = db.Query().Do(ctx, // context manage exiting from Do - func(ctx context.Context, s query.Session) (err error) { // retry operation - _, res, err := s.Execute(ctx, + func(ctx context.Context, s query.Session) error { // retry operation + var errIn error + _, res, errIn := s.Execute(ctx, `SELECT 42 as id, "my string" as myStr`, ) - if err != nil { - return err // for auto-retry with driver + if errIn != nil { + return errIn // for auto-retry with driver } defer func() { _ = res.Close(ctx) }() // cleanup resources for { // iterate over result sets - rs, err := res.NextResultSet(ctx) - if err != nil { - if errors.Is(err, io.EOF) { + rs, errIn := res.NextResultSet(ctx) + if errIn != nil { + if errors.Is(errIn, io.EOF) { break } - return err + return errIn } for { // iterate over rows - row, err := rs.NextRow(ctx) - if err != nil { - if errors.Is(err, io.EOF) { + row, errIn := rs.NextRow(ctx) + if errIn != nil { + if errors.Is(errIn, io.EOF) { break } - return err + return errIn } - if err = row.Scan(&id, &myStr); err != nil { - return err // generally scan error not retryable, return it for driver check error + if errIn = row.Scan(&id, &myStr); err != nil { + return errIn // generally scan error not retryable, return it for driver check error } } } @@ -82,8 +83,8 @@ func Example_selectWithParameters() { ) // Do retry operation on errors with best effort err = db.Query().Do(ctx, // context manage exiting from Do - func(ctx context.Context, s query.Session) (err error) { // retry operation - _, res, err := s.Execute(ctx, + func(ctx context.Context, s query.Session) error { // retry operation + _, res, errIn := s.Execute(ctx, `SELECT CAST($id AS Uint64) AS id, CAST($myStr AS Text) AS myStr`, query.WithParameters( ydb.ParamsBuilder(). @@ -92,33 +93,33 @@ func Example_selectWithParameters() { Build(), ), ) - if err != nil { - return err // for auto-retry with driver + if errIn != nil { + return errIn // for auto-retry with driver } defer func() { _ = res.Close(ctx) }() // cleanup resources for { // iterate over result sets - rs, err := res.NextResultSet(ctx) - if err != nil { - if errors.Is(err, io.EOF) { + rs, errIn := res.NextResultSet(ctx) + if errIn != nil { + if errors.Is(errIn, io.EOF) { break } - return err + return errIn } for { // iterate over rows - row, err := rs.NextRow(ctx) - if err != nil { - if errors.Is(err, io.EOF) { + row, errIn := rs.NextRow(ctx) + if errIn != nil { + if errors.Is(errIn, io.EOF) { break } - return err + return errIn } - if err = row.ScanNamed( + if errIn = row.ScanNamed( query.Named("id", &id), query.Named("myStr", &myStr), - ); err != nil { - return err // generally scan error not retryable, return it for driver check error + ); errIn != nil { + return errIn // generally scan error not retryable, return it for driver check error } } } @@ -148,37 +149,37 @@ func Example_txSelect() { ) // Do retry operation on errors with best effort err = db.Query().DoTx(ctx, // context manage exiting from Do - func(ctx context.Context, tx query.TxActor) (err error) { // retry operation - res, err := tx.Execute(ctx, + func(ctx context.Context, tx query.TxActor) error { // retry operation + res, errIn := tx.Execute(ctx, `SELECT 42 as id, "my string" as myStr`, ) - if err != nil { - return err // for auto-retry with driver + if errIn != nil { + return errIn // for auto-retry with driver } defer func() { _ = res.Close(ctx) }() // cleanup resources for { // iterate over result sets - rs, err := res.NextResultSet(ctx) - if err != nil { - if errors.Is(err, io.EOF) { + rs, errIn := res.NextResultSet(ctx) + if errIn != nil { + if errors.Is(errIn, io.EOF) { break } - return err + return errIn } for { // iterate over rows - row, err := rs.NextRow(ctx) - if err != nil { - if errors.Is(err, io.EOF) { + row, errIn := rs.NextRow(ctx) + if errIn != nil { + if errors.Is(errIn, io.EOF) { break } - return err + return errIn } - if err = row.ScanNamed( + if errIn = row.ScanNamed( query.Named("id", &id), query.Named("myStr", &myStr), - ); err != nil { - return err // generally scan error not retryable, return it for driver check error + ); errIn != nil { + return errIn // generally scan error not retryable, return it for driver check error } } } diff --git a/query/execute_options.go b/query/execute_options.go index 091bd67de..ee809a51e 100644 --- a/query/execute_options.go +++ b/query/execute_options.go @@ -103,8 +103,8 @@ func defaultCommonExecuteSettings() commonExecuteSettings { } } -func ExecuteSettings(opts ...ExecuteOption) (settings *executeSettings) { - settings = &executeSettings{ +func ExecuteSettings(opts ...ExecuteOption) *executeSettings { + settings := &executeSettings{ commonExecuteSettings: defaultCommonExecuteSettings(), } settings.commonExecuteSettings = defaultCommonExecuteSettings() @@ -144,8 +144,8 @@ func (s *commonExecuteSettings) Params() *params.Parameters { return &s.params } -func TxExecuteSettings(opts ...TxExecuteOption) (settings *txExecuteSettings) { - settings = &txExecuteSettings{ +func TxExecuteSettings(opts ...TxExecuteOption) *txExecuteSettings { + settings := &txExecuteSettings{ commonExecuteSettings: defaultCommonExecuteSettings(), } for _, opt := range opts { diff --git a/query/named.go b/query/named.go index e25a3ef3a..c67f1613d 100644 --- a/query/named.go +++ b/query/named.go @@ -18,7 +18,8 @@ func (dst namedDestination) Destination() interface{} { return dst.ref } -func Named(columnName string, destinationValueReference interface{}) (dst namedDestination) { +func Named(columnName string, destinationValueReference interface{}) namedDestination { + dst := namedDestination{} if columnName == "" { panic("columnName must be not empty") } diff --git a/sugar/params.go b/sugar/params.go index 612268260..bcef9924b 100644 --- a/sugar/params.go +++ b/sugar/params.go @@ -83,7 +83,8 @@ func parameterOptionsToDeclares(v []table.ParameterOption) string { } func namedArgsToDeclares(v []sql.NamedArg) (string, error) { - vv, err := bind.Params(func() (newArgs []interface{}) { + vv, err := bind.Params(func() []interface{} { + newArgs := make([]interface{}, 0) for i := range v { newArgs = append(newArgs, v[i]) } From ab2def61946b2ac3b6802dfd826063ee947b32e0 Mon Sep 17 00:00:00 2001 From: Dmitry Khrapov Date: Mon, 4 Mar 2024 21:55:03 +0300 Subject: [PATCH 10/10] fix test's errors --- examples/basic/native/query/series.go | 56 ++++++++++++++------------- internal/balancer/balancer.go | 8 ++-- internal/query/client.go | 4 +- internal/query/result.go | 6 +-- internal/value/type.go | 32 +++++++-------- tests/slo/native/query/main.go | 15 +++---- tests/slo/native/query/storage.go | 14 ++++--- 7 files changed, 70 insertions(+), 65 deletions(-) diff --git a/examples/basic/native/query/series.go b/examples/basic/native/query/series.go index 625c5967e..1cf07d036 100644 --- a/examples/basic/native/query/series.go +++ b/examples/basic/native/query/series.go @@ -70,18 +70,19 @@ SELECT FROM AS_TABLE($episodesData); `)) -func readTable(ctx context.Context, c table.Client, path string) (err error) { +func readTable(ctx context.Context, c table.Client, path string) error { var res result.StreamResult - err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - res, err = s.StreamReadTable(ctx, path, + err := c.Do(ctx, + func(ctx context.Context, s table.Session) error { + var errIn error + res, errIn = s.StreamReadTable(ctx, path, options.ReadOrdered(), options.ReadColumn("series_id"), options.ReadColumn("title"), options.ReadColumn("release_date"), ) - return + return errIn }, ) if err != nil { @@ -138,13 +139,14 @@ func readTable(ctx context.Context, c table.Client, path string) (err error) { return res.Err() } -func describeTableOptions(ctx context.Context, c table.Client) (err error) { +func describeTableOptions(ctx context.Context, c table.Client) error { var desc options.TableOptionsDescription - err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - desc, err = s.DescribeTableOptions(ctx) + err := c.Do(ctx, + func(ctx context.Context, s table.Session) error { + var errIn error + desc, errIn = s.DescribeTableOptions(ctx) - return + return errIn }, ) if err != nil { @@ -191,7 +193,7 @@ func describeTableOptions(ctx context.Context, c table.Client) (err error) { return nil } -func selectSimple(ctx context.Context, c table.Client, prefix string) (err error) { +func selectSimple(ctx context.Context, c table.Client, prefix string) error { query := render( template.Must(template.New("").Parse(` PRAGMA TablePathPrefix("{{ .TablePathPrefix }}"); @@ -221,16 +223,17 @@ func selectSimple(ctx context.Context, c table.Client, prefix string) (err error table.CommitTx(), ) var res result.Result - err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, res, err = s.Execute(ctx, readTx, query, + err := c.Do(ctx, + func(ctx context.Context, s table.Session) error { + var errIn error + _, res, errIn = s.Execute(ctx, readTx, query, table.NewQueryParameters( table.ValueParam("$seriesID", types.Uint64Value(1)), ), options.WithCollectStatsModeBasic(), ) - return + return errIn }, ) if err != nil { @@ -266,7 +269,7 @@ func selectSimple(ctx context.Context, c table.Client, prefix string) (err error return res.Err() } -func scanQuerySelect(ctx context.Context, c table.Client, prefix string) (err error) { +func scanQuerySelect(ctx context.Context, c table.Client, prefix string) error { query := render( template.Must(template.New("").Parse(` PRAGMA TablePathPrefix("{{ .TablePathPrefix }}"); @@ -327,16 +330,17 @@ func scanQuerySelect(ctx context.Context, c table.Client, prefix string) (err er ) } -func fillTablesWithData(ctx context.Context, c table.Client, prefix string) (err error) { +func fillTablesWithData(ctx context.Context, c table.Client, prefix string) error { writeTx := table.TxControl( table.BeginTx( table.WithSerializableReadWrite(), ), table.CommitTx(), ) - err = c.Do(ctx, - func(ctx context.Context, s table.Session) (err error) { - _, _, err = s.Execute(ctx, writeTx, render(fill, templateConfig{ + err := c.Do(ctx, + func(ctx context.Context, s table.Session) error { + var errIn error + _, _, errIn = s.Execute(ctx, writeTx, render(fill, templateConfig{ TablePathPrefix: prefix, }), table.NewQueryParameters( table.ValueParam("$seriesData", getSeriesData()), @@ -344,15 +348,15 @@ func fillTablesWithData(ctx context.Context, c table.Client, prefix string) (err table.ValueParam("$episodesData", getEpisodesData()), )) - return err + return errIn }, ) return err } -func createTables(ctx context.Context, c table.Client, prefix string) (err error) { - err = c.Do(ctx, +func createTables(ctx context.Context, c table.Client, prefix string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { return s.CreateTable(ctx, path.Join(prefix, "series"), options.WithColumn("series_id", types.Optional(types.TypeUint64)), @@ -403,8 +407,8 @@ func createTables(ctx context.Context, c table.Client, prefix string) (err error return nil } -func describeTable(ctx context.Context, c table.Client, path string) (err error) { - err = c.Do(ctx, +func describeTable(ctx context.Context, c table.Client, path string) error { + err := c.Do(ctx, func(ctx context.Context, s table.Session) error { desc, err := s.DescribeTable(ctx, path) if err != nil { @@ -419,7 +423,7 @@ func describeTable(ctx context.Context, c table.Client, path string) (err error) }, ) - return + return err } func render(t *template.Template, data interface{}) string { diff --git a/internal/balancer/balancer.go b/internal/balancer/balancer.go index ab7cccf9e..fbe0d2261 100644 --- a/internal/balancer/balancer.go +++ b/internal/balancer/balancer.go @@ -309,16 +309,14 @@ func (b *Balancer) Invoke( }) } +//nolint:nonamedreturns //FAIL integration tests func (b *Balancer) NewStream( ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption, -) (grpc.ClientStream, error) { - var ( - client grpc.ClientStream - err error - ) +) (_ grpc.ClientStream, err error) { + var client grpc.ClientStream err = b.wrapCall(ctx, func(ctx context.Context, cc conn.Conn) error { client, err = cc.NewStream(ctx, desc, method, opts...) diff --git a/internal/query/client.go b/internal/query/client.go index 8b9165f03..d4d4ad80d 100644 --- a/internal/query/client.go +++ b/internal/query/client.go @@ -133,11 +133,11 @@ type createSessionSettings struct { onAttach func(id string) } +//nolint:nonamedreturns //FAIL TestCreateSession func createSession( ctx context.Context, client Ydb_Query_V1.QueryServiceClient, settings createSessionSettings, -) (*Session, error) { +) (_ *Session, finalErr error) { var ( - finalErr error createSessionCtx context.Context cancelCreateSession context.CancelFunc ) diff --git a/internal/query/result.go b/internal/query/result.go index d6077c612..33ab11407 100644 --- a/internal/query/result.go +++ b/internal/query/result.go @@ -86,8 +86,8 @@ func (r *result) Close(ctx context.Context) error { return nil } -func (r *result) nextResultSet(ctx context.Context) (*resultSet, error) { - var err error +//nolint:nonamedreturns //FAIL TestExecute and TestResultNextResultSet +func (r *result) nextResultSet(ctx context.Context) (_ *resultSet, err error) { defer func() { if err != nil && !xerrors.Is(err, io.EOF, errClosedResult, context.Canceled, @@ -110,7 +110,7 @@ func (r *result) nextResultSet(ctx context.Context) (*resultSet, error) { if resultSetIndex := r.lastPart.GetResultSetIndex(); resultSetIndex >= nextResultSetIndex { //nolint:nestif r.resultSetIndex = resultSetIndex - return newResultSet(func() (*Ydb_Query.ExecuteQueryResponsePart, error) { + return newResultSet(func() (_ *Ydb_Query.ExecuteQueryResponsePart, err error) { defer func() { if err != nil && !xerrors.Is(err, io.EOF, context.Canceled, diff --git a/internal/value/type.go b/internal/value/type.go index 351e6cd42..4924adf3e 100644 --- a/internal/value/type.go +++ b/internal/value/type.go @@ -22,33 +22,33 @@ func TypeToYDB(t Type, a *allocator.Allocator) *Ydb.Type { } func TypeFromYDB(x *Ydb.Type) Type { - switch v := x.Type.(type) { + switch v := x.Type.(type) { //nolint:protogetter //because need to use interface cast case *Ydb.Type_TypeId: return primitiveTypeFromYDB(v.TypeId) case *Ydb.Type_OptionalType: - return Optional(TypeFromYDB(v.OptionalType.Item)) + return Optional(TypeFromYDB(v.OptionalType.GetItem())) case *Ydb.Type_ListType: - return List(TypeFromYDB(v.ListType.Item)) + return List(TypeFromYDB(v.ListType.GetItem())) case *Ydb.Type_DecimalType: d := v.DecimalType - return Decimal(d.Precision, d.Scale) + return Decimal(d.GetPrecision(), d.GetScale()) case *Ydb.Type_TupleType: t := v.TupleType - return Tuple(TypesFromYDB(t.Elements)...) + return Tuple(TypesFromYDB(t.GetElements())...) case *Ydb.Type_StructType: s := v.StructType - return Struct(StructFields(s.Members)...) + return Struct(StructFields(s.GetMembers())...) case *Ydb.Type_DictType: - keyType, valueType := TypeFromYDB(v.DictType.Key), TypeFromYDB(v.DictType.Payload) + keyType, valueType := TypeFromYDB(v.DictType.GetKey()), TypeFromYDB(v.DictType.GetPayload()) if valueType.equalsTo(Void()) { return Set(keyType) } @@ -57,11 +57,11 @@ func TypeFromYDB(x *Ydb.Type) Type { case *Ydb.Type_VariantType: t := v.VariantType - switch x := t.Type.(type) { + switch x := t.Type.(type) { //nolint:protogetter //because need to use interface cast case *Ydb.VariantType_TupleItems: - return VariantTuple(TypesFromYDB(x.TupleItems.Elements)...) + return VariantTuple(TypesFromYDB(x.TupleItems.GetElements())...) case *Ydb.VariantType_StructItems: - return VariantStruct(StructFields(x.StructItems.Members)...) + return VariantStruct(StructFields(x.StructItems.GetMembers())...) default: panic("ydb: unknown variant type") } @@ -613,7 +613,7 @@ func (v *StructType) toYDB(a *allocator.Allocator) *Ydb.Type { structMember.Name = v.fields[i].Name structMember.Type = v.fields[i].T.toYDB(a) typeStruct.StructType.Members = append( - typeStruct.StructType.Members, + typeStruct.StructType.GetMembers(), structMember, ) } @@ -633,8 +633,8 @@ func StructFields(ms []*Ydb.StructMember) []StructField { fs := make([]StructField, len(ms)) for i, m := range ms { fs[i] = StructField{ - Name: m.Name, - T: TypeFromYDB(m.Type), + Name: m.GetName(), + T: TypeFromYDB(m.GetType()), } } @@ -693,7 +693,7 @@ func (v *TupleType) toYDB(a *allocator.Allocator) *Ydb.Type { typeTuple.TupleType = a.Tuple() for _, vv := range items { - typeTuple.TupleType.Elements = append(typeTuple.TupleType.Elements, vv.toYDB(a)) + typeTuple.TupleType.Elements = append(typeTuple.TupleType.GetElements(), vv.toYDB(a)) } t.Type = typeTuple @@ -747,7 +747,7 @@ func (v *variantStructType) toYDB(a *allocator.Allocator) *Ydb.Type { typeVariant.VariantType = a.Variant() structItems := a.VariantStructItems() - structItems.StructItems = v.StructType.toYDB(a).Type.(*Ydb.Type_StructType).StructType + structItems.StructItems = v.StructType.toYDB(a).GetType().(*Ydb.Type_StructType).StructType typeVariant.VariantType.Type = structItems @@ -800,7 +800,7 @@ func (v *variantTupleType) toYDB(a *allocator.Allocator) *Ydb.Type { typeVariant.VariantType = a.Variant() tupleItems := a.VariantTupleItems() - tupleItems.TupleItems = v.TupleType.toYDB(a).Type.(*Ydb.Type_TupleType).TupleType + tupleItems.TupleItems = v.TupleType.toYDB(a).GetType().(*Ydb.Type_TupleType).TupleType typeVariant.VariantType.Type = tupleItems diff --git a/tests/slo/native/query/main.go b/tests/slo/native/query/main.go index 9d5df4e72..0fd812442 100644 --- a/tests/slo/native/query/main.go +++ b/tests/slo/native/query/main.go @@ -63,15 +63,16 @@ func main() { g := errgroup.Group{} for i := uint64(0); i < cfg.InitialDataCount; i++ { - g.Go(func() (err error) { - e, err := gen.Generate() - if err != nil { - return err + g.Go(func() error { + var errIn error + e, errIn := gen.Generate() + if errIn != nil { + return errIn } - _, err = s.Write(ctx, e) - if err != nil { - return err + _, errIn = s.Write(ctx, e) + if errIn != nil { + return errIn } return nil diff --git a/tests/slo/native/query/storage.go b/tests/slo/native/query/storage.go index f784543c9..1bde6630d 100755 --- a/tests/slo/native/query/storage.go +++ b/tests/slo/native/query/storage.go @@ -87,8 +87,9 @@ func NewStorage(ctx context.Context, cfg *config.Config, poolSize int) (*Storage return s, nil } -func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (_ generator.Row, attempts int, err error) { - if err = ctx.Err(); err != nil { +func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (generator.Row, int, error) { + var attempts int + if err := ctx.Err(); err != nil { return generator.Row{}, attempts, err } @@ -97,9 +98,9 @@ func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (_ generato e := generator.Row{} - err = s.db.Query().Do(ctx, - func(ctx context.Context, session query.Session) (err error) { - if err = ctx.Err(); err != nil { + err := s.db.Query().Do(ctx, + func(ctx context.Context, session query.Session) error { + if err := ctx.Err(); err != nil { return err } @@ -155,7 +156,8 @@ func (s *Storage) Read(ctx context.Context, entryID generator.RowID) (_ generato return e, attempts, err } -func (s *Storage) Write(ctx context.Context, e generator.Row) (attempts int, _ error) { +func (s *Storage) Write(ctx context.Context, e generator.Row) (int, error) { + var attempts int if err := ctx.Err(); err != nil { return attempts, err }