From a18af8a28ca2781050b33683bcd7f926cac2a939 Mon Sep 17 00:00:00 2001 From: Oleg Jukovec Date: Tue, 27 Jun 2023 12:37:40 +0300 Subject: [PATCH] ci: enable more linters - forbidigo - gocritic - lll - reassign - stylecheck - unconvert --- .github/workflows/check.yaml | 13 +- .golangci.yaml | 30 ++ CHANGELOG.md | 1 + Makefile | 2 +- box_error_test.go | 18 +- connection.go | 31 +- connector.go | 52 ++-- crud/error.go | 8 +- crud/request_test.go | 221 ++++++++------ crud/result.go | 1 - crud/tarantool_test.go | 11 +- crud/unflatten_rows.go | 4 +- crud/upsert_many.go | 3 +- datetime/datetime.go | 35 +-- datetime/datetime_test.go | 3 +- datetime/interval.go | 2 +- decimal/bcd.go | 20 +- decimal/decimal.go | 25 +- decimal/decimal_test.go | 72 +++-- example_test.go | 10 +- export_test.go | 3 +- future.go | 3 +- pool/connection_pool.go | 551 ++++++++++++++++++---------------- pool/connection_pool_test.go | 52 ++-- pool/connector_test.go | 88 +++--- queue/example_msgpack_test.go | 20 +- queue/queue_test.go | 160 +++++----- request.go | 68 +++-- request_test.go | 3 +- response.go | 6 +- schema.go | 33 +- settings/request.go | 3 +- settings/request_test.go | 12 +- settings/tarantool_test.go | 18 +- shutdown_test.go | 3 +- smallbuf.go | 2 +- ssl_test.go | 8 +- stream.go | 9 +- tarantool_test.go | 100 +++--- test_helpers/main.go | 8 +- test_helpers/pool_helper.go | 28 +- uuid/uuid.go | 11 +- uuid/uuid_test.go | 3 +- 43 files changed, 991 insertions(+), 763 deletions(-) create mode 100644 .golangci.yaml diff --git a/.github/workflows/check.yaml b/.github/workflows/check.yaml index 2297b0b3c..88b6afa43 100644 --- a/.github/workflows/check.yaml +++ b/.github/workflows/check.yaml @@ -40,24 +40,15 @@ jobs: uses: golangci/golangci-lint-action@v3 continue-on-error: true with: - # The suppression of the rule `errcheck` may be removed after adding - # errors check in all methods calling EncodeXxx inside. - # For now those methods are not even able to return any error - # cause of internal implementation of writer interface (see smallbuf.go). - # - # The `//nolint` workaround was not the acceptable way of warnings suppression, - # cause those comments get rendered in documentation by godoc. - # See https://github.com/tarantool/go-tarantool/pull/160#discussion_r858608221 - # # The first run is for GitHub Actions error format. - args: -E goimports -D errcheck + args: --config=.golangci.yaml - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: # The second run is for human-readable error format with a file name # and a line number. - args: --out-${NO_FUTURE}format colored-line-number -E goimports -D errcheck + args: --out-${NO_FUTURE}format colored-line-number --config=.golangci.yaml codespell: runs-on: ubuntu-latest diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 000000000..32f87cb0d --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,30 @@ +run: + timeout: 3m + +linters: + disable: + - errcheck + enable: + - forbidigo + - gocritic + - goimports + - lll + - reassign + - stylecheck + - unconvert + +linters-settings: + gocritic: + disabled-checks: + - ifElseChain + lll: + line-length: 100 + tab-width: 4 + stylecheck: + checks: ["all", "-ST1003"] + +issues: + exclude-rules: + - linters: + - lll + source: "\t?// *(see )?https://" diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fcd90d53..c3705194d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Versioning](http://semver.org/spec/v2.0.0.html) except to the first release. - Type() method to the Request interface (#158) - Enumeration types for RLimitAction/iterators (#158) - IsNullable flag for Field (#302) +- More linters on CI (#310) ### Changed diff --git a/Makefile b/Makefile index f48b789cc..4f676a530 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ format: .PHONY: golangci-lint golangci-lint: - golangci-lint run -E goimports -D errcheck + golangci-lint run --config=.golangci.yaml .PHONY: test test: diff --git a/box_error_test.go b/box_error_test.go index d8ff5b11f..0d7d3f47b 100644 --- a/box_error_test.go +++ b/box_error_test.go @@ -129,12 +129,14 @@ var mpDecodeSamples = map[string]struct { "InnerMapInvalidErrorType": { []byte{0x81, 0x00, 0x91, 0x81, 0x00, 0xc1}, false, - regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1 decoding (?:string\/bytes|bytes) length`), + regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1` + + ` decoding (?:string\/bytes|bytes) length`), }, "InnerMapInvalidErrorFile": { []byte{0x81, 0x00, 0x91, 0x81, 0x01, 0xc1}, false, - regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1 decoding (?:string\/bytes|bytes) length`), + regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1` + + ` decoding (?:string\/bytes|bytes) length`), }, "InnerMapInvalidErrorLine": { []byte{0x81, 0x00, 0x91, 0x81, 0x02, 0xc1}, @@ -144,7 +146,8 @@ var mpDecodeSamples = map[string]struct { "InnerMapInvalidErrorMessage": { []byte{0x81, 0x00, 0x91, 0x81, 0x03, 0xc1}, false, - regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1 decoding (?:string\/bytes|bytes) length`), + regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1 decoding` + + ` (?:string\/bytes|bytes) length`), }, "InnerMapInvalidErrorErrno": { []byte{0x81, 0x00, 0x91, 0x81, 0x04, 0xc1}, @@ -164,7 +167,8 @@ var mpDecodeSamples = map[string]struct { "InnerMapInvalidErrorFieldsKey": { []byte{0x81, 0x00, 0x91, 0x81, 0x06, 0x81, 0xc1}, false, - regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1 decoding (?:string\/bytes|bytes) length`), + regexp.MustCompile(`msgpack: (?:unexpected|invalid|unknown) code.c1` + + ` decoding (?:string\/bytes|bytes) length`), }, "InnerMapInvalidErrorFieldsValue": { []byte{0x81, 0x00, 0x91, 0x81, 0x06, 0x81, 0xa3, 0x6b, 0x65, 0x79, 0xc1}, @@ -435,7 +439,8 @@ func TestErrorTypeSelect(t *testing.T) { var resp *Response var offset uint32 = 0 var limit uint32 = 1 - resp, err = conn.Select(space, index, offset, limit, IterEq, []interface{}{testcase.tuple.pk}) + resp, err = conn.Select(space, index, offset, limit, IterEq, + []interface{}{testcase.tuple.pk}) require.Nil(t, err) require.NotNil(t, resp.Data) require.Equalf(t, len(resp.Data), 1, "Exactly one tuple had been found") @@ -479,7 +484,8 @@ func TestErrorTypeSelectTyped(t *testing.T) { var offset uint32 = 0 var limit uint32 = 1 var resp []TupleBoxError - err = conn.SelectTyped(space, index, offset, limit, IterEq, []interface{}{testcase.tuple.pk}, &resp) + err = conn.SelectTyped(space, index, offset, limit, IterEq, + []interface{}{testcase.tuple.pk}, &resp) require.Nil(t, err) require.NotNil(t, resp) require.Equalf(t, len(resp), 1, "Exactly one tuple had been found") diff --git a/connection.go b/connection.go index ea7f236fe..367cf9640 100644 --- a/connection.go +++ b/connection.go @@ -33,6 +33,11 @@ const shutdownEventKey = "box.shutdown" type ConnEventKind int type ConnLogKind int +var ( + errUnknownRequest = errors.New("the passed connected request doesn't belong " + + "to the current connection or connection pool") +) + const ( // Connected signals that connection is established or reestablished. Connected ConnEventKind = iota + 1 @@ -84,13 +89,16 @@ func (d defaultLogger) Report(event ConnLogKind, conn *Connection, v ...interfac case LogReconnectFailed: reconnects := v[0].(uint) err := v[1].(error) - log.Printf("tarantool: reconnect (%d/%d) to %s failed: %s", reconnects, conn.opts.MaxReconnects, conn.addr, err) + log.Printf("tarantool: reconnect (%d/%d) to %s failed: %s", + reconnects, conn.opts.MaxReconnects, conn.addr, err) case LogLastReconnectFailed: err := v[0].(error) - log.Printf("tarantool: last reconnect to %s failed: %s, giving it up", conn.addr, err) + log.Printf("tarantool: last reconnect to %s failed: %s, giving it up", + conn.addr, err) case LogUnexpectedResultId: resp := v[0].(*Response) - log.Printf("tarantool: connection %s got unexpected resultId (%d) in response", conn.addr, resp.RequestId) + log.Printf("tarantool: connection %s got unexpected resultId (%d) in response", + conn.addr, resp.RequestId) case LogWatchEventReadFailed: err := v[0].(error) log.Printf("tarantool: unable to parse watch event: %s", err) @@ -145,7 +153,8 @@ func (d defaultLogger) Report(event ConnLogKind, conn *Connection, v ...interfac // by timeout). Client reconnect will happen if connection options enable // reconnect. Beware that graceful shutdown event initialization is asynchronous. // -// More on graceful shutdown: https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/ +// More on graceful shutdown: +// https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/ type Connection struct { addr string c Conn @@ -579,7 +588,8 @@ func (conn *Connection) dial() (err error) { go conn.reader(c, c) // Subscribe shutdown event to process graceful shutdown. - if conn.shutdownWatcher == nil && isFeatureInSlice(WatchersFeature, conn.serverProtocolInfo.Features) { + if conn.shutdownWatcher == nil && + isFeatureInSlice(WatchersFeature, conn.serverProtocolInfo.Features) { watcher, werr := conn.newWatcherImpl(shutdownEventKey, shutdownEventCallback) if werr != nil { return werr @@ -696,7 +706,10 @@ func (conn *Connection) closeConnection(neterr error, forever bool) (err error) } for i := range conn.shard { conn.shard[i].buf.Reset() - requestsLists := []*[requestsMap]futureList{&conn.shard[i].requests, &conn.shard[i].requestsWithCtx} + requestsLists := []*[requestsMap]futureList{ + &conn.shard[i].requests, + &conn.shard[i].requestsWithCtx, + } for _, requests := range requestsLists { for pos := range requests { requests[pos].clear(neterr, conn) @@ -1207,7 +1220,7 @@ func read(r io.Reader, lenbuf []byte) (response []byte, err error) { return } if lenbuf[0] != 0xce { - err = errors.New("Wrong response header") + err = errors.New("wrong response header") return } length = (int(lenbuf[1]) << 24) + @@ -1216,7 +1229,7 @@ func read(r io.Reader, lenbuf []byte) (response []byte, err error) { int(lenbuf[4]) if length == 0 { - err = errors.New("Response should not be 0 length") + err = errors.New("response should not be 0 length") return } response = make([]byte, length) @@ -1241,7 +1254,7 @@ func (conn *Connection) Do(req Request) *Future { if connectedReq, ok := req.(ConnectedRequest); ok { if connectedReq.Conn() != conn { fut := NewFuture() - fut.SetError(fmt.Errorf("the passed connected request doesn't belong to the current connection or connection pool")) + fut.SetError(errUnknownRequest) return fut } } diff --git a/connector.go b/connector.go index 016dbbfb3..5d4b5be39 100644 --- a/connector.go +++ b/connector.go @@ -13,78 +13,82 @@ type Connector interface { // Deprecated: the method will be removed in the next major version, // use a PingRequest object + Do() instead. - Ping() (resp *Response, err error) + Ping() (*Response, error) // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. - Select(space, index interface{}, offset, limit uint32, iterator Iter, key interface{}) (resp *Response, err error) + Select(space, index interface{}, offset, limit uint32, iterator Iter, + key interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. - Insert(space interface{}, tuple interface{}) (resp *Response, err error) + Insert(space interface{}, tuple interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a ReplicaRequest object + Do() instead. - Replace(space interface{}, tuple interface{}) (resp *Response, err error) + Replace(space interface{}, tuple interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a DeleteRequest object + Do() instead. - Delete(space, index interface{}, key interface{}) (resp *Response, err error) + Delete(space, index interface{}, key interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a UpdateRequest object + Do() instead. - Update(space, index interface{}, key, ops interface{}) (resp *Response, err error) + Update(space, index interface{}, key, ops interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a UpsertRequest object + Do() instead. - Upsert(space interface{}, tuple, ops interface{}) (resp *Response, err error) + Upsert(space interface{}, tuple, ops interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a CallRequest object + Do() instead. - Call(functionName string, args interface{}) (resp *Response, err error) + Call(functionName string, args interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a Call16Request object + Do() instead. - Call16(functionName string, args interface{}) (resp *Response, err error) + Call16(functionName string, args interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a Call17Request object + Do() instead. - Call17(functionName string, args interface{}) (resp *Response, err error) + Call17(functionName string, args interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use an EvalRequest object + Do() instead. - Eval(expr string, args interface{}) (resp *Response, err error) + Eval(expr string, args interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use an ExecuteRequest object + Do() instead. - Execute(expr string, args interface{}) (resp *Response, err error) + Execute(expr string, args interface{}) (*Response, error) // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. - GetTyped(space, index interface{}, key interface{}, result interface{}) (err error) + GetTyped(space, index interface{}, key interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. - SelectTyped(space, index interface{}, offset, limit uint32, iterator Iter, key interface{}, result interface{}) (err error) + SelectTyped(space, index interface{}, offset, limit uint32, iterator Iter, key interface{}, + result interface{}) error // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. - InsertTyped(space interface{}, tuple interface{}, result interface{}) (err error) + InsertTyped(space interface{}, tuple interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use a ReplaceRequest object + Do() instead. - ReplaceTyped(space interface{}, tuple interface{}, result interface{}) (err error) + ReplaceTyped(space interface{}, tuple interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use a DeleteRequest object + Do() instead. - DeleteTyped(space, index interface{}, key interface{}, result interface{}) (err error) + DeleteTyped(space, index interface{}, key interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use a UpdateRequest object + Do() instead. - UpdateTyped(space, index interface{}, key, ops interface{}, result interface{}) (err error) + UpdateTyped(space, index interface{}, key, ops interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use a CallRequest object + Do() instead. - CallTyped(functionName string, args interface{}, result interface{}) (err error) + CallTyped(functionName string, args interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use a Call16Request object + Do() instead. - Call16Typed(functionName string, args interface{}, result interface{}) (err error) + Call16Typed(functionName string, args interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use a Call17Request object + Do() instead. - Call17Typed(functionName string, args interface{}, result interface{}) (err error) + Call17Typed(functionName string, args interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use an EvalRequest object + Do() instead. - EvalTyped(expr string, args interface{}, result interface{}) (err error) + EvalTyped(expr string, args interface{}, result interface{}) error // Deprecated: the method will be removed in the next major version, // use an ExecuteRequest object + Do() instead. - ExecuteTyped(expr string, args interface{}, result interface{}) (SQLInfo, []ColumnMetaData, error) + ExecuteTyped(expr string, args interface{}, + result interface{}) (SQLInfo, []ColumnMetaData, error) // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. - SelectAsync(space, index interface{}, offset, limit uint32, iterator Iter, key interface{}) *Future + SelectAsync(space, index interface{}, offset, limit uint32, iterator Iter, + key interface{}) *Future // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. InsertAsync(space interface{}, tuple interface{}) *Future diff --git a/crud/error.go b/crud/error.go index d7c36a333..b0b267fbe 100644 --- a/crud/error.go +++ b/crud/error.go @@ -70,8 +70,8 @@ func (e *Error) DecodeMsgpack(d *msgpack.Decoder) error { } // Error converts an Error to a string. -func (err Error) Error() string { - return err.Str +func (e Error) Error() string { + return e.Str } // ErrorMany describes CRUD error object for `_many` methods. @@ -104,9 +104,9 @@ func (e *ErrorMany) DecodeMsgpack(d *msgpack.Decoder) error { } // Error converts an Error to a string. -func (errs ErrorMany) Error() string { +func (e ErrorMany) Error() string { var str []string - for _, err := range errs.Errors { + for _, err := range e.Errors { str = append(str, err.Str) } diff --git a/crud/request_test.go b/crud/request_test.go index d36d8a264..4c49a9214 100644 --- a/crud/request_test.go +++ b/crud/request_test.go @@ -72,7 +72,8 @@ var expectedOpts = map[string]interface{}{ type ValidSchemeResolver struct { } -func (*ValidSchemeResolver) ResolveSpaceIndex(s, i interface{}) (spaceNo, indexNo uint32, err error) { +func (*ValidSchemeResolver) ResolveSpaceIndex(s, i interface{}) (uint32, uint32, error) { + var spaceNo, indexNo uint32 if s != nil { spaceNo = uint32(s.(int)) } else { @@ -322,50 +323,51 @@ func TestRequestsDefaultValues(t *testing.T) { }{ { name: "InsertRequest", - ref: tarantool.NewCall17Request("crud.insert").Args([]interface{}{validSpace, []interface{}{}, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.insert").Args( + []interface{}{validSpace, []interface{}{}, map[string]interface{}{}}), target: crud.MakeInsertRequest(validSpace), }, { name: "InsertObjectRequest", - ref: tarantool.NewCall17Request("crud.insert_object").Args([]interface{}{validSpace, map[string]interface{}{}, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.insert_object").Args( + []interface{}{validSpace, map[string]interface{}{}, map[string]interface{}{}}), target: crud.MakeInsertObjectRequest(validSpace), }, { name: "InsertManyRequest", - ref: tarantool.NewCall17Request("crud.insert_many").Args([]interface{}{validSpace, []interface{}{}, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.insert_many").Args( + []interface{}{validSpace, []interface{}{}, map[string]interface{}{}}), target: crud.MakeInsertManyRequest(validSpace), }, { name: "InsertObjectManyRequest", - ref: tarantool.NewCall17Request("crud.insert_object_many").Args([]interface{}{validSpace, []map[string]interface{}{}, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.insert_object_many").Args( + []interface{}{validSpace, []map[string]interface{}{}, map[string]interface{}{}}), target: crud.MakeInsertObjectManyRequest(validSpace), }, { name: "GetRequest", - ref: tarantool.NewCall17Request("crud.get").Args([]interface{}{validSpace, []interface{}{}, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.get").Args( + []interface{}{validSpace, []interface{}{}, map[string]interface{}{}}), target: crud.MakeGetRequest(validSpace), }, { name: "UpdateRequest", - ref: tarantool.NewCall17Request("crud.update").Args([]interface{}{validSpace, []interface{}{}, - []interface{}{}, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.update").Args( + []interface{}{validSpace, []interface{}{}, + []interface{}{}, map[string]interface{}{}}), target: crud.MakeUpdateRequest(validSpace), }, { name: "DeleteRequest", - ref: tarantool.NewCall17Request("crud.delete").Args([]interface{}{validSpace, []interface{}{}, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.delete").Args( + []interface{}{validSpace, []interface{}{}, map[string]interface{}{}}), target: crud.MakeDeleteRequest(validSpace), }, { name: "ReplaceRequest", - ref: tarantool.NewCall17Request("crud.replace").Args([]interface{}{validSpace, []interface{}{}, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.replace").Args( + []interface{}{validSpace, []interface{}{}, map[string]interface{}{}}), target: crud.MakeReplaceRequest(validSpace), }, { @@ -382,68 +384,70 @@ func TestRequestsDefaultValues(t *testing.T) { }, { name: "ReplaceObjectManyRequest", - ref: tarantool.NewCall17Request("crud.replace_object_many").Args([]interface{}{validSpace, - []map[string]interface{}{}, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.replace_object_many").Args( + []interface{}{validSpace, []map[string]interface{}{}, map[string]interface{}{}}), target: crud.MakeReplaceObjectManyRequest(validSpace), }, { name: "UpsertRequest", - ref: tarantool.NewCall17Request("crud.upsert").Args([]interface{}{validSpace, []interface{}{}, - []interface{}{}, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.upsert").Args( + []interface{}{validSpace, []interface{}{}, []interface{}{}, + map[string]interface{}{}}), target: crud.MakeUpsertRequest(validSpace), }, { name: "UpsertObjectRequest", - ref: tarantool.NewCall17Request("crud.upsert_object").Args([]interface{}{validSpace, - map[string]interface{}{}, []interface{}{}, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.upsert_object").Args( + []interface{}{validSpace, map[string]interface{}{}, []interface{}{}, + map[string]interface{}{}}), target: crud.MakeUpsertObjectRequest(validSpace), }, { name: "UpsertManyRequest", - ref: tarantool.NewCall17Request("crud.upsert_many").Args([]interface{}{validSpace, - []interface{}{}, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.upsert_many").Args( + []interface{}{validSpace, []interface{}{}, map[string]interface{}{}}), target: crud.MakeUpsertManyRequest(validSpace), }, { name: "UpsertObjectManyRequest", - ref: tarantool.NewCall17Request("crud.upsert_object_many").Args([]interface{}{validSpace, - []interface{}{}, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.upsert_object_many").Args( + []interface{}{validSpace, []interface{}{}, map[string]interface{}{}}), target: crud.MakeUpsertObjectManyRequest(validSpace), }, { name: "SelectRequest", - ref: tarantool.NewCall17Request("crud.select").Args([]interface{}{validSpace, - nil, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.select").Args( + []interface{}{validSpace, nil, map[string]interface{}{}}), target: crud.MakeSelectRequest(validSpace), }, { name: "MinRequest", - ref: tarantool.NewCall17Request("crud.min").Args([]interface{}{validSpace, - nil, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.min").Args( + []interface{}{validSpace, nil, map[string]interface{}{}}), target: crud.MakeMinRequest(validSpace), }, { name: "MaxRequest", - ref: tarantool.NewCall17Request("crud.max").Args([]interface{}{validSpace, - nil, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.max").Args( + []interface{}{validSpace, nil, map[string]interface{}{}}), target: crud.MakeMaxRequest(validSpace), }, { name: "TruncateRequest", - ref: tarantool.NewCall17Request("crud.truncate").Args([]interface{}{validSpace, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.truncate").Args( + []interface{}{validSpace, map[string]interface{}{}}), target: crud.MakeTruncateRequest(validSpace), }, { name: "LenRequest", - ref: tarantool.NewCall17Request("crud.len").Args([]interface{}{validSpace, - map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.len").Args( + []interface{}{validSpace, map[string]interface{}{}}), target: crud.MakeLenRequest(validSpace), }, { name: "CountRequest", - ref: tarantool.NewCall17Request("crud.count").Args([]interface{}{validSpace, - nil, map[string]interface{}{}}), + ref: tarantool.NewCall17Request("crud.count").Args( + []interface{}{validSpace, nil, map[string]interface{}{}}), target: crud.MakeCountRequest(validSpace), }, { @@ -474,121 +478,150 @@ func TestRequestsSetters(t *testing.T) { target tarantool.Request }{ { - name: "InsertRequest", - ref: tarantool.NewCall17Request("crud.insert").Args([]interface{}{spaceName, tuple, expectedOpts}), + name: "InsertRequest", + ref: tarantool.NewCall17Request("crud.insert").Args( + []interface{}{spaceName, tuple, expectedOpts}), target: crud.MakeInsertRequest(spaceName).Tuple(tuple).Opts(simpleOperationOpts), }, { - name: "InsertObjectRequest", - ref: tarantool.NewCall17Request("crud.insert_object").Args([]interface{}{spaceName, reqObject, expectedOpts}), - target: crud.MakeInsertObjectRequest(spaceName).Object(reqObject).Opts(simpleOperationObjectOpts), + name: "InsertObjectRequest", + ref: tarantool.NewCall17Request("crud.insert_object").Args( + []interface{}{spaceName, reqObject, expectedOpts}), + target: crud.MakeInsertObjectRequest(spaceName).Object(reqObject). + Opts(simpleOperationObjectOpts), }, { - name: "InsertManyRequest", - ref: tarantool.NewCall17Request("crud.insert_many").Args([]interface{}{spaceName, tuples, expectedOpts}), + name: "InsertManyRequest", + ref: tarantool.NewCall17Request("crud.insert_many").Args( + []interface{}{spaceName, tuples, expectedOpts}), target: crud.MakeInsertManyRequest(spaceName).Tuples(tuples).Opts(opManyOpts), }, { - name: "InsertObjectManyRequest", - ref: tarantool.NewCall17Request("crud.insert_object_many").Args([]interface{}{spaceName, reqObjects, expectedOpts}), - target: crud.MakeInsertObjectManyRequest(spaceName).Objects(reqObjects).Opts(opObjManyOpts), + name: "InsertObjectManyRequest", + ref: tarantool.NewCall17Request("crud.insert_object_many").Args( + []interface{}{spaceName, reqObjects, expectedOpts}), + target: crud.MakeInsertObjectManyRequest(spaceName).Objects(reqObjects). + Opts(opObjManyOpts), }, { - name: "GetRequest", - ref: tarantool.NewCall17Request("crud.get").Args([]interface{}{spaceName, key, expectedOpts}), + name: "GetRequest", + ref: tarantool.NewCall17Request("crud.get").Args( + []interface{}{spaceName, key, expectedOpts}), target: crud.MakeGetRequest(spaceName).Key(key).Opts(getOpts), }, { - name: "UpdateRequest", - ref: tarantool.NewCall17Request("crud.update").Args([]interface{}{spaceName, key, operations, expectedOpts}), - target: crud.MakeUpdateRequest(spaceName).Key(key).Operations(operations).Opts(simpleOperationOpts), + name: "UpdateRequest", + ref: tarantool.NewCall17Request("crud.update").Args( + []interface{}{spaceName, key, operations, expectedOpts}), + target: crud.MakeUpdateRequest(spaceName).Key(key).Operations(operations). + Opts(simpleOperationOpts), }, { - name: "DeleteRequest", - ref: tarantool.NewCall17Request("crud.delete").Args([]interface{}{spaceName, key, expectedOpts}), + name: "DeleteRequest", + ref: tarantool.NewCall17Request("crud.delete").Args( + []interface{}{spaceName, key, expectedOpts}), target: crud.MakeDeleteRequest(spaceName).Key(key).Opts(simpleOperationOpts), }, { - name: "ReplaceRequest", - ref: tarantool.NewCall17Request("crud.replace").Args([]interface{}{spaceName, tuple, expectedOpts}), + name: "ReplaceRequest", + ref: tarantool.NewCall17Request("crud.replace").Args( + []interface{}{spaceName, tuple, expectedOpts}), target: crud.MakeReplaceRequest(spaceName).Tuple(tuple).Opts(simpleOperationOpts), }, { - name: "ReplaceObjectRequest", - ref: tarantool.NewCall17Request("crud.replace_object").Args([]interface{}{spaceName, reqObject, expectedOpts}), - target: crud.MakeReplaceObjectRequest(spaceName).Object(reqObject).Opts(simpleOperationObjectOpts), + name: "ReplaceObjectRequest", + ref: tarantool.NewCall17Request("crud.replace_object").Args( + []interface{}{spaceName, reqObject, expectedOpts}), + target: crud.MakeReplaceObjectRequest(spaceName).Object(reqObject). + Opts(simpleOperationObjectOpts), }, { - name: "ReplaceManyRequest", - ref: tarantool.NewCall17Request("crud.replace_many").Args([]interface{}{spaceName, tuples, expectedOpts}), + name: "ReplaceManyRequest", + ref: tarantool.NewCall17Request("crud.replace_many").Args( + []interface{}{spaceName, tuples, expectedOpts}), target: crud.MakeReplaceManyRequest(spaceName).Tuples(tuples).Opts(opManyOpts), }, { - name: "ReplaceObjectManyRequest", - ref: tarantool.NewCall17Request("crud.replace_object_many").Args([]interface{}{spaceName, reqObjects, expectedOpts}), - target: crud.MakeReplaceObjectManyRequest(spaceName).Objects(reqObjects).Opts(opObjManyOpts), + name: "ReplaceObjectManyRequest", + ref: tarantool.NewCall17Request("crud.replace_object_many").Args( + []interface{}{spaceName, reqObjects, expectedOpts}), + target: crud.MakeReplaceObjectManyRequest(spaceName).Objects(reqObjects). + Opts(opObjManyOpts), }, { - name: "UpsertRequest", - ref: tarantool.NewCall17Request("crud.upsert").Args([]interface{}{spaceName, tuple, operations, expectedOpts}), - target: crud.MakeUpsertRequest(spaceName).Tuple(tuple).Operations(operations).Opts(simpleOperationOpts), + name: "UpsertRequest", + ref: tarantool.NewCall17Request("crud.upsert").Args( + []interface{}{spaceName, tuple, operations, expectedOpts}), + target: crud.MakeUpsertRequest(spaceName).Tuple(tuple).Operations(operations). + Opts(simpleOperationOpts), }, { name: "UpsertObjectRequest", - ref: tarantool.NewCall17Request("crud.upsert_object").Args([]interface{}{spaceName, reqObject, - operations, expectedOpts}), - target: crud.MakeUpsertObjectRequest(spaceName).Object(reqObject).Operations(operations).Opts(simpleOperationOpts), + ref: tarantool.NewCall17Request("crud.upsert_object").Args( + []interface{}{spaceName, reqObject, operations, expectedOpts}), + target: crud.MakeUpsertObjectRequest(spaceName).Object(reqObject). + Operations(operations).Opts(simpleOperationOpts), }, { name: "UpsertManyRequest", - ref: tarantool.NewCall17Request("crud.upsert_many").Args([]interface{}{spaceName, - tuplesOperationsData, expectedOpts}), - target: crud.MakeUpsertManyRequest(spaceName).TuplesOperationsData(tuplesOperationsData).Opts(opManyOpts), + ref: tarantool.NewCall17Request("crud.upsert_many").Args( + []interface{}{spaceName, tuplesOperationsData, expectedOpts}), + target: crud.MakeUpsertManyRequest(spaceName). + TuplesOperationsData(tuplesOperationsData).Opts(opManyOpts), }, { name: "UpsertObjectManyRequest", - ref: tarantool.NewCall17Request("crud.upsert_object_many").Args([]interface{}{spaceName, - reqObjectsOperationsData, expectedOpts}), - target: crud.MakeUpsertObjectManyRequest(spaceName).ObjectsOperationsData(reqObjectsOperationsData).Opts(opManyOpts), + ref: tarantool.NewCall17Request("crud.upsert_object_many").Args( + []interface{}{spaceName, reqObjectsOperationsData, expectedOpts}), + target: crud.MakeUpsertObjectManyRequest(spaceName). + ObjectsOperationsData(reqObjectsOperationsData).Opts(opManyOpts), }, { - name: "SelectRequest", - ref: tarantool.NewCall17Request("crud.select").Args([]interface{}{spaceName, conditions, expectedOpts}), + name: "SelectRequest", + ref: tarantool.NewCall17Request("crud.select").Args( + []interface{}{spaceName, conditions, expectedOpts}), target: crud.MakeSelectRequest(spaceName).Conditions(conditions).Opts(selectOpts), }, { - name: "MinRequest", - ref: tarantool.NewCall17Request("crud.min").Args([]interface{}{spaceName, indexName, expectedOpts}), + name: "MinRequest", + ref: tarantool.NewCall17Request("crud.min").Args( + []interface{}{spaceName, indexName, expectedOpts}), target: crud.MakeMinRequest(spaceName).Index(indexName).Opts(minOpts), }, { - name: "MaxRequest", - ref: tarantool.NewCall17Request("crud.max").Args([]interface{}{spaceName, indexName, expectedOpts}), + name: "MaxRequest", + ref: tarantool.NewCall17Request("crud.max").Args( + []interface{}{spaceName, indexName, expectedOpts}), target: crud.MakeMaxRequest(spaceName).Index(indexName).Opts(maxOpts), }, { - name: "TruncateRequest", - ref: tarantool.NewCall17Request("crud.truncate").Args([]interface{}{spaceName, expectedOpts}), + name: "TruncateRequest", + ref: tarantool.NewCall17Request("crud.truncate").Args( + []interface{}{spaceName, expectedOpts}), target: crud.MakeTruncateRequest(spaceName).Opts(baseOpts), }, { - name: "LenRequest", - ref: tarantool.NewCall17Request("crud.len").Args([]interface{}{spaceName, expectedOpts}), + name: "LenRequest", + ref: tarantool.NewCall17Request("crud.len").Args( + []interface{}{spaceName, expectedOpts}), target: crud.MakeLenRequest(spaceName).Opts(baseOpts), }, { - name: "CountRequest", - ref: tarantool.NewCall17Request("crud.count").Args([]interface{}{spaceName, conditions, expectedOpts}), + name: "CountRequest", + ref: tarantool.NewCall17Request("crud.count").Args( + []interface{}{spaceName, conditions, expectedOpts}), target: crud.MakeCountRequest(spaceName).Conditions(conditions).Opts(countOpts), }, { - name: "StorageInfoRequest", - ref: tarantool.NewCall17Request("crud.storage_info").Args([]interface{}{expectedOpts}), + name: "StorageInfoRequest", + ref: tarantool.NewCall17Request("crud.storage_info").Args( + []interface{}{expectedOpts}), target: crud.MakeStorageInfoRequest().Opts(baseOpts), }, { - name: "StatsRequest", - ref: tarantool.NewCall17Request("crud.stats").Args([]interface{}{spaceName}), + name: "StatsRequest", + ref: tarantool.NewCall17Request("crud.stats").Args( + []interface{}{spaceName}), target: crud.MakeStatsRequest().Space(spaceName), }, } diff --git a/crud/result.go b/crud/result.go index 100ec2a95..b594e5de7 100644 --- a/crud/result.go +++ b/crud/result.go @@ -113,7 +113,6 @@ func (r *Result) DecodeMsgpack(d *msgpack.Decoder) error { if r.rowType != nil { tuples := reflect.New(reflect.SliceOf(r.rowType)) if err = d.DecodeValue(tuples); err != nil { - fmt.Println(tuples) return err } r.Rows = tuples.Elem().Interface() diff --git a/crud/tarantool_test.go b/crud/tarantool_test.go index c9870abc6..5cf29f66a 100644 --- a/crud/tarantool_test.go +++ b/crud/tarantool_test.go @@ -361,7 +361,8 @@ func generateTuples() []crud.Tuple { return tpls } -func generateTuplesOperationsData(tpls []crud.Tuple, operations []crud.Operation) []crud.TupleOperationsData { +func generateTuplesOperationsData(tpls []crud.Tuple, + operations []crud.Operation) []crud.TupleOperationsData { tuplesOperationsData := []crud.TupleOperationsData{} for _, tpl := range tpls { tuplesOperationsData = append(tuplesOperationsData, crud.TupleOperationsData{ @@ -385,7 +386,8 @@ func generateObjects() []crud.Object { return objs } -func generateObjectsOperationsData(objs []crud.Object, operations []crud.Operation) []crud.ObjectOperationsData { +func generateObjectsOperationsData(objs []crud.Object, + operations []crud.Operation) []crud.ObjectOperationsData { objectsOperationsData := []crud.ObjectOperationsData{} for _, obj := range objs { objectsOperationsData = append(objectsOperationsData, crud.ObjectOperationsData{ @@ -548,7 +550,7 @@ func TestUnflattenRows_IncorrectParams(t *testing.T) { objs, err := crud.UnflattenRows(tpls, invalidMetadata) require.Nil(t, objs) require.NotNil(t, err) - require.Contains(t, err.Error(), "Unexpected space format") + require.Contains(t, err.Error(), "unexpected space format") } func TestUnflattenRows(t *testing.T) { @@ -816,7 +818,8 @@ func runTestMain(m *testing.M) int { defer test_helpers.StopTarantoolWithCleanup(inst) if err != nil { - log.Fatalf("Failed to prepare test tarantool: %s", err) + log.Printf("Failed to prepare test tarantool: %s", err) + return 1 } return m.Run() diff --git a/crud/unflatten_rows.go b/crud/unflatten_rows.go index 67ebb2b69..f360f8ad5 100644 --- a/crud/unflatten_rows.go +++ b/crud/unflatten_rows.go @@ -18,11 +18,11 @@ func UnflattenRows(tuples []interface{}, format []interface{}) ([]MapObject, err object := make(map[string]interface{}) for fieldIdx, field := range tuple.([]interface{}) { if fieldInfo, ok = format[fieldIdx].(map[interface{}]interface{}); !ok { - return nil, fmt.Errorf("Unexpected space format: %q", format) + return nil, fmt.Errorf("unexpected space format: %q", format) } if fieldName, ok = fieldInfo["name"].(string); !ok { - return nil, fmt.Errorf("Unexpected space format: %q", format) + return nil, fmt.Errorf("unexpected space format: %q", format) } object[fieldName] = field diff --git a/crud/upsert_many.go b/crud/upsert_many.go index c7a54ba05..b0ccedf09 100644 --- a/crud/upsert_many.go +++ b/crud/upsert_many.go @@ -46,7 +46,8 @@ func MakeUpsertManyRequest(space string) UpsertManyRequest { // TuplesOperationsData sets tuples and operations for // the UpsertManyRequest request. // Note: default value is nil. -func (req UpsertManyRequest) TuplesOperationsData(tuplesOperationData []TupleOperationsData) UpsertManyRequest { +func (req UpsertManyRequest) TuplesOperationsData( + tuplesOperationData []TupleOperationsData) UpsertManyRequest { req.tuplesOperationsData = tuplesOperationData return req } diff --git a/datetime/datetime.go b/datetime/datetime.go index 09e86ce46..1f3bff775 100644 --- a/datetime/datetime.go +++ b/datetime/datetime.go @@ -181,8 +181,8 @@ func addMonth(ival *Interval, delta int64, adjust Adjust) { } } -func (dtime *Datetime) add(ival Interval, positive bool) (*Datetime, error) { - newVal := intervalFromDatetime(dtime) +func (d *Datetime) add(ival Interval, positive bool) (*Datetime, error) { + newVal := intervalFromDatetime(d) var direction int64 if positive { @@ -201,28 +201,28 @@ func (dtime *Datetime) add(ival Interval, positive bool) (*Datetime, error) { tm := time.Date(int(newVal.Year), time.Month(newVal.Month), int(newVal.Day), int(newVal.Hour), int(newVal.Min), - int(newVal.Sec), int(newVal.Nsec), dtime.time.Location()) + int(newVal.Sec), int(newVal.Nsec), d.time.Location()) return NewDatetime(tm) } // Add creates a new Datetime as addition of the Datetime and Interval. It may // return an error if a new Datetime is out of supported range. -func (dtime *Datetime) Add(ival Interval) (*Datetime, error) { - return dtime.add(ival, true) +func (d *Datetime) Add(ival Interval) (*Datetime, error) { + return d.add(ival, true) } // Sub creates a new Datetime as subtraction of the Datetime and Interval. It // may return an error if a new Datetime is out of supported range. -func (dtime *Datetime) Sub(ival Interval) (*Datetime, error) { - return dtime.add(ival, false) +func (d *Datetime) Sub(ival Interval) (*Datetime, error) { + return d.add(ival, false) } // Interval returns an Interval value to a next Datetime value. -func (dtime *Datetime) Interval(next *Datetime) Interval { - curIval := intervalFromDatetime(dtime) +func (d *Datetime) Interval(next *Datetime) Interval { + curIval := intervalFromDatetime(d) nextIval := intervalFromDatetime(next) - _, curOffset := dtime.time.Zone() + _, curOffset := d.time.Zone() _, nextOffset := next.time.Zone() curIval.Min -= int64(curOffset-nextOffset) / 60 return nextIval.Sub(curIval) @@ -236,12 +236,12 @@ func (dtime *Datetime) Interval(next *Datetime) Interval { // If a Datetime created via unmarshaling Tarantool's datetime then we try to // create a location with time.LoadLocation() first. In case of failure, we use // a location created with time.FixedZone(). -func (dtime *Datetime) ToTime() time.Time { - return dtime.time +func (d *Datetime) ToTime() time.Time { + return d.time } -func (dtime *Datetime) MarshalMsgpack() ([]byte, error) { - tm := dtime.ToTime() +func (d *Datetime) MarshalMsgpack() ([]byte, error) { + tm := d.ToTime() var dt datetime dt.seconds = tm.Unix() @@ -272,10 +272,11 @@ func (dtime *Datetime) MarshalMsgpack() ([]byte, error) { return buf, nil } -func (tm *Datetime) UnmarshalMsgpack(b []byte) error { +func (d *Datetime) UnmarshalMsgpack(b []byte) error { l := len(b) if l != maxSize && l != secondsSize { - return fmt.Errorf("invalid data length: got %d, wanted %d or %d", len(b), secondsSize, maxSize) + return fmt.Errorf("invalid data length: got %d, wanted %d or %d", + len(b), secondsSize, maxSize) } var dt datetime @@ -317,7 +318,7 @@ func (tm *Datetime) UnmarshalMsgpack(b []byte) error { dtp, err := NewDatetime(tt) if dtp != nil { - *tm = *dtp + *d = *dtp } return err } diff --git a/datetime/datetime_test.go b/datetime/datetime_test.go index e2f707f6f..705d2c56b 100644 --- a/datetime/datetime_test.go +++ b/datetime/datetime_test.go @@ -1183,7 +1183,8 @@ func runTestMain(m *testing.M) int { defer test_helpers.StopTarantoolWithCleanup(instance) if err != nil { - log.Fatalf("Failed to prepare test Tarantool: %s", err) + log.Printf("Failed to prepare test Tarantool: %s", err) + return 1 } return m.Run() diff --git a/datetime/interval.go b/datetime/interval.go index ef378e405..bcd052383 100644 --- a/datetime/interval.go +++ b/datetime/interval.go @@ -75,7 +75,7 @@ func encodeIntervalValue(e *msgpack.Encoder, typ uint64, value int64) (err error if value > 0 { err = e.EncodeUint(uint64(value)) } else if value < 0 { - err = e.EncodeInt(int64(value)) + err = e.EncodeInt(value) } } return diff --git a/decimal/bcd.go b/decimal/bcd.go index 2b5a4b258..d6222b861 100644 --- a/decimal/bcd.go +++ b/decimal/bcd.go @@ -39,9 +39,11 @@ package decimal // // See also: // -// * MessagePack extensions https://www.tarantool.io/en/doc/latest/dev_guide/internals/msgpack_extensions/ +// * MessagePack extensions: +// https://www.tarantool.io/en/doc/latest/dev_guide/internals/msgpack_extensions/ // -// * An implementation in C language https://github.com/tarantool/decNumber/blob/master/decPacked.c +// * An implementation in C language: +// https://github.com/tarantool/decNumber/blob/master/decPacked.c import ( "fmt" @@ -106,7 +108,7 @@ func getNumberLength(buf string) int { // is set to the scale of the number (this is the exponent, negated). func encodeStringToBCD(buf string) ([]byte, error) { if len(buf) == 0 { - return nil, fmt.Errorf("Length of number is zero") + return nil, fmt.Errorf("length of number is zero") } signByte := bytePlus // By default number is positive. if buf[0] == '-' { @@ -134,19 +136,19 @@ func encodeStringToBCD(buf string) ([]byte, error) { // Calculate a number of digits after the decimal point. if ch == '.' { if scale != 0 { - return nil, fmt.Errorf("Number contains more than one point") + return nil, fmt.Errorf("number contains more than one point") } scale = len(buf) - i - 1 continue } if ch < '0' || ch > '9' { - return nil, fmt.Errorf("Failed to convert symbol '%c' to a digit", ch) + return nil, fmt.Errorf("failed to convert symbol '%c' to a digit", ch) } - digit := byte(ch - '0') + digit := ch - '0' if highNibble { // Add a digit to a high nibble. - digit = digit << 4 + digit <<= 4 byteBuf = append(byteBuf, digit) highNibble = false } else { @@ -155,7 +157,7 @@ func encodeStringToBCD(buf string) ([]byte, error) { } // Add a digit to a low nibble. lowByteIdx := len(byteBuf) - 1 - byteBuf[lowByteIdx] = byteBuf[lowByteIdx] | digit + byteBuf[lowByteIdx] |= digit highNibble = true } } @@ -169,7 +171,7 @@ func encodeStringToBCD(buf string) ([]byte, error) { } else { // Put a sign to a low nibble. lowByteIdx := len(byteBuf) - 1 - byteBuf[lowByteIdx] = byteBuf[lowByteIdx] | signByte + byteBuf[lowByteIdx] |= signByte } byteBuf = append([]byte{byte(scale)}, byteBuf...) diff --git a/decimal/decimal.go b/decimal/decimal.go index 6cca53404..dd7b30433 100644 --- a/decimal/decimal.go +++ b/decimal/decimal.go @@ -6,13 +6,17 @@ // // See also: // -// * Tarantool MessagePack extensions https://www.tarantool.io/en/doc/latest/dev_guide/internals/msgpack_extensions/#the-decimal-type +// - Tarantool MessagePack extensions: +// https://www.tarantool.io/en/doc/latest/dev_guide/internals/msgpack_extensions/#the-decimal-type // -// * Tarantool data model https://www.tarantool.io/en/doc/latest/book/box/data_model/ +// - Tarantool data model: +// https://www.tarantool.io/en/doc/latest/book/box/data_model/ // -// * Tarantool issue for support decimal type https://github.com/tarantool/tarantool/issues/692 +// - Tarantool issue for support decimal type: +// https://github.com/tarantool/tarantool/issues/692 // -// * Tarantool module decimal https://www.tarantool.io/en/doc/latest/reference/reference_lua/decimal/ +// - Tarantool module decimal: +// https://www.tarantool.io/en/doc/latest/reference/reference_lua/decimal/ package decimal import ( @@ -29,7 +33,8 @@ import ( // // See also: // -// * Tarantool module decimal https://www.tarantool.io/en/doc/latest/reference/reference_lua/decimal/ +// - Tarantool module decimal: +// https://www.tarantool.io/en/doc/latest/reference/reference_lua/decimal/ const ( // Decimal external type. @@ -62,10 +67,16 @@ func (decNum *Decimal) MarshalMsgpack() ([]byte, error) { maxSupportedDecimal := decimal.New(1, decimalPrecision).Sub(one) // 10^decimalPrecision - 1 minSupportedDecimal := maxSupportedDecimal.Neg().Sub(one) // -10^decimalPrecision - 1 if decNum.GreaterThan(maxSupportedDecimal) { - return nil, fmt.Errorf("msgpack: decimal number is bigger than maximum supported number (10^%d - 1)", decimalPrecision) + return nil, + fmt.Errorf( + "msgpack: decimal number is bigger than maximum supported number (10^%d - 1)", + decimalPrecision) } if decNum.LessThan(minSupportedDecimal) { - return nil, fmt.Errorf("msgpack: decimal number is lesser than minimum supported number (-10^%d - 1)", decimalPrecision) + return nil, + fmt.Errorf( + "msgpack: decimal number is lesser than minimum supported number (-10^%d - 1)", + decimalPrecision) } strBuf := decNum.String() diff --git a/decimal/decimal_test.go b/decimal/decimal_test.go index e3eb867c2..92616c5f2 100644 --- a/decimal/decimal_test.go +++ b/decimal/decimal_test.go @@ -82,7 +82,8 @@ var benchmarkSamples = []struct { {"0.00000000000000000000000000000000000009", "d501269c", true}, {"-18.34", "d6010201834d", true}, {"-108.123456789", "d701090108123456789d", true}, - {"-11111111111111111111111111111111111111", "c7150100011111111111111111111111111111111111111d", false}, + {"-11111111111111111111111111111111111111", "c7150100011111111111111111111111111111111111111d", + false}, } var correctnessSamples = []struct { @@ -103,8 +104,10 @@ var correctnessSamples = []struct { {"-0", "d501000c", true}, {"0.01", "d501021c", true}, {"0.001", "d501031c", true}, - {"99999999999999999999999999999999999999", "c7150100099999999999999999999999999999999999999c", false}, - {"-99999999999999999999999999999999999999", "c7150100099999999999999999999999999999999999999d", false}, + {"99999999999999999999999999999999999999", "c7150100099999999999999999999999999999999999999c", + false}, + {"-99999999999999999999999999999999999999", "c7150100099999999999999999999999999999999999999d", + false}, {"-12.34", "d6010201234d", true}, {"12.34", "d6010201234c", true}, {"1.4", "c7030101014c", false}, @@ -112,8 +115,10 @@ var correctnessSamples = []struct { {"-2.718281828459045", "c70a010f02718281828459045d", false}, {"3.141592653589793", "c70a010f03141592653589793c", false}, {"-3.141592653589793", "c70a010f03141592653589793d", false}, - {"1234567891234567890.0987654321987654321", "c7150113012345678912345678900987654321987654321c", false}, - {"-1234567891234567890.0987654321987654321", "c7150113012345678912345678900987654321987654321d", false}, + {"1234567891234567890.0987654321987654321", "c7150113012345678912345678900987654321987654321c", + false}, + {"-1234567891234567890.0987654321987654321", + "c7150113012345678912345678900987654321987654321d", false}, } // There is a difference between encoding result from a raw string and from @@ -150,15 +155,16 @@ func TestMPEncodeDecode(t *testing.T) { var buf []byte tuple := TupleDecimal{number: *decNum} if buf, err = msgpack.Marshal(&tuple); err != nil { - t.Fatalf("Failed to msgpack.Encoder decimal number '%s' to a MessagePack buffer: %s", testcase.numString, err) + t.Fatalf( + "Failed to msgpack.Encoder decimal number '%s' to a MessagePack buffer: %s", + testcase.numString, err) } var v TupleDecimal if err = msgpack.Unmarshal(buf, &v); err != nil { - t.Fatalf("Failed to decode MessagePack buffer '%x' to a decimal number: %s", buf, err) + t.Fatalf("Failed to decode MessagePack buffer '%x' to a decimal number: %s", + buf, err) } if !decNum.Equal(v.number.Decimal) { - fmt.Println(decNum) - fmt.Println(v.number) t.Fatal("Decimal numbers are not equal") } }) @@ -208,7 +214,7 @@ func TestGetNumberLength(t *testing.T) { } func TestEncodeStringToBCDIncorrectNumber(t *testing.T) { - referenceErrMsg := "Number contains more than one point" + referenceErrMsg := "number contains more than one point" var numString = "0.1.0" buf, err := EncodeStringToBCD(numString) if err == nil { @@ -221,7 +227,7 @@ func TestEncodeStringToBCDIncorrectNumber(t *testing.T) { t.Fatalf("wrong error message on encoding of a string double points") } - referenceErrMsg = "Length of number is zero" + referenceErrMsg = "length of number is zero" numString = "" buf, err = EncodeStringToBCD(numString) if err == nil { @@ -234,7 +240,7 @@ func TestEncodeStringToBCDIncorrectNumber(t *testing.T) { t.Fatalf("wrong error message on encoding of an empty string") } - referenceErrMsg = "Failed to convert symbol 'a' to a digit" + referenceErrMsg = "failed to convert symbol 'a' to a digit" numString = "0.1a" buf, err = EncodeStringToBCD(numString) if err == nil { @@ -249,7 +255,8 @@ func TestEncodeStringToBCDIncorrectNumber(t *testing.T) { } func TestEncodeMaxNumber(t *testing.T) { - referenceErrMsg := "msgpack: decimal number is bigger than maximum supported number (10^38 - 1)" + referenceErrMsg := "msgpack: decimal number is bigger than maximum " + + "supported number (10^38 - 1)" decNum := decimal.New(1, DecimalPrecision) // // 10^DecimalPrecision tuple := TupleDecimal{number: *NewDecimal(decNum)} _, err := msgpack.Marshal(&tuple) @@ -257,12 +264,13 @@ func TestEncodeMaxNumber(t *testing.T) { t.Fatalf("It is possible to msgpack.Encoder a number unsupported by Tarantool") } if err.Error() != referenceErrMsg { - t.Fatalf("Incorrect error message on attempt to msgpack.Encoder number unsupported by Tarantool") + t.Fatalf("Incorrect error message on attempt to msgpack.Encoder number unsupported") } } func TestEncodeMinNumber(t *testing.T) { - referenceErrMsg := "msgpack: decimal number is lesser than minimum supported number (-10^38 - 1)" + referenceErrMsg := "msgpack: decimal number is lesser than minimum " + + "supported number (-10^38 - 1)" two := decimal.NewFromInt(2) decNum := decimal.New(1, DecimalPrecision).Neg().Sub(two) // -10^DecimalPrecision - 2 tuple := TupleDecimal{number: *NewDecimal(decNum)} @@ -271,9 +279,7 @@ func TestEncodeMinNumber(t *testing.T) { t.Fatalf("It is possible to msgpack.Encoder a number unsupported by Tarantool") } if err.Error() != referenceErrMsg { - fmt.Println("Actual message: ", err.Error()) - fmt.Println("Expected message: ", referenceErrMsg) - t.Fatalf("Incorrect error message on attempt to msgpack.Encoder number unsupported by Tarantool") + t.Fatalf("Incorrect error message on attempt to msgpack.Encoder number unsupported") } } @@ -368,26 +374,30 @@ func trimMPHeader(mpBuf []byte, fixExt bool) []byte { } func TestEncodeStringToBCD(t *testing.T) { - samples := append(correctnessSamples, rawSamples...) + samples := correctnessSamples + samples = append(samples, rawSamples...) samples = append(samples, benchmarkSamples...) for _, testcase := range samples { t.Run(testcase.numString, func(t *testing.T) { buf, err := EncodeStringToBCD(testcase.numString) if err != nil { - t.Fatalf("Failed to msgpack.Encoder decimal '%s' to BCD: %s", testcase.numString, err) - + t.Fatalf("Failed to msgpack.Encoder decimal '%s' to BCD: %s", + testcase.numString, err) } b, _ := hex.DecodeString(testcase.mpBuf) bcdBuf := trimMPHeader(b, testcase.fixExt) if reflect.DeepEqual(buf, bcdBuf) != true { - t.Fatalf("Failed to msgpack.Encoder decimal '%s' to BCD: expected '%x', actual '%x'", testcase.numString, bcdBuf, buf) + t.Fatalf( + "Failed to msgpack.Encoder decimal '%s' to BCD: expected '%x', actual '%x'", + testcase.numString, bcdBuf, buf) } }) } } func TestDecodeStringFromBCD(t *testing.T) { - samples := append(correctnessSamples, rawSamples...) + samples := correctnessSamples + samples = append(samples, rawSamples...) samples = append(samples, benchmarkSamples...) for _, testcase := range samples { t.Run(testcase.numString, func(t *testing.T) { @@ -407,14 +417,17 @@ func TestDecodeStringFromBCD(t *testing.T) { t.Fatalf("Failed to msgpack.Encoder string ('%s') to decimal", testcase.numString) } if !decExpected.Equal(decActual) { - t.Fatalf("Decoded decimal from BCD ('%x') is incorrect: expected '%s', actual '%s'", bcdBuf, testcase.numString, s) + t.Fatalf( + "Decoded decimal from BCD ('%x') is incorrect: expected '%s', actual '%s'", + bcdBuf, testcase.numString, s) } }) } } func TestMPEncode(t *testing.T) { - samples := append(correctnessSamples, decimalSamples...) + samples := correctnessSamples + samples = append(samples, decimalSamples...) samples = append(samples, benchmarkSamples...) for _, testcase := range samples { t.Run(testcase.numString, func(t *testing.T) { @@ -438,7 +451,8 @@ func TestMPEncode(t *testing.T) { } func TestMPDecode(t *testing.T) { - samples := append(correctnessSamples, decimalSamples...) + samples := correctnessSamples + samples = append(samples, decimalSamples...) samples = append(samples, benchmarkSamples...) for _, testcase := range samples { t.Run(testcase.numString, func(t *testing.T) { @@ -567,7 +581,8 @@ func TestInsert(t *testing.T) { conn := test_helpers.ConnectWithValidation(t, server, opts) defer conn.Close() - samples := append(correctnessSamples, benchmarkSamples...) + samples := correctnessSamples + samples = append(samples, benchmarkSamples...) for _, testcase := range samples { t.Run(testcase.numString, func(t *testing.T) { assertInsert(t, conn, testcase.numString) @@ -642,7 +657,8 @@ func runTestMain(m *testing.M) int { defer test_helpers.StopTarantoolWithCleanup(instance) if err != nil { - log.Fatalf("Failed to prepare test Tarantool: %s", err) + log.Printf("Failed to prepare test Tarantool: %s", err) + return 1 } return m.Run() diff --git a/example_test.go b/example_test.go index 70d499820..e2a645937 100644 --- a/example_test.go +++ b/example_test.go @@ -618,10 +618,16 @@ func ExampleProtocolVersion() { clientProtocolInfo := conn.ClientProtocolInfo() fmt.Println("Connector client protocol version:", clientProtocolInfo.Version) - fmt.Println("Connector client protocol features:", clientProtocolInfo.Features) + for _, f := range clientProtocolInfo.Features { + fmt.Println("Connector client protocol feature:", f) + } // Output: // Connector client protocol version: 4 - // Connector client protocol features: [StreamsFeature TransactionsFeature ErrorExtensionFeature WatchersFeature PaginationFeature] + // Connector client protocol feature: StreamsFeature + // Connector client protocol feature: TransactionsFeature + // Connector client protocol feature: ErrorExtensionFeature + // Connector client protocol feature: WatchersFeature + // Connector client protocol feature: PaginationFeature } func getTestTxnOpts() tarantool.Opts { diff --git a/export_test.go b/export_test.go index 688d09059..10d194840 100644 --- a/export_test.go +++ b/export_test.go @@ -97,7 +97,8 @@ func RefImplUnprepareBody(enc *msgpack.Encoder, stmt Prepared) error { // RefImplBeginBody is reference implementation for filling of an begin // request's body. -func RefImplBeginBody(enc *msgpack.Encoder, txnIsolation TxnIsolationLevel, timeout time.Duration) error { +func RefImplBeginBody(enc *msgpack.Encoder, txnIsolation TxnIsolationLevel, + timeout time.Duration) error { return fillBegin(enc, txnIsolation, timeout) } diff --git a/future.go b/future.go index a92a4c091..09229788c 100644 --- a/future.go +++ b/future.go @@ -206,7 +206,8 @@ func (fut *Future) GetTyped(result interface{}) error { // // # See also // -// * box.session.push() https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_session/push/ +// - box.session.push(): +// https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_session/push/ func (fut *Future) GetIterator() (it TimeoutResponseIterator) { futit := &asyncResponseIterator{ fut: fut, diff --git a/pool/connection_pool.go b/pool/connection_pool.go index 581b226fd..26e2199e9 100644 --- a/pool/connection_pool.go +++ b/pool/connection_pool.go @@ -12,7 +12,6 @@ package pool import ( "errors" - "fmt" "log" "sync" "time" @@ -32,6 +31,8 @@ var ( ErrNoHealthyInstance = errors.New("can't find healthy instance in pool") ErrExists = errors.New("endpoint exists") ErrClosed = errors.New("pool is closed") + ErrUnknownRequest = errors.New("the passed connected request doesn't belong to " + + "the current connection pool") ) // ConnectionHandler provides callbacks for components interested in handling @@ -132,7 +133,7 @@ func newEndpoint(addr string) *endpoint { // ConnectWithOpts creates pool for instances with addresses addrs // with options opts. -func ConnectWithOpts(addrs []string, connOpts tarantool.Opts, opts Opts) (connPool *ConnectionPool, err error) { +func ConnectWithOpts(addrs []string, connOpts tarantool.Opts, opts Opts) (*ConnectionPool, error) { if len(addrs) == 0 { return nil, ErrEmptyAddrs } @@ -145,7 +146,7 @@ func ConnectWithOpts(addrs []string, connOpts tarantool.Opts, opts Opts) (connPo roPool := newRoundRobinStrategy(size) anyPool := newRoundRobinStrategy(size) - connPool = &ConnectionPool{ + connPool := &ConnectionPool{ addrs: make(map[string]*endpoint), connOpts: connOpts.Clone(), opts: opts, @@ -180,7 +181,7 @@ func ConnectWithOpts(addrs []string, connOpts tarantool.Opts, opts Opts) (connPo // It is useless to set up tarantool.Opts.Reconnect value for a connection. // The connection pool has its own reconnection logic. See // Opts.CheckTimeout description. -func Connect(addrs []string, connOpts tarantool.Opts) (connPool *ConnectionPool, err error) { +func Connect(addrs []string, connOpts tarantool.Opts) (*ConnectionPool, error) { opts := Opts{ CheckTimeout: 1 * time.Second, } @@ -188,32 +189,32 @@ func Connect(addrs []string, connOpts tarantool.Opts) (connPool *ConnectionPool, } // ConnectedNow gets connected status of pool. -func (connPool *ConnectionPool) ConnectedNow(mode Mode) (bool, error) { - connPool.poolsMutex.RLock() - defer connPool.poolsMutex.RUnlock() +func (p *ConnectionPool) ConnectedNow(mode Mode) (bool, error) { + p.poolsMutex.RLock() + defer p.poolsMutex.RUnlock() - if connPool.state.get() != connectedState { + if p.state.get() != connectedState { return false, nil } switch mode { case ANY: - return !connPool.anyPool.IsEmpty(), nil + return !p.anyPool.IsEmpty(), nil case RW: - return !connPool.rwPool.IsEmpty(), nil + return !p.rwPool.IsEmpty(), nil case RO: - return !connPool.roPool.IsEmpty(), nil + return !p.roPool.IsEmpty(), nil case PreferRW: fallthrough case PreferRO: - return !connPool.rwPool.IsEmpty() || !connPool.roPool.IsEmpty(), nil + return !p.rwPool.IsEmpty() || !p.roPool.IsEmpty(), nil default: return false, ErrNoHealthyInstance } } // ConfiguredTimeout gets timeout of current connection. -func (connPool *ConnectionPool) ConfiguredTimeout(mode Mode) (time.Duration, error) { - conn, err := connPool.getNextConnection(mode) +func (p *ConnectionPool) ConfiguredTimeout(mode Mode) (time.Duration, error) { + conn, err := p.getNextConnection(mode) if err != nil { return 0, err } @@ -223,41 +224,41 @@ func (connPool *ConnectionPool) ConfiguredTimeout(mode Mode) (time.Duration, err // Add adds a new endpoint with the address into the pool. This function // adds the endpoint only after successful connection. -func (pool *ConnectionPool) Add(addr string) error { +func (p *ConnectionPool) Add(addr string) error { e := newEndpoint(addr) - pool.addrsMutex.Lock() + p.addrsMutex.Lock() // Ensure that Close()/CloseGraceful() not in progress/done. - if pool.state.get() != connectedState { - pool.addrsMutex.Unlock() + if p.state.get() != connectedState { + p.addrsMutex.Unlock() return ErrClosed } - if _, ok := pool.addrs[addr]; ok { - pool.addrsMutex.Unlock() + if _, ok := p.addrs[addr]; ok { + p.addrsMutex.Unlock() return ErrExists } - pool.addrs[addr] = e - pool.addrsMutex.Unlock() + p.addrs[addr] = e + p.addrsMutex.Unlock() - if err := pool.tryConnect(e); err != nil { - pool.addrsMutex.Lock() - delete(pool.addrs, addr) - pool.addrsMutex.Unlock() + if err := p.tryConnect(e); err != nil { + p.addrsMutex.Lock() + delete(p.addrs, addr) + p.addrsMutex.Unlock() close(e.closed) return err } - go pool.controller(e) + go p.controller(e) return nil } // Remove removes an endpoint with the address from the pool. The call // closes an active connection gracefully. -func (pool *ConnectionPool) Remove(addr string) error { - pool.addrsMutex.Lock() - endpoint, ok := pool.addrs[addr] +func (p *ConnectionPool) Remove(addr string) error { + p.addrsMutex.Lock() + endpoint, ok := p.addrs[addr] if !ok { - pool.addrsMutex.Unlock() + p.addrsMutex.Unlock() return errors.New("endpoint not exist") } @@ -270,20 +271,20 @@ func (pool *ConnectionPool) Remove(addr string) error { close(endpoint.shutdown) } - delete(pool.addrs, addr) - pool.addrsMutex.Unlock() + delete(p.addrs, addr) + p.addrsMutex.Unlock() <-endpoint.closed return nil } -func (pool *ConnectionPool) waitClose() []error { - pool.addrsMutex.RLock() - endpoints := make([]*endpoint, 0, len(pool.addrs)) - for _, e := range pool.addrs { +func (p *ConnectionPool) waitClose() []error { + p.addrsMutex.RLock() + endpoints := make([]*endpoint, 0, len(p.addrs)) + for _, e := range p.addrs { endpoints = append(endpoints, e) } - pool.addrsMutex.RUnlock() + p.addrsMutex.RUnlock() errs := make([]error, 0, len(endpoints)) for _, e := range endpoints { @@ -296,42 +297,42 @@ func (pool *ConnectionPool) waitClose() []error { } // Close closes connections in the ConnectionPool. -func (pool *ConnectionPool) Close() []error { - if pool.state.cas(connectedState, closedState) || - pool.state.cas(shutdownState, closedState) { - pool.addrsMutex.RLock() - for _, s := range pool.addrs { +func (p *ConnectionPool) Close() []error { + if p.state.cas(connectedState, closedState) || + p.state.cas(shutdownState, closedState) { + p.addrsMutex.RLock() + for _, s := range p.addrs { close(s.close) } - pool.addrsMutex.RUnlock() + p.addrsMutex.RUnlock() } - return pool.waitClose() + return p.waitClose() } // CloseGraceful closes connections in the ConnectionPool gracefully. It waits // for all requests to complete. -func (pool *ConnectionPool) CloseGraceful() []error { - if pool.state.cas(connectedState, shutdownState) { - pool.addrsMutex.RLock() - for _, s := range pool.addrs { +func (p *ConnectionPool) CloseGraceful() []error { + if p.state.cas(connectedState, shutdownState) { + p.addrsMutex.RLock() + for _, s := range p.addrs { close(s.shutdown) } - pool.addrsMutex.RUnlock() + p.addrsMutex.RUnlock() } - return pool.waitClose() + return p.waitClose() } // GetAddrs gets addresses of connections in pool. -func (pool *ConnectionPool) GetAddrs() []string { - pool.addrsMutex.RLock() - defer pool.addrsMutex.RUnlock() +func (p *ConnectionPool) GetAddrs() []string { + p.addrsMutex.RLock() + defer p.addrsMutex.RUnlock() - cpy := make([]string, len(pool.addrs)) + cpy := make([]string, len(p.addrs)) i := 0 - for addr := range pool.addrs { + for addr := range p.addrs { cpy[i] = addr i++ } @@ -340,20 +341,20 @@ func (pool *ConnectionPool) GetAddrs() []string { } // GetPoolInfo gets information of connections (connected status, ro/rw role). -func (pool *ConnectionPool) GetPoolInfo() map[string]*ConnectionInfo { +func (p *ConnectionPool) GetPoolInfo() map[string]*ConnectionInfo { info := make(map[string]*ConnectionInfo) - pool.addrsMutex.RLock() - defer pool.addrsMutex.RUnlock() - pool.poolsMutex.RLock() - defer pool.poolsMutex.RUnlock() + p.addrsMutex.RLock() + defer p.addrsMutex.RUnlock() + p.poolsMutex.RLock() + defer p.poolsMutex.RUnlock() - if pool.state.get() != connectedState { + if p.state.get() != connectedState { return info } - for addr := range pool.addrs { - conn, role := pool.getConnectionFromPool(addr) + for addr := range p.addrs { + conn, role := p.getConnectionFromPool(addr) if conn != nil { info[addr] = &ConnectionInfo{ConnectedNow: conn.ConnectedNow(), ConnRole: role} } @@ -366,8 +367,8 @@ func (pool *ConnectionPool) GetPoolInfo() map[string]*ConnectionInfo { // // Deprecated: the method will be removed in the next major version, // use a PingRequest object + Do() instead. -func (connPool *ConnectionPool) Ping(userMode Mode) (*tarantool.Response, error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Ping(userMode Mode) (*tarantool.Response, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -379,10 +380,10 @@ func (connPool *ConnectionPool) Ping(userMode Mode) (*tarantool.Response, error) // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (connPool *ConnectionPool) Select(space, index interface{}, +func (p *ConnectionPool) Select(space, index interface{}, offset, limit uint32, - iterator tarantool.Iter, key interface{}, userMode ...Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getConnByMode(ANY, userMode) + iterator tarantool.Iter, key interface{}, userMode ...Mode) (*tarantool.Response, error) { + conn, err := p.getConnByMode(ANY, userMode) if err != nil { return nil, err } @@ -395,8 +396,9 @@ func (connPool *ConnectionPool) Select(space, index interface{}, // // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. -func (connPool *ConnectionPool) Insert(space interface{}, tuple interface{}, userMode ...Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) Insert(space interface{}, tuple interface{}, + userMode ...Mode) (*tarantool.Response, error) { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return nil, err } @@ -409,8 +411,9 @@ func (connPool *ConnectionPool) Insert(space interface{}, tuple interface{}, use // // Deprecated: the method will be removed in the next major version, // use a ReplaceRequest object + Do() instead. -func (connPool *ConnectionPool) Replace(space interface{}, tuple interface{}, userMode ...Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) Replace(space interface{}, tuple interface{}, + userMode ...Mode) (*tarantool.Response, error) { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return nil, err } @@ -423,8 +426,9 @@ func (connPool *ConnectionPool) Replace(space interface{}, tuple interface{}, us // // Deprecated: the method will be removed in the next major version, // use a DeleteRequest object + Do() instead. -func (connPool *ConnectionPool) Delete(space, index interface{}, key interface{}, userMode ...Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) Delete(space, index interface{}, key interface{}, + userMode ...Mode) (*tarantool.Response, error) { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return nil, err } @@ -437,8 +441,9 @@ func (connPool *ConnectionPool) Delete(space, index interface{}, key interface{} // // Deprecated: the method will be removed in the next major version, // use a UpdateRequest object + Do() instead. -func (connPool *ConnectionPool) Update(space, index interface{}, key, ops interface{}, userMode ...Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) Update(space, index interface{}, key, ops interface{}, + userMode ...Mode) (*tarantool.Response, error) { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return nil, err } @@ -451,8 +456,9 @@ func (connPool *ConnectionPool) Update(space, index interface{}, key, ops interf // // Deprecated: the method will be removed in the next major version, // use a UpsertRequest object + Do() instead. -func (connPool *ConnectionPool) Upsert(space interface{}, tuple, ops interface{}, userMode ...Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) Upsert(space interface{}, tuple, ops interface{}, + userMode ...Mode) (*tarantool.Response, error) { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return nil, err } @@ -465,8 +471,9 @@ func (connPool *ConnectionPool) Upsert(space interface{}, tuple, ops interface{} // // Deprecated: the method will be removed in the next major version, // use a CallRequest object + Do() instead. -func (connPool *ConnectionPool) Call(functionName string, args interface{}, userMode Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Call(functionName string, args interface{}, + userMode Mode) (*tarantool.Response, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -480,8 +487,9 @@ func (connPool *ConnectionPool) Call(functionName string, args interface{}, user // // Deprecated: the method will be removed in the next major version, // use a Call16Request object + Do() instead. -func (connPool *ConnectionPool) Call16(functionName string, args interface{}, userMode Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Call16(functionName string, args interface{}, + userMode Mode) (*tarantool.Response, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -494,8 +502,9 @@ func (connPool *ConnectionPool) Call16(functionName string, args interface{}, us // // Deprecated: the method will be removed in the next major version, // use a Call17Request object + Do() instead. -func (connPool *ConnectionPool) Call17(functionName string, args interface{}, userMode Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Call17(functionName string, args interface{}, + userMode Mode) (*tarantool.Response, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -507,8 +516,9 @@ func (connPool *ConnectionPool) Call17(functionName string, args interface{}, us // // Deprecated: the method will be removed in the next major version, // use an EvalRequest object + Do() instead. -func (connPool *ConnectionPool) Eval(expr string, args interface{}, userMode Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Eval(expr string, args interface{}, + userMode Mode) (*tarantool.Response, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -520,8 +530,9 @@ func (connPool *ConnectionPool) Eval(expr string, args interface{}, userMode Mod // // Deprecated: the method will be removed in the next major version, // use an ExecuteRequest object + Do() instead. -func (connPool *ConnectionPool) Execute(expr string, args interface{}, userMode Mode) (resp *tarantool.Response, err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Execute(expr string, args interface{}, + userMode Mode) (*tarantool.Response, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -534,8 +545,9 @@ func (connPool *ConnectionPool) Execute(expr string, args interface{}, userMode // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (connPool *ConnectionPool) GetTyped(space, index interface{}, key interface{}, result interface{}, userMode ...Mode) (err error) { - conn, err := connPool.getConnByMode(ANY, userMode) +func (p *ConnectionPool) GetTyped(space, index interface{}, key interface{}, result interface{}, + userMode ...Mode) error { + conn, err := p.getConnByMode(ANY, userMode) if err != nil { return err } @@ -547,10 +559,10 @@ func (connPool *ConnectionPool) GetTyped(space, index interface{}, key interface // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (connPool *ConnectionPool) SelectTyped(space, index interface{}, +func (p *ConnectionPool) SelectTyped(space, index interface{}, offset, limit uint32, - iterator tarantool.Iter, key interface{}, result interface{}, userMode ...Mode) (err error) { - conn, err := connPool.getConnByMode(ANY, userMode) + iterator tarantool.Iter, key interface{}, result interface{}, userMode ...Mode) error { + conn, err := p.getConnByMode(ANY, userMode) if err != nil { return err } @@ -563,8 +575,9 @@ func (connPool *ConnectionPool) SelectTyped(space, index interface{}, // // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. -func (connPool *ConnectionPool) InsertTyped(space interface{}, tuple interface{}, result interface{}, userMode ...Mode) (err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) InsertTyped(space interface{}, tuple interface{}, result interface{}, + userMode ...Mode) error { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return err } @@ -577,8 +590,9 @@ func (connPool *ConnectionPool) InsertTyped(space interface{}, tuple interface{} // // Deprecated: the method will be removed in the next major version, // use a ReplaceRequest object + Do() instead. -func (connPool *ConnectionPool) ReplaceTyped(space interface{}, tuple interface{}, result interface{}, userMode ...Mode) (err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) ReplaceTyped(space interface{}, tuple interface{}, result interface{}, + userMode ...Mode) error { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return err } @@ -590,8 +604,9 @@ func (connPool *ConnectionPool) ReplaceTyped(space interface{}, tuple interface{ // // Deprecated: the method will be removed in the next major version, // use a DeleteRequest object + Do() instead. -func (connPool *ConnectionPool) DeleteTyped(space, index interface{}, key interface{}, result interface{}, userMode ...Mode) (err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) DeleteTyped(space, index interface{}, key interface{}, result interface{}, + userMode ...Mode) error { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return err } @@ -603,8 +618,9 @@ func (connPool *ConnectionPool) DeleteTyped(space, index interface{}, key interf // // Deprecated: the method will be removed in the next major version, // use a UpdateRequest object + Do() instead. -func (connPool *ConnectionPool) UpdateTyped(space, index interface{}, key, ops interface{}, result interface{}, userMode ...Mode) (err error) { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) UpdateTyped(space, index interface{}, key, ops interface{}, + result interface{}, userMode ...Mode) error { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return err } @@ -617,8 +633,9 @@ func (connPool *ConnectionPool) UpdateTyped(space, index interface{}, key, ops i // // Deprecated: the method will be removed in the next major version, // use a CallRequest object + Do() instead. -func (connPool *ConnectionPool) CallTyped(functionName string, args interface{}, result interface{}, userMode Mode) (err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) CallTyped(functionName string, args interface{}, result interface{}, + userMode Mode) error { + conn, err := p.getNextConnection(userMode) if err != nil { return err } @@ -632,8 +649,9 @@ func (connPool *ConnectionPool) CallTyped(functionName string, args interface{}, // // Deprecated: the method will be removed in the next major version, // use a Call16Request object + Do() instead. -func (connPool *ConnectionPool) Call16Typed(functionName string, args interface{}, result interface{}, userMode Mode) (err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Call16Typed(functionName string, args interface{}, result interface{}, + userMode Mode) error { + conn, err := p.getNextConnection(userMode) if err != nil { return err } @@ -646,8 +664,9 @@ func (connPool *ConnectionPool) Call16Typed(functionName string, args interface{ // // Deprecated: the method will be removed in the next major version, // use a Call17Request object + Do() instead. -func (connPool *ConnectionPool) Call17Typed(functionName string, args interface{}, result interface{}, userMode Mode) (err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Call17Typed(functionName string, args interface{}, result interface{}, + userMode Mode) error { + conn, err := p.getNextConnection(userMode) if err != nil { return err } @@ -659,8 +678,9 @@ func (connPool *ConnectionPool) Call17Typed(functionName string, args interface{ // // Deprecated: the method will be removed in the next major version, // use an EvalRequest object + Do() instead. -func (connPool *ConnectionPool) EvalTyped(expr string, args interface{}, result interface{}, userMode Mode) (err error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) EvalTyped(expr string, args interface{}, result interface{}, + userMode Mode) error { + conn, err := p.getNextConnection(userMode) if err != nil { return err } @@ -672,8 +692,9 @@ func (connPool *ConnectionPool) EvalTyped(expr string, args interface{}, result // // Deprecated: the method will be removed in the next major version, // use an ExecuteRequest object + Do() instead. -func (connPool *ConnectionPool) ExecuteTyped(expr string, args interface{}, result interface{}, userMode Mode) (tarantool.SQLInfo, []tarantool.ColumnMetaData, error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) ExecuteTyped(expr string, args interface{}, result interface{}, + userMode Mode) (tarantool.SQLInfo, []tarantool.ColumnMetaData, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return tarantool.SQLInfo{}, nil, err } @@ -685,10 +706,10 @@ func (connPool *ConnectionPool) ExecuteTyped(expr string, args interface{}, resu // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (connPool *ConnectionPool) SelectAsync(space, index interface{}, +func (p *ConnectionPool) SelectAsync(space, index interface{}, offset, limit uint32, iterator tarantool.Iter, key interface{}, userMode ...Mode) *tarantool.Future { - conn, err := connPool.getConnByMode(ANY, userMode) + conn, err := p.getConnByMode(ANY, userMode) if err != nil { return newErrorFuture(err) } @@ -701,8 +722,9 @@ func (connPool *ConnectionPool) SelectAsync(space, index interface{}, // // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. -func (connPool *ConnectionPool) InsertAsync(space interface{}, tuple interface{}, userMode ...Mode) *tarantool.Future { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) InsertAsync(space interface{}, tuple interface{}, + userMode ...Mode) *tarantool.Future { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return newErrorFuture(err) } @@ -715,8 +737,9 @@ func (connPool *ConnectionPool) InsertAsync(space interface{}, tuple interface{} // // Deprecated: the method will be removed in the next major version, // use a ReplaceRequest object + Do() instead. -func (connPool *ConnectionPool) ReplaceAsync(space interface{}, tuple interface{}, userMode ...Mode) *tarantool.Future { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) ReplaceAsync(space interface{}, tuple interface{}, + userMode ...Mode) *tarantool.Future { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return newErrorFuture(err) } @@ -729,8 +752,9 @@ func (connPool *ConnectionPool) ReplaceAsync(space interface{}, tuple interface{ // // Deprecated: the method will be removed in the next major version, // use a DeleteRequest object + Do() instead. -func (connPool *ConnectionPool) DeleteAsync(space, index interface{}, key interface{}, userMode ...Mode) *tarantool.Future { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) DeleteAsync(space, index interface{}, key interface{}, + userMode ...Mode) *tarantool.Future { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return newErrorFuture(err) } @@ -743,8 +767,9 @@ func (connPool *ConnectionPool) DeleteAsync(space, index interface{}, key interf // // Deprecated: the method will be removed in the next major version, // use a UpdateRequest object + Do() instead. -func (connPool *ConnectionPool) UpdateAsync(space, index interface{}, key, ops interface{}, userMode ...Mode) *tarantool.Future { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) UpdateAsync(space, index interface{}, key, ops interface{}, + userMode ...Mode) *tarantool.Future { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return newErrorFuture(err) } @@ -757,8 +782,9 @@ func (connPool *ConnectionPool) UpdateAsync(space, index interface{}, key, ops i // // Deprecated: the method will be removed in the next major version, // use a UpsertRequest object + Do() instead. -func (connPool *ConnectionPool) UpsertAsync(space interface{}, tuple interface{}, ops interface{}, userMode ...Mode) *tarantool.Future { - conn, err := connPool.getConnByMode(RW, userMode) +func (p *ConnectionPool) UpsertAsync(space interface{}, tuple interface{}, ops interface{}, + userMode ...Mode) *tarantool.Future { + conn, err := p.getConnByMode(RW, userMode) if err != nil { return newErrorFuture(err) } @@ -771,8 +797,9 @@ func (connPool *ConnectionPool) UpsertAsync(space interface{}, tuple interface{} // // Deprecated: the method will be removed in the next major version, // use a CallRequest object + Do() instead. -func (connPool *ConnectionPool) CallAsync(functionName string, args interface{}, userMode Mode) *tarantool.Future { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) CallAsync(functionName string, args interface{}, + userMode Mode) *tarantool.Future { + conn, err := p.getNextConnection(userMode) if err != nil { return newErrorFuture(err) } @@ -786,8 +813,9 @@ func (connPool *ConnectionPool) CallAsync(functionName string, args interface{}, // // Deprecated: the method will be removed in the next major version, // use a Call16Request object + Do() instead. -func (connPool *ConnectionPool) Call16Async(functionName string, args interface{}, userMode Mode) *tarantool.Future { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Call16Async(functionName string, args interface{}, + userMode Mode) *tarantool.Future { + conn, err := p.getNextConnection(userMode) if err != nil { return newErrorFuture(err) } @@ -800,8 +828,9 @@ func (connPool *ConnectionPool) Call16Async(functionName string, args interface{ // // Deprecated: the method will be removed in the next major version, // use a Call17Request object + Do() instead. -func (connPool *ConnectionPool) Call17Async(functionName string, args interface{}, userMode Mode) *tarantool.Future { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) Call17Async(functionName string, args interface{}, + userMode Mode) *tarantool.Future { + conn, err := p.getNextConnection(userMode) if err != nil { return newErrorFuture(err) } @@ -813,8 +842,9 @@ func (connPool *ConnectionPool) Call17Async(functionName string, args interface{ // // Deprecated: the method will be removed in the next major version, // use an EvalRequest object + Do() instead. -func (connPool *ConnectionPool) EvalAsync(expr string, args interface{}, userMode Mode) *tarantool.Future { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) EvalAsync(expr string, args interface{}, + userMode Mode) *tarantool.Future { + conn, err := p.getNextConnection(userMode) if err != nil { return newErrorFuture(err) } @@ -827,8 +857,9 @@ func (connPool *ConnectionPool) EvalAsync(expr string, args interface{}, userMod // // Deprecated: the method will be removed in the next major version, // use an ExecuteRequest object + Do() instead. -func (connPool *ConnectionPool) ExecuteAsync(expr string, args interface{}, userMode Mode) *tarantool.Future { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) ExecuteAsync(expr string, args interface{}, + userMode Mode) *tarantool.Future { + conn, err := p.getNextConnection(userMode) if err != nil { return newErrorFuture(err) } @@ -837,13 +868,13 @@ func (connPool *ConnectionPool) ExecuteAsync(expr string, args interface{}, user } // NewStream creates new Stream object for connection selected -// by userMode from connPool. +// by userMode from pool. // // Since v. 2.10.0, Tarantool supports streams and interactive transactions over them. // To use interactive transactions, memtx_use_mvcc_engine box option should be set to true. // Since 1.7.0 -func (connPool *ConnectionPool) NewStream(userMode Mode) (*tarantool.Stream, error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) NewStream(userMode Mode) (*tarantool.Stream, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -851,8 +882,8 @@ func (connPool *ConnectionPool) NewStream(userMode Mode) (*tarantool.Stream, err } // NewPrepared passes a sql statement to Tarantool for preparation synchronously. -func (connPool *ConnectionPool) NewPrepared(expr string, userMode Mode) (*tarantool.Prepared, error) { - conn, err := connPool.getNextConnection(userMode) +func (p *ConnectionPool) NewPrepared(expr string, userMode Mode) (*tarantool.Prepared, error) { + conn, err := p.getNextConnection(userMode) if err != nil { return nil, err } @@ -878,10 +909,10 @@ func (connPool *ConnectionPool) NewPrepared(expr string, userMode Mode) (*tarant // https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_events/#box-watchers // // Since 1.10.0 -func (pool *ConnectionPool) NewWatcher(key string, +func (p *ConnectionPool) NewWatcher(key string, callback tarantool.WatchCallback, mode Mode) (tarantool.Watcher, error) { watchersRequired := false - for _, feature := range pool.connOpts.RequiredProtocolInfo.Features { + for _, feature := range p.connOpts.RequiredProtocolInfo.Features { if tarantool.WatchersFeature == feature { watchersRequired = true break @@ -893,7 +924,7 @@ func (pool *ConnectionPool) NewWatcher(key string, } watcher := &poolWatcher{ - container: &pool.watcherContainer, + container: &p.watcherContainer, mode: mode, key: key, callback: callback, @@ -903,11 +934,11 @@ func (pool *ConnectionPool) NewWatcher(key string, watcher.container.add(watcher) - rr := pool.anyPool + rr := p.anyPool if mode == RW { - rr = pool.rwPool + rr = p.rwPool } else if mode == RO { - rr = pool.roPool + rr = p.roPool } conns := rr.GetConnections() @@ -923,15 +954,15 @@ func (pool *ConnectionPool) NewWatcher(key string, // Do sends the request and returns a future. // For requests that belong to the only one connection (e.g. Unprepare or ExecutePrepared) // the argument of type Mode is unused. -func (connPool *ConnectionPool) Do(req tarantool.Request, userMode Mode) *tarantool.Future { +func (p *ConnectionPool) Do(req tarantool.Request, userMode Mode) *tarantool.Future { if connectedReq, ok := req.(tarantool.ConnectedRequest); ok { - conn, _ := connPool.getConnectionFromPool(connectedReq.Conn().Addr()) + conn, _ := p.getConnectionFromPool(connectedReq.Conn().Addr()) if conn == nil { - return newErrorFuture(fmt.Errorf("the passed connected request doesn't belong to the current connection or connection pool")) + return newErrorFuture(ErrUnknownRequest) } return connectedReq.Conn().Do(req) } - conn, err := connPool.getNextConnection(userMode) + conn, err := p.getNextConnection(userMode) if err != nil { return newErrorFuture(err) } @@ -943,7 +974,7 @@ func (connPool *ConnectionPool) Do(req tarantool.Request, userMode Mode) *tarant // private // -func (connPool *ConnectionPool) getConnectionRole(conn *tarantool.Connection) (Role, error) { +func (p *ConnectionPool) getConnectionRole(conn *tarantool.Connection) (Role, error) { resp, err := conn.Do(tarantool.NewCallRequest("box.info")).Get() if err != nil { return UnknownRole, err @@ -978,48 +1009,49 @@ func (connPool *ConnectionPool) getConnectionRole(conn *tarantool.Connection) (R return UnknownRole, nil } -func (connPool *ConnectionPool) getConnectionFromPool(addr string) (*tarantool.Connection, Role) { - if conn := connPool.rwPool.GetConnByAddr(addr); conn != nil { +func (p *ConnectionPool) getConnectionFromPool(addr string) (*tarantool.Connection, Role) { + if conn := p.rwPool.GetConnByAddr(addr); conn != nil { return conn, MasterRole } - if conn := connPool.roPool.GetConnByAddr(addr); conn != nil { + if conn := p.roPool.GetConnByAddr(addr); conn != nil { return conn, ReplicaRole } - return connPool.anyPool.GetConnByAddr(addr), UnknownRole + return p.anyPool.GetConnByAddr(addr), UnknownRole } -func (pool *ConnectionPool) deleteConnection(addr string) { - if conn := pool.anyPool.DeleteConnByAddr(addr); conn != nil { - if conn := pool.rwPool.DeleteConnByAddr(addr); conn == nil { - pool.roPool.DeleteConnByAddr(addr) +func (p *ConnectionPool) deleteConnection(addr string) { + if conn := p.anyPool.DeleteConnByAddr(addr); conn != nil { + if conn := p.rwPool.DeleteConnByAddr(addr); conn == nil { + p.roPool.DeleteConnByAddr(addr) } // The internal connection deinitialization. - pool.watcherContainer.mutex.RLock() - defer pool.watcherContainer.mutex.RUnlock() + p.watcherContainer.mutex.RLock() + defer p.watcherContainer.mutex.RUnlock() - pool.watcherContainer.foreach(func(watcher *poolWatcher) error { + p.watcherContainer.foreach(func(watcher *poolWatcher) error { watcher.unwatch(conn) return nil }) } } -func (pool *ConnectionPool) addConnection(addr string, +func (p *ConnectionPool) addConnection(addr string, conn *tarantool.Connection, role Role) error { // The internal connection initialization. - pool.watcherContainer.mutex.RLock() - defer pool.watcherContainer.mutex.RUnlock() + p.watcherContainer.mutex.RLock() + defer p.watcherContainer.mutex.RUnlock() watched := []*poolWatcher{} - err := pool.watcherContainer.foreach(func(watcher *poolWatcher) error { + err := p.watcherContainer.foreach(func(watcher *poolWatcher) error { watch := false - if watcher.mode == RW { + switch watcher.mode { + case RW: watch = role == MasterRole - } else if watcher.mode == RO { + case RO: watch = role == ReplicaRole - } else { + default: watch = true } if watch { @@ -1038,22 +1070,22 @@ func (pool *ConnectionPool) addConnection(addr string, return err } - pool.anyPool.AddConn(addr, conn) + p.anyPool.AddConn(addr, conn) switch role { case MasterRole: - pool.rwPool.AddConn(addr, conn) + p.rwPool.AddConn(addr, conn) case ReplicaRole: - pool.roPool.AddConn(addr, conn) + p.roPool.AddConn(addr, conn) } return nil } -func (connPool *ConnectionPool) handlerDiscovered(conn *tarantool.Connection, +func (p *ConnectionPool) handlerDiscovered(conn *tarantool.Connection, role Role) bool { var err error - if connPool.opts.ConnectionHandler != nil { - err = connPool.opts.ConnectionHandler.Discovered(conn, role) + if p.opts.ConnectionHandler != nil { + err = p.opts.ConnectionHandler.Discovered(conn, role) } if err != nil { @@ -1064,11 +1096,11 @@ func (connPool *ConnectionPool) handlerDiscovered(conn *tarantool.Connection, return true } -func (connPool *ConnectionPool) handlerDeactivated(conn *tarantool.Connection, +func (p *ConnectionPool) handlerDeactivated(conn *tarantool.Connection, role Role) { var err error - if connPool.opts.ConnectionHandler != nil { - err = connPool.opts.ConnectionHandler.Deactivated(conn, role) + if p.opts.ConnectionHandler != nil { + err = p.opts.ConnectionHandler.Deactivated(conn, role) } if err != nil { @@ -1077,32 +1109,32 @@ func (connPool *ConnectionPool) handlerDeactivated(conn *tarantool.Connection, } } -func (connPool *ConnectionPool) fillPools() bool { +func (p *ConnectionPool) fillPools() bool { somebodyAlive := false // It is called before controller() goroutines so we don't expect // concurrency issues here. - for addr := range connPool.addrs { + for addr := range p.addrs { end := newEndpoint(addr) - connPool.addrs[addr] = end + p.addrs[addr] = end - connOpts := connPool.connOpts + connOpts := p.connOpts connOpts.Notify = end.notify conn, err := tarantool.Connect(addr, connOpts) if err != nil { log.Printf("tarantool: connect to %s failed: %s\n", addr, err.Error()) } else if conn != nil { - role, err := connPool.getConnectionRole(conn) + role, err := p.getConnectionRole(conn) if err != nil { conn.Close() log.Printf("tarantool: storing connection to %s failed: %s\n", addr, err) continue } - if connPool.handlerDiscovered(conn, role) { - if connPool.addConnection(addr, conn, role) != nil { + if p.handlerDiscovered(conn, role) { + if p.addConnection(addr, conn, role) != nil { conn.Close() - connPool.handlerDeactivated(conn, role) + p.handlerDeactivated(conn, role) } if conn.ConnectedNow() { @@ -1110,9 +1142,9 @@ func (connPool *ConnectionPool) fillPools() bool { end.role = role somebodyAlive = true } else { - connPool.deleteConnection(addr) + p.deleteConnection(addr) conn.Close() - connPool.handlerDeactivated(conn, role) + p.handlerDeactivated(conn, role) } } else { conn.Close() @@ -1123,21 +1155,21 @@ func (connPool *ConnectionPool) fillPools() bool { return somebodyAlive } -func (pool *ConnectionPool) updateConnection(e *endpoint) { - pool.poolsMutex.Lock() +func (p *ConnectionPool) updateConnection(e *endpoint) { + p.poolsMutex.Lock() - if pool.state.get() != connectedState { - pool.poolsMutex.Unlock() + if p.state.get() != connectedState { + p.poolsMutex.Unlock() return } - if role, err := pool.getConnectionRole(e.conn); err == nil { + if role, err := p.getConnectionRole(e.conn); err == nil { if e.role != role { - pool.deleteConnection(e.addr) - pool.poolsMutex.Unlock() + p.deleteConnection(e.addr) + p.poolsMutex.Unlock() - pool.handlerDeactivated(e.conn, e.role) - opened := pool.handlerDiscovered(e.conn, role) + p.handlerDeactivated(e.conn, e.role) + opened := p.handlerDiscovered(e.conn, role) if !opened { e.conn.Close() e.conn = nil @@ -1145,59 +1177,59 @@ func (pool *ConnectionPool) updateConnection(e *endpoint) { return } - pool.poolsMutex.Lock() - if pool.state.get() != connectedState { - pool.poolsMutex.Unlock() + p.poolsMutex.Lock() + if p.state.get() != connectedState { + p.poolsMutex.Unlock() e.conn.Close() - pool.handlerDeactivated(e.conn, role) + p.handlerDeactivated(e.conn, role) e.conn = nil e.role = UnknownRole return } - if pool.addConnection(e.addr, e.conn, role) != nil { - pool.poolsMutex.Unlock() + if p.addConnection(e.addr, e.conn, role) != nil { + p.poolsMutex.Unlock() e.conn.Close() - pool.handlerDeactivated(e.conn, role) + p.handlerDeactivated(e.conn, role) e.conn = nil e.role = UnknownRole return } e.role = role } - pool.poolsMutex.Unlock() + p.poolsMutex.Unlock() return } else { - pool.deleteConnection(e.addr) - pool.poolsMutex.Unlock() + p.deleteConnection(e.addr) + p.poolsMutex.Unlock() e.conn.Close() - pool.handlerDeactivated(e.conn, e.role) + p.handlerDeactivated(e.conn, e.role) e.conn = nil e.role = UnknownRole return } } -func (pool *ConnectionPool) tryConnect(e *endpoint) error { - pool.poolsMutex.Lock() +func (p *ConnectionPool) tryConnect(e *endpoint) error { + p.poolsMutex.Lock() - if pool.state.get() != connectedState { - pool.poolsMutex.Unlock() + if p.state.get() != connectedState { + p.poolsMutex.Unlock() return ErrClosed } e.conn = nil e.role = UnknownRole - connOpts := pool.connOpts + connOpts := p.connOpts connOpts.Notify = e.notify conn, err := tarantool.Connect(e.addr, connOpts) if err == nil { - role, err := pool.getConnectionRole(conn) - pool.poolsMutex.Unlock() + role, err := p.getConnectionRole(conn) + p.poolsMutex.Unlock() if err != nil { conn.Close() @@ -1205,54 +1237,54 @@ func (pool *ConnectionPool) tryConnect(e *endpoint) error { return err } - opened := pool.handlerDiscovered(conn, role) + opened := p.handlerDiscovered(conn, role) if !opened { conn.Close() return errors.New("storing connection canceled") } - pool.poolsMutex.Lock() - if pool.state.get() != connectedState { - pool.poolsMutex.Unlock() + p.poolsMutex.Lock() + if p.state.get() != connectedState { + p.poolsMutex.Unlock() conn.Close() - pool.handlerDeactivated(conn, role) + p.handlerDeactivated(conn, role) return ErrClosed } - if err = pool.addConnection(e.addr, conn, role); err != nil { - pool.poolsMutex.Unlock() + if err = p.addConnection(e.addr, conn, role); err != nil { + p.poolsMutex.Unlock() conn.Close() - pool.handlerDeactivated(conn, role) + p.handlerDeactivated(conn, role) return err } e.conn = conn e.role = role } - pool.poolsMutex.Unlock() + p.poolsMutex.Unlock() return err } -func (pool *ConnectionPool) reconnect(e *endpoint) { - pool.poolsMutex.Lock() +func (p *ConnectionPool) reconnect(e *endpoint) { + p.poolsMutex.Lock() - if pool.state.get() != connectedState { - pool.poolsMutex.Unlock() + if p.state.get() != connectedState { + p.poolsMutex.Unlock() return } - pool.deleteConnection(e.addr) - pool.poolsMutex.Unlock() + p.deleteConnection(e.addr) + p.poolsMutex.Unlock() - pool.handlerDeactivated(e.conn, e.role) + p.handlerDeactivated(e.conn, e.role) e.conn = nil e.role = UnknownRole - pool.tryConnect(e) + p.tryConnect(e) } -func (pool *ConnectionPool) controller(e *endpoint) { - timer := time.NewTicker(pool.opts.CheckTimeout) +func (p *ConnectionPool) controller(e *endpoint) { + timer := time.NewTicker(p.opts.CheckTimeout) defer timer.Stop() shutdown := false @@ -1276,13 +1308,13 @@ func (pool *ConnectionPool) controller(e *endpoint) { // e.close has priority to avoid concurrency with e.shutdown. case <-e.close: if e.conn != nil { - pool.poolsMutex.Lock() - pool.deleteConnection(e.addr) - pool.poolsMutex.Unlock() + p.poolsMutex.Lock() + p.deleteConnection(e.addr) + p.poolsMutex.Unlock() if !shutdown { e.closeErr = e.conn.Close() - pool.handlerDeactivated(e.conn, e.role) + p.handlerDeactivated(e.conn, e.role) close(e.closed) } else { // Force close the connection. @@ -1298,9 +1330,9 @@ func (pool *ConnectionPool) controller(e *endpoint) { case <-e.shutdown: shutdown = true if e.conn != nil { - pool.poolsMutex.Lock() - pool.deleteConnection(e.addr) - pool.poolsMutex.Unlock() + p.poolsMutex.Lock() + p.deleteConnection(e.addr) + p.poolsMutex.Unlock() // We need to catch s.close in the current goroutine, so // we need to start an another one for the shutdown. @@ -1319,15 +1351,15 @@ func (pool *ConnectionPool) controller(e *endpoint) { // Will be processed at an upper level. case <-e.notify: if e.conn != nil && e.conn.ClosedNow() { - pool.poolsMutex.Lock() - if pool.state.get() == connectedState { - pool.deleteConnection(e.addr) - pool.poolsMutex.Unlock() - pool.handlerDeactivated(e.conn, e.role) + p.poolsMutex.Lock() + if p.state.get() == connectedState { + p.deleteConnection(e.addr) + p.poolsMutex.Unlock() + p.handlerDeactivated(e.conn, e.role) e.conn = nil e.role = UnknownRole } else { - pool.poolsMutex.Unlock() + p.poolsMutex.Unlock() } } case <-timer.C: @@ -1335,11 +1367,11 @@ func (pool *ConnectionPool) controller(e *endpoint) { // Relocate connection between subpools // if ro/rw was updated. if e.conn == nil { - pool.tryConnect(e) + p.tryConnect(e) } else if !e.conn.ClosedNow() { - pool.updateConnection(e) + p.updateConnection(e) } else { - pool.reconnect(e) + p.reconnect(e) } } } @@ -1347,42 +1379,43 @@ func (pool *ConnectionPool) controller(e *endpoint) { } } -func (connPool *ConnectionPool) getNextConnection(mode Mode) (*tarantool.Connection, error) { +func (p *ConnectionPool) getNextConnection(mode Mode) (*tarantool.Connection, error) { switch mode { case ANY: - if next := connPool.anyPool.GetNextConnection(); next != nil { + if next := p.anyPool.GetNextConnection(); next != nil { return next, nil } case RW: - if next := connPool.rwPool.GetNextConnection(); next != nil { + if next := p.rwPool.GetNextConnection(); next != nil { return next, nil } return nil, ErrNoRwInstance case RO: - if next := connPool.roPool.GetNextConnection(); next != nil { + if next := p.roPool.GetNextConnection(); next != nil { return next, nil } return nil, ErrNoRoInstance case PreferRW: - if next := connPool.rwPool.GetNextConnection(); next != nil { + if next := p.rwPool.GetNextConnection(); next != nil { return next, nil } - if next := connPool.roPool.GetNextConnection(); next != nil { + if next := p.roPool.GetNextConnection(); next != nil { return next, nil } case PreferRO: - if next := connPool.roPool.GetNextConnection(); next != nil { + if next := p.roPool.GetNextConnection(); next != nil { return next, nil } - if next := connPool.rwPool.GetNextConnection(); next != nil { + if next := p.rwPool.GetNextConnection(); next != nil { return next, nil } } return nil, ErrNoHealthyInstance } -func (connPool *ConnectionPool) getConnByMode(defaultMode Mode, userMode []Mode) (*tarantool.Connection, error) { +func (p *ConnectionPool) getConnByMode(defaultMode Mode, + userMode []Mode) (*tarantool.Connection, error) { if len(userMode) > 1 { return nil, ErrTooManyArgs } @@ -1392,7 +1425,7 @@ func (connPool *ConnectionPool) getConnByMode(defaultMode Mode, userMode []Mode) mode = userMode[0] } - return connPool.getNextConnection(mode) + return p.getNextConnection(mode) } func newErrorFuture(err error) *tarantool.Future { diff --git a/pool/connection_pool_test.go b/pool/connection_pool_test.go index 912721cd4..c34e71673 100644 --- a/pool/connection_pool_test.go +++ b/pool/connection_pool_test.go @@ -130,7 +130,8 @@ func TestReconnect(t *testing.T) { }, } - err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) err = test_helpers.RestartTarantool(&instances[0]) @@ -146,7 +147,8 @@ func TestReconnect(t *testing.T) { }, } - err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) } @@ -220,7 +222,8 @@ func TestDisconnectAll(t *testing.T) { }, } - err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) err = test_helpers.RestartTarantool(&instances[0]) @@ -240,7 +243,8 @@ func TestDisconnectAll(t *testing.T) { }, } - err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) } @@ -578,7 +582,8 @@ func TestClose(t *testing.T) { }, } - err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) } @@ -636,7 +641,8 @@ func TestCloseGraceful(t *testing.T) { }, } - err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) } @@ -904,7 +910,8 @@ func TestRequestOnClosed(t *testing.T) { server2: false, }, } - err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.CheckPoolStatuses, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) _, err = connPool.Ping(pool.ANY) @@ -1563,7 +1570,8 @@ func TestUpdateInstancesRoles(t *testing.T) { Mode: pool.ANY, } - err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) // RW @@ -1574,7 +1582,8 @@ func TestUpdateInstancesRoles(t *testing.T) { Mode: pool.RW, } - err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) // RO @@ -1585,7 +1594,8 @@ func TestUpdateInstancesRoles(t *testing.T) { Mode: pool.RO, } - err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) // PreferRW @@ -1596,7 +1606,8 @@ func TestUpdateInstancesRoles(t *testing.T) { Mode: pool.PreferRW, } - err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) // PreferRO @@ -1607,7 +1618,8 @@ func TestUpdateInstancesRoles(t *testing.T) { Mode: pool.PreferRO, } - err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, defaultCountRetry, defaultTimeoutRetry) + err = test_helpers.Retry(test_helpers.ProcessListenOnInstance, args, + defaultCountRetry, defaultTimeoutRetry) require.Nil(t, err) } @@ -1669,7 +1681,8 @@ func TestInsert(t *testing.T) { require.Equalf(t, "rw_insert_value", value, "unexpected body of Select (1)") // PreferRW - resp, err = connPool.Insert(spaceName, []interface{}{"preferRW_insert_key", "preferRW_insert_value"}) + resp, err = connPool.Insert(spaceName, + []interface{}{"preferRW_insert_key", "preferRW_insert_value"}) require.Nilf(t, err, "failed to Insert") require.NotNilf(t, resp, "response is nil after Insert") require.Equalf(t, len(resp.Data), 1, "response Body len != 1 after Insert") @@ -1791,7 +1804,9 @@ func TestUpsert(t *testing.T) { defer conn.Close() // Mode is `RW` by default, we have only one RW instance (servers[2]) - resp, err := connPool.Upsert(spaceName, []interface{}{"upsert_key", "upsert_value"}, []interface{}{[]interface{}{"=", 1, "new_value"}}) + resp, err := connPool.Upsert(spaceName, + []interface{}{"upsert_key", "upsert_value"}, + []interface{}{[]interface{}{"=", 1, "new_value"}}) require.Nilf(t, err, "failed to Upsert") require.NotNilf(t, resp, "response is nil after Upsert") @@ -1880,7 +1895,8 @@ func TestUpdate(t *testing.T) { require.Equalf(t, "update_value", value, "unexpected body of Insert (1)") // Mode is `RW` by default, we have only one RW instance (servers[2]) - resp, err = connPool.Update(spaceName, indexNo, []interface{}{"update_key"}, []interface{}{[]interface{}{"=", 1, "new_value"}}) + resp, err = connPool.Update(spaceName, indexNo, + []interface{}{"update_key"}, []interface{}{[]interface{}{"=", 1, "new_value"}}) require.Nilf(t, err, "failed to Update") require.NotNilf(t, resp, "response is nil after Update") @@ -2229,7 +2245,8 @@ func TestNewPrepared(t *testing.T) { defer connPool.Close() - stmt, err := connPool.NewPrepared("SELECT NAME0, NAME1 FROM SQL_TEST WHERE NAME0=:id AND NAME1=:name;", pool.RO) + stmt, err := connPool.NewPrepared( + "SELECT NAME0, NAME1 FROM SQL_TEST WHERE NAME0=:id AND NAME1=:name;", pool.RO) require.Nilf(t, err, "fail to prepare statement: %v", err) if connPool.GetPoolInfo()[stmt.Conn.Addr()].ConnRole != pool.ReplicaRole { @@ -2282,7 +2299,8 @@ func TestNewPrepared(t *testing.T) { } func TestDoWithStrangerConn(t *testing.T) { - expectedErr := fmt.Errorf("the passed connected request doesn't belong to the current connection or connection pool") + expectedErr := fmt.Errorf("the passed connected request doesn't belong to " + + "the current connection pool") roles := []bool{true, true, false, true, false} diff --git a/pool/connector_test.go b/pool/connector_test.go index 8a954fa6e..b667b0d34 100644 --- a/pool/connector_test.go +++ b/pool/connector_test.go @@ -136,7 +136,7 @@ type baseRequestMock struct { } var reqResp *tarantool.Response = &tarantool.Response{} -var reqErr error = errors.New("response error") +var errReq error = errors.New("response error") var reqFuture *tarantool.Future = &tarantool.Future{} var reqFunctionName string = "any_name" @@ -166,7 +166,7 @@ func (m *getTypedMock) GetTyped(space, index, key interface{}, m.key = key m.result = result m.mode = mode[0] - return reqErr + return errReq } func TestConnectorGetTyped(t *testing.T) { @@ -175,7 +175,7 @@ func TestConnectorGetTyped(t *testing.T) { err := c.GetTyped(reqSpace, reqIndex, reqKey, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqIndex, m.index, "unexpected index was passed") @@ -199,7 +199,7 @@ func (m *selectMock) Select(space, index interface{}, m.iterator = iterator m.key = key m.mode = mode[0] - return reqResp, reqErr + return reqResp, errReq } func TestConnectorSelect(t *testing.T) { @@ -209,7 +209,7 @@ func TestConnectorSelect(t *testing.T) { resp, err := c.Select(reqSpace, reqIndex, reqOffset, reqLimit, reqIterator, reqKey) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqIndex, m.index, "unexpected index was passed") @@ -236,7 +236,7 @@ func (m *selectTypedMock) SelectTyped(space, index interface{}, m.key = key m.result = result m.mode = mode[0] - return reqErr + return errReq } func TestConnectorSelectTyped(t *testing.T) { @@ -246,7 +246,7 @@ func TestConnectorSelectTyped(t *testing.T) { err := c.SelectTyped(reqSpace, reqIndex, reqOffset, reqLimit, reqIterator, reqKey, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqIndex, m.index, "unexpected index was passed") @@ -304,7 +304,7 @@ func (m *insertMock) Insert(space, tuple interface{}, m.space = space m.tuple = tuple m.mode = mode[0] - return reqResp, reqErr + return reqResp, errReq } func TestConnectorInsert(t *testing.T) { @@ -314,7 +314,7 @@ func TestConnectorInsert(t *testing.T) { resp, err := c.Insert(reqSpace, reqTuple) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqTuple, m.tuple, "unexpected tuple was passed") @@ -332,7 +332,7 @@ func (m *insertTypedMock) InsertTyped(space, tuple interface{}, m.tuple = tuple m.result = result m.mode = mode[0] - return reqErr + return errReq } func TestConnectorInsertTyped(t *testing.T) { @@ -341,7 +341,7 @@ func TestConnectorInsertTyped(t *testing.T) { err := c.InsertTyped(reqSpace, reqTuple, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqTuple, m.tuple, "unexpected tuple was passed") @@ -385,7 +385,7 @@ func (m *replaceMock) Replace(space, tuple interface{}, m.space = space m.tuple = tuple m.mode = mode[0] - return reqResp, reqErr + return reqResp, errReq } func TestConnectorReplace(t *testing.T) { @@ -395,7 +395,7 @@ func TestConnectorReplace(t *testing.T) { resp, err := c.Replace(reqSpace, reqTuple) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqTuple, m.tuple, "unexpected tuple was passed") @@ -413,7 +413,7 @@ func (m *replaceTypedMock) ReplaceTyped(space, tuple interface{}, m.tuple = tuple m.result = result m.mode = mode[0] - return reqErr + return errReq } func TestConnectorReplaceTyped(t *testing.T) { @@ -422,7 +422,7 @@ func TestConnectorReplaceTyped(t *testing.T) { err := c.ReplaceTyped(reqSpace, reqTuple, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqTuple, m.tuple, "unexpected tuple was passed") @@ -467,7 +467,7 @@ func (m *deleteMock) Delete(space, index, key interface{}, m.index = index m.key = key m.mode = mode[0] - return reqResp, reqErr + return reqResp, errReq } func TestConnectorDelete(t *testing.T) { @@ -477,7 +477,7 @@ func TestConnectorDelete(t *testing.T) { resp, err := c.Delete(reqSpace, reqIndex, reqKey) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqIndex, m.index, "unexpected index was passed") @@ -497,7 +497,7 @@ func (m *deleteTypedMock) DeleteTyped(space, index, key interface{}, m.key = key m.result = result m.mode = mode[0] - return reqErr + return errReq } func TestConnectorDeleteTyped(t *testing.T) { @@ -506,7 +506,7 @@ func TestConnectorDeleteTyped(t *testing.T) { err := c.DeleteTyped(reqSpace, reqIndex, reqKey, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqIndex, m.index, "unexpected index was passed") @@ -555,7 +555,7 @@ func (m *updateMock) Update(space, index, key, ops interface{}, m.key = key m.ops = ops m.mode = mode[0] - return reqResp, reqErr + return reqResp, errReq } func TestConnectorUpdate(t *testing.T) { @@ -565,7 +565,7 @@ func TestConnectorUpdate(t *testing.T) { resp, err := c.Update(reqSpace, reqIndex, reqKey, reqOps) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqIndex, m.index, "unexpected index was passed") @@ -587,7 +587,7 @@ func (m *updateTypedMock) UpdateTyped(space, index, key, ops interface{}, m.ops = ops m.result = result m.mode = mode[0] - return reqErr + return errReq } func TestConnectorUpdateTyped(t *testing.T) { @@ -596,7 +596,7 @@ func TestConnectorUpdateTyped(t *testing.T) { err := c.UpdateTyped(reqSpace, reqIndex, reqKey, reqOps, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqIndex, m.index, "unexpected index was passed") @@ -647,7 +647,7 @@ func (m *upsertMock) Upsert(space, tuple, ops interface{}, m.tuple = tuple m.ops = ops m.mode = mode[0] - return reqResp, reqErr + return reqResp, errReq } func TestConnectorUpsert(t *testing.T) { @@ -657,7 +657,7 @@ func TestConnectorUpsert(t *testing.T) { resp, err := c.Upsert(reqSpace, reqTuple, reqOps) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqSpace, m.space, "unexpected space was passed") require.Equalf(t, reqTuple, m.tuple, "unexpected tuple was passed") @@ -703,7 +703,7 @@ func (m *baseCallMock) call(functionName string, args interface{}, m.functionName = functionName m.args = args m.mode = mode - return reqResp, reqErr + return reqResp, errReq } func (m *baseCallMock) callTyped(functionName string, args interface{}, @@ -713,7 +713,7 @@ func (m *baseCallMock) callTyped(functionName string, args interface{}, m.args = args m.result = result m.mode = mode - return reqErr + return errReq } func (m *baseCallMock) callAsync(functionName string, args interface{}, @@ -741,7 +741,7 @@ func TestConnectorCall(t *testing.T) { resp, err := c.Call(reqFunctionName, reqArgs) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected functionName was passed") @@ -764,7 +764,7 @@ func TestConnectorCallTyped(t *testing.T) { err := c.CallTyped(reqFunctionName, reqArgs, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected functionName was passed") @@ -812,7 +812,7 @@ func TestConnectorCall16(t *testing.T) { resp, err := c.Call16(reqFunctionName, reqArgs) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected functionName was passed") @@ -835,7 +835,7 @@ func TestConnectorCall16Typed(t *testing.T) { err := c.Call16Typed(reqFunctionName, reqArgs, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected functionName was passed") @@ -883,7 +883,7 @@ func TestConnectorCall17(t *testing.T) { resp, err := c.Call17(reqFunctionName, reqArgs) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected functionName was passed") @@ -906,7 +906,7 @@ func TestConnectorCall17Typed(t *testing.T) { err := c.Call17Typed(reqFunctionName, reqArgs, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected functionName was passed") @@ -954,7 +954,7 @@ func TestConnectorEval(t *testing.T) { resp, err := c.Eval(reqFunctionName, reqArgs) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected expr was passed") @@ -977,7 +977,7 @@ func TestConnectorEvalTyped(t *testing.T) { err := c.EvalTyped(reqFunctionName, reqArgs, reqResult) - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected expr was passed") @@ -1025,7 +1025,7 @@ func TestConnectorExecute(t *testing.T) { resp, err := c.Execute(reqFunctionName, reqArgs) require.Equalf(t, reqResp, resp, "unexpected response") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected expr was passed") @@ -1040,7 +1040,7 @@ type executeTypedMock struct { func (m *executeTypedMock) ExecuteTyped(functionName string, args, result interface{}, mode Mode) (tarantool.SQLInfo, []tarantool.ColumnMetaData, error) { m.callTyped(functionName, args, result, mode) - return reqSqlInfo, reqMeta, reqErr + return reqSqlInfo, reqMeta, errReq } func TestConnectorExecuteTyped(t *testing.T) { @@ -1051,7 +1051,7 @@ func TestConnectorExecuteTyped(t *testing.T) { require.Equalf(t, reqSqlInfo, info, "unexpected info") require.Equalf(t, reqMeta, meta, "unexpected meta") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.functionName, "unexpected expr was passed") @@ -1097,7 +1097,7 @@ func (m *newPreparedMock) NewPrepared(expr string, m.called++ m.expr = expr m.mode = mode - return reqPrepared, reqErr + return reqPrepared, errReq } func TestConnectorNewPrepared(t *testing.T) { @@ -1107,7 +1107,7 @@ func TestConnectorNewPrepared(t *testing.T) { p, err := c.NewPrepared(reqFunctionName) require.Equalf(t, reqPrepared, p, "unexpected prepared") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqFunctionName, m.expr, "unexpected expr was passed") @@ -1125,7 +1125,7 @@ type newStreamMock struct { func (m *newStreamMock) NewStream(mode Mode) (*tarantool.Stream, error) { m.called++ m.mode = mode - return reqStream, reqErr + return reqStream, errReq } func TestConnectorNewStream(t *testing.T) { @@ -1135,7 +1135,7 @@ func TestConnectorNewStream(t *testing.T) { s, err := c.NewStream() require.Equalf(t, reqStream, s, "unexpected stream") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, testMode, m.mode, "unexpected proxy mode") } @@ -1162,7 +1162,7 @@ func (m *newWatcherMock) NewWatcher(key string, m.key = key m.callback = callback m.mode = mode - return reqWatcher, reqErr + return reqWatcher, errReq } func TestConnectorNewWatcher(t *testing.T) { @@ -1172,7 +1172,7 @@ func TestConnectorNewWatcher(t *testing.T) { w, err := c.NewWatcher(reqWatchKey, func(event tarantool.WatchEvent) {}) require.Equalf(t, reqWatcher, w, "unexpected watcher") - require.Equalf(t, reqErr, err, "unexpected error") + require.Equalf(t, errReq, err, "unexpected error") require.Equalf(t, 1, m.called, "should be called only once") require.Equalf(t, reqWatchKey, m.key, "unexpected key") require.NotNilf(t, m.callback, "callback must be set") diff --git a/queue/example_msgpack_test.go b/queue/example_msgpack_test.go index ff37c1879..6fd101e09 100644 --- a/queue/example_msgpack_test.go +++ b/queue/example_msgpack_test.go @@ -76,21 +76,23 @@ func Example_simpleQueueCustomMsgPack() { que := queue.New(conn, "test_queue_msgpack") if err = que.Create(cfg); err != nil { - log.Fatalf("queue create: %s", err) + fmt.Printf("queue create: %s", err) return } // Put data. task, err := que.Put("test_data") if err != nil { - log.Fatalf("put task: %s", err) + fmt.Printf("put task: %s", err) + return } fmt.Println("Task id is", task.Id()) // Take data. task, err = que.Take() // Blocking operation. if err != nil { - log.Fatalf("take task: %s", err) + fmt.Printf("take task: %s", err) + return } fmt.Println("Data is", task.Data()) task.Ack() @@ -100,7 +102,8 @@ func Example_simpleQueueCustomMsgPack() { // Put data. task, err = que.Put(&putData) if err != nil { - log.Fatalf("put typed task: %s", err) + fmt.Printf("put typed task: %s", err) + return } fmt.Println("Task id is ", task.Id()) @@ -108,7 +111,8 @@ func Example_simpleQueueCustomMsgPack() { // Take data. task, err = que.TakeTyped(&takeData) // Blocking operation. if err != nil { - log.Fatalf("take take typed: %s", err) + fmt.Printf("take take typed: %s", err) + return } fmt.Println("Data is ", takeData) // Same data. @@ -116,13 +120,15 @@ func Example_simpleQueueCustomMsgPack() { task, err = que.Put([]int{1, 2, 3}) if err != nil { - log.Fatalf("Put failed: %s", err) + fmt.Printf("Put failed: %s", err) + return } task.Bury() task, err = que.TakeTimeout(2 * time.Second) if err != nil { - log.Fatalf("Take with timeout failed: %s", err) + fmt.Printf("Take with timeout failed: %s", err) + return } if task == nil { fmt.Println("Task is nil") diff --git a/queue/queue_test.go b/queue/queue_test.go index 313032f49..575ce78a0 100644 --- a/queue/queue_test.go +++ b/queue/queue_test.go @@ -129,7 +129,7 @@ func TestQueue_ReIdentify(t *testing.T) { if newuuid.String() != uuid.String() { t.Fatalf("Unequal UUIDs after re-identify: %s, expected %s", newuuid, uuid) } - //Put + // Put. putData := "put_data" task, err := q.Put(putData) if err != nil { @@ -137,13 +137,11 @@ func TestQueue_ReIdentify(t *testing.T) { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } - //Take + // Take. task, err = q.TakeTimeout(2 * time.Second) if err != nil { t.Fatalf("Failed take from queue: %s", err) @@ -157,7 +155,7 @@ func TestQueue_ReIdentify(t *testing.T) { conn = test_helpers.ConnectWithValidation(t, server, opts) q = queue.New(conn, name) - //Identify in another connection + // Identify in another connection. newuuid, err = q.Identify(&uuid) if err != nil { t.Fatalf("Failed to identify: %s", err) @@ -166,7 +164,7 @@ func TestQueue_ReIdentify(t *testing.T) { t.Fatalf("Unequal UUIDs after re-identify: %s, expected %s", newuuid, uuid) } - //Peek in another connection + // Peek in another connection. task, err = q.Peek(task.Id()) if err != nil { t.Fatalf("Failed take from queue: %s", err) @@ -174,7 +172,7 @@ func TestQueue_ReIdentify(t *testing.T) { t.Fatalf("Task is nil after take") } - //Ack in another connection + // Ack in another connection. err = task.Ack() if err != nil { t.Errorf("Failed ack %s", err) @@ -238,17 +236,15 @@ func TestFifoQueue_Put(t *testing.T) { q := createQueue(t, conn, name, queue.Cfg{Temporary: true, Kind: queue.FIFO}) defer dropQueue(t, q) - //Put + // Put. putData := "put_data" task, err := q.Put(putData) if err != nil { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } } @@ -260,20 +256,18 @@ func TestFifoQueue_Take(t *testing.T) { q := createQueue(t, conn, name, queue.Cfg{Temporary: true, Kind: queue.FIFO}) defer dropQueue(t, q) - //Put + // Put. putData := "put_data" task, err := q.Put(putData) if err != nil { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } - //Take + // Take. task, err = q.TakeTimeout(2 * time.Second) if err != nil { t.Errorf("Failed take from queue: %s", err) @@ -335,7 +329,7 @@ func TestFifoQueue_TakeTyped(t *testing.T) { q := createQueue(t, conn, name, queue.Cfg{Temporary: true, Kind: queue.FIFO}) defer dropQueue(t, q) - //Put + // Put. putData := &customData{customField: "put_data"} task, err := q.Put(putData) if err != nil { @@ -345,14 +339,16 @@ func TestFifoQueue_TakeTyped(t *testing.T) { } else { typedData, ok := task.Data().(*customData) if !ok { - t.Errorf("Task data after put has different type. %#v != %#v", task.Data(), putData) + t.Errorf("Task data after put has different type. %#v != %#v", + task.Data(), putData) } if *typedData != *putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) + t.Errorf("Task data after put not equal with example. %s != %s", + task.Data(), putData) } } - //Take + // Take. takeData := &customData{} task, err = q.TakeTypedTimeout(2*time.Second, takeData) if err != nil { @@ -362,23 +358,28 @@ func TestFifoQueue_TakeTyped(t *testing.T) { } else { typedData, ok := task.Data().(*customData) if !ok { - t.Errorf("Task data after put has different type. %#v != %#v", task.Data(), putData) + t.Errorf("Task data after put has different type. %#v != %#v", + task.Data(), putData) } if *typedData != *putData { - t.Errorf("Task data after take not equal with example. %#v != %#v", task.Data(), putData) + t.Errorf("Task data after take not equal with example. %#v != %#v", + task.Data(), putData) } if *takeData != *putData { - t.Errorf("Task data after take not equal with example. %#v != %#v", task.Data(), putData) + t.Errorf("Task data after take not equal with example. %#v != %#v", + task.Data(), putData) } if !task.IsTaken() { - t.Errorf("Task status after take is not taken. Status = %s", task.Status()) + t.Errorf("Task status after take is not taken. Status = %s", + task.Status()) } err = task.Ack() if err != nil { t.Errorf("Failed ack %s", err) } else if !task.IsDone() { - t.Errorf("Task status after take is not done. Status = %s", task.Status()) + t.Errorf("Task status after take is not done. Status = %s", + task.Status()) } } } @@ -391,33 +392,27 @@ func TestFifoQueue_Peek(t *testing.T) { q := createQueue(t, conn, name, queue.Cfg{Temporary: true, Kind: queue.FIFO}) defer dropQueue(t, q) - //Put + // Put. putData := "put_data" task, err := q.Put(putData) if err != nil { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } - //Peek + // Peek. task, err = q.Peek(task.Id()) if err != nil { t.Errorf("Failed peek from queue: %s", err) } else if task == nil { t.Errorf("Task is nil after peek") - } else { - if task.Data() != putData { - t.Errorf("Task data after peek not equal with example. %s != %s", task.Data(), putData) - } - - if !task.IsReady() { - t.Errorf("Task status after peek is not ready. Status = %s", task.Status()) - } + } else if task.Data() != putData { + t.Errorf("Task data after peek not equal with example. %s != %s", task.Data(), putData) + } else if !task.IsReady() { + t.Errorf("Task status after peek is not ready. Status = %s", task.Status()) } } @@ -429,20 +424,18 @@ func TestFifoQueue_Bury_Kick(t *testing.T) { q := createQueue(t, conn, name, queue.Cfg{Temporary: true, Kind: queue.FIFO}) defer dropQueue(t, q) - //Put + // Put. putData := "put_data" task, err := q.Put(putData) if err != nil { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } - //Bury + // Bury. err = task.Bury() if err != nil { t.Fatalf("Failed bury task %s", err) @@ -450,7 +443,7 @@ func TestFifoQueue_Bury_Kick(t *testing.T) { t.Errorf("Task status after bury is not buried. Status = %s", task.Status()) } - //Kick + // Kick. count, err := q.Kick(1) if err != nil { t.Fatalf("Failed kick task %s", err) @@ -458,7 +451,7 @@ func TestFifoQueue_Bury_Kick(t *testing.T) { t.Fatalf("Kick result != 1") } - //Take + // Take. task, err = q.TakeTimeout(2 * time.Second) if err != nil { t.Errorf("Failed take from queue: %s", err) @@ -492,7 +485,7 @@ func TestFifoQueue_Delete(t *testing.T) { q := createQueue(t, conn, name, queue.Cfg{Temporary: true, Kind: queue.FIFO}) defer dropQueue(t, q) - //Put + // Put. var putData = "put_data" var tasks = [2]*queue.Task{} @@ -502,14 +495,14 @@ func TestFifoQueue_Delete(t *testing.T) { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && tasks[i] == nil { t.Fatalf("Task is nil after put") - } else { - if tasks[i].Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", tasks[i].Data(), putData) - } + } else if tasks[i].Data() != putData { + t.Errorf( + "Task data after put not equal with example. %s != %s", + tasks[i].Data(), putData) } } - //Delete by task method + // Delete by task method. err = tasks[0].Delete() if err != nil { t.Fatalf("Failed bury task %s", err) @@ -517,7 +510,7 @@ func TestFifoQueue_Delete(t *testing.T) { t.Errorf("Task status after delete is not done. Status = %s", tasks[0].Status()) } - //Delete by task ID + // Delete by task ID. err = q.Delete(tasks[1].Id()) if err != nil { t.Fatalf("Failed bury task %s", err) @@ -525,7 +518,7 @@ func TestFifoQueue_Delete(t *testing.T) { t.Errorf("Task status after delete is not done. Status = %s", tasks[0].Status()) } - //Take + // Take. for i := 0; i < 2; i++ { tasks[i], err = q.TakeTimeout(2 * time.Second) if err != nil { @@ -550,13 +543,11 @@ func TestFifoQueue_Release(t *testing.T) { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } - //Take + // Take. task, err = q.Take() if err != nil { t.Fatalf("Failed take from queue: %s", err) @@ -564,7 +555,7 @@ func TestFifoQueue_Release(t *testing.T) { t.Fatal("Task is nil after take") } - //Release + // Release. err = task.Release() if err != nil { t.Fatalf("Failed release task %s", err) @@ -574,7 +565,7 @@ func TestFifoQueue_Release(t *testing.T) { t.Fatalf("Task status is not ready, but %s", task.Status()) } - //Take + // Take. task, err = q.Take() if err != nil { t.Fatalf("Failed take from queue: %s", err) @@ -612,13 +603,11 @@ func TestQueue_ReleaseAll(t *testing.T) { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } - //Take + // Take. task, err = q.Take() if err != nil { t.Fatalf("Failed take from queue: %s", err) @@ -626,7 +615,7 @@ func TestQueue_ReleaseAll(t *testing.T) { t.Fatal("Task is nil after take") } - //ReleaseAll + // ReleaseAll. err = q.ReleaseAll() if err != nil { t.Fatalf("Failed release task %s", err) @@ -640,7 +629,7 @@ func TestQueue_ReleaseAll(t *testing.T) { t.Fatalf("Task status is not ready, but %s", task.Status()) } - //Take + // Take. task, err = q.Take() if err != nil { t.Fatalf("Failed take from queue: %s", err) @@ -683,15 +672,13 @@ func TestTtlQueue(t *testing.T) { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } time.Sleep(10 * time.Second) - //Take + // Take. task, err = q.TakeTimeout(2 * time.Second) if err != nil { t.Errorf("Failed take from queue: %s", err) @@ -719,15 +706,13 @@ func TestTtlQueue_Put(t *testing.T) { t.Fatalf("Failed put to queue: %s", err) } else if err == nil && task == nil { t.Fatalf("Task is nil after put") - } else { - if task.Data() != putData { - t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) - } + } else if task.Data() != putData { + t.Errorf("Task data after put not equal with example. %s != %s", task.Data(), putData) } time.Sleep(5 * time.Second) - //Take + // Take. task, err = q.TakeTimeout(2 * time.Second) if err != nil { t.Errorf("Failed take from queue: %s", err) @@ -819,7 +804,8 @@ func TestUtube_Put(t *testing.T) { timeSpent := math.Abs(float64(end.Sub(start) - 2*time.Second)) if timeSpent > float64(700*time.Millisecond) { - t.Fatalf("Blocking time is less than expected: actual = %.2fs, expected = 1s", end.Sub(start).Seconds()) + t.Fatalf("Blocking time is less than expected: actual = %.2fs, expected = 1s", + end.Sub(start).Seconds()) } } @@ -935,7 +921,8 @@ func runTestMain(m *testing.M) int { instances, err = test_helpers.StartTarantoolInstances(serversPool, nil, poolOpts) if err != nil { - log.Fatalf("Failed to prepare test tarantool pool: %s", err) + log.Printf("Failed to prepare test tarantool pool: %s", err) + return 1 } defer test_helpers.StopTarantoolInstances(instances) @@ -958,7 +945,8 @@ func runTestMain(m *testing.M) int { } if err != nil { - log.Fatalf("Failed to set roles in tarantool pool: %s", err) + log.Printf("Failed to set roles in tarantool pool: %s", err) + return 1 } return m.Run() } diff --git a/request.go b/request.go index 48c13e869..917c1fb6a 100644 --- a/request.go +++ b/request.go @@ -170,7 +170,7 @@ func fillPing(enc *msgpack.Encoder) error { // // Deprecated: the method will be removed in the next major version, // use a PingRequest object + Do() instead. -func (conn *Connection) Ping() (resp *Response, err error) { +func (conn *Connection) Ping() (*Response, error) { return conn.Do(NewPingRequest()).Get() } @@ -180,7 +180,8 @@ func (conn *Connection) Ping() (resp *Response, err error) { // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (conn *Connection) Select(space, index interface{}, offset, limit uint32, iterator Iter, key interface{}) (resp *Response, err error) { +func (conn *Connection) Select(space, index interface{}, offset, limit uint32, iterator Iter, + key interface{}) (*Response, error) { return conn.SelectAsync(space, index, offset, limit, iterator, key).Get() } @@ -191,7 +192,7 @@ func (conn *Connection) Select(space, index interface{}, offset, limit uint32, i // // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. -func (conn *Connection) Insert(space interface{}, tuple interface{}) (resp *Response, err error) { +func (conn *Connection) Insert(space interface{}, tuple interface{}) (*Response, error) { return conn.InsertAsync(space, tuple).Get() } @@ -202,7 +203,7 @@ func (conn *Connection) Insert(space interface{}, tuple interface{}) (resp *Resp // // Deprecated: the method will be removed in the next major version, // use a ReplaceRequest object + Do() instead. -func (conn *Connection) Replace(space interface{}, tuple interface{}) (resp *Response, err error) { +func (conn *Connection) Replace(space interface{}, tuple interface{}) (*Response, error) { return conn.ReplaceAsync(space, tuple).Get() } @@ -213,7 +214,7 @@ func (conn *Connection) Replace(space interface{}, tuple interface{}) (resp *Res // // Deprecated: the method will be removed in the next major version, // use a DeleteRequest object + Do() instead. -func (conn *Connection) Delete(space, index interface{}, key interface{}) (resp *Response, err error) { +func (conn *Connection) Delete(space, index interface{}, key interface{}) (*Response, error) { return conn.DeleteAsync(space, index, key).Get() } @@ -224,7 +225,7 @@ func (conn *Connection) Delete(space, index interface{}, key interface{}) (resp // // Deprecated: the method will be removed in the next major version, // use a UpdateRequest object + Do() instead. -func (conn *Connection) Update(space, index interface{}, key, ops interface{}) (resp *Response, err error) { +func (conn *Connection) Update(space, index interface{}, key, ops interface{}) (*Response, error) { return conn.UpdateAsync(space, index, key, ops).Get() } @@ -235,7 +236,7 @@ func (conn *Connection) Update(space, index interface{}, key, ops interface{}) ( // // Deprecated: the method will be removed in the next major version, // use a UpsertRequest object + Do() instead. -func (conn *Connection) Upsert(space interface{}, tuple, ops interface{}) (resp *Response, err error) { +func (conn *Connection) Upsert(space interface{}, tuple, ops interface{}) (*Response, error) { return conn.UpsertAsync(space, tuple, ops).Get() } @@ -246,7 +247,7 @@ func (conn *Connection) Upsert(space interface{}, tuple, ops interface{}) (resp // // Deprecated: the method will be removed in the next major version, // use a CallRequest object + Do() instead. -func (conn *Connection) Call(functionName string, args interface{}) (resp *Response, err error) { +func (conn *Connection) Call(functionName string, args interface{}) (*Response, error) { return conn.CallAsync(functionName, args).Get() } @@ -258,7 +259,7 @@ func (conn *Connection) Call(functionName string, args interface{}) (resp *Respo // // Deprecated: the method will be removed in the next major version, // use a Call16Request object + Do() instead. -func (conn *Connection) Call16(functionName string, args interface{}) (resp *Response, err error) { +func (conn *Connection) Call16(functionName string, args interface{}) (*Response, error) { return conn.Call16Async(functionName, args).Get() } @@ -269,7 +270,7 @@ func (conn *Connection) Call16(functionName string, args interface{}) (resp *Res // // Deprecated: the method will be removed in the next major version, // use a Call17Request object + Do() instead. -func (conn *Connection) Call17(functionName string, args interface{}) (resp *Response, err error) { +func (conn *Connection) Call17(functionName string, args interface{}) (*Response, error) { return conn.Call17Async(functionName, args).Get() } @@ -279,7 +280,7 @@ func (conn *Connection) Call17(functionName string, args interface{}) (resp *Res // // Deprecated: the method will be removed in the next major version, // use an EvalRequest object + Do() instead. -func (conn *Connection) Eval(expr string, args interface{}) (resp *Response, err error) { +func (conn *Connection) Eval(expr string, args interface{}) (*Response, error) { return conn.EvalAsync(expr, args).Get() } @@ -290,7 +291,7 @@ func (conn *Connection) Eval(expr string, args interface{}) (resp *Response, err // // Deprecated: the method will be removed in the next major version, // use an ExecuteRequest object + Do() instead. -func (conn *Connection) Execute(expr string, args interface{}) (resp *Response, err error) { +func (conn *Connection) Execute(expr string, args interface{}) (*Response, error) { return conn.ExecuteAsync(expr, args).Get() } @@ -310,7 +311,7 @@ func (s *single) DecodeMsgpack(d *msgpack.Decoder) error { return nil } if len != 1 { - return errors.New("Tarantool returns unexpected value for Select(limit=1)") + return errors.New("tarantool returns unexpected value for Select(limit=1)") } return d.Decode(s.res) } @@ -322,10 +323,10 @@ func (s *single) DecodeMsgpack(d *msgpack.Decoder) error { // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (conn *Connection) GetTyped(space, index interface{}, key interface{}, result interface{}) (err error) { +func (conn *Connection) GetTyped(space, index interface{}, key interface{}, + result interface{}) error { s := single{res: result} - err = conn.SelectAsync(space, index, 0, 1, IterEq, key).GetTyped(&s) - return + return conn.SelectAsync(space, index, 0, 1, IterEq, key).GetTyped(&s) } // SelectTyped performs select to box space and fills typed result. @@ -334,7 +335,8 @@ func (conn *Connection) GetTyped(space, index interface{}, key interface{}, resu // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (conn *Connection) SelectTyped(space, index interface{}, offset, limit uint32, iterator Iter, key interface{}, result interface{}) (err error) { +func (conn *Connection) SelectTyped(space, index interface{}, offset, limit uint32, iterator Iter, + key interface{}, result interface{}) error { return conn.SelectAsync(space, index, offset, limit, iterator, key).GetTyped(result) } @@ -345,7 +347,8 @@ func (conn *Connection) SelectTyped(space, index interface{}, offset, limit uint // // Deprecated: the method will be removed in the next major version, // use an InsertRequest object + Do() instead. -func (conn *Connection) InsertTyped(space interface{}, tuple interface{}, result interface{}) (err error) { +func (conn *Connection) InsertTyped(space interface{}, tuple interface{}, + result interface{}) error { return conn.InsertAsync(space, tuple).GetTyped(result) } @@ -356,7 +359,8 @@ func (conn *Connection) InsertTyped(space interface{}, tuple interface{}, result // // Deprecated: the method will be removed in the next major version, // use a ReplaceRequest object + Do() instead. -func (conn *Connection) ReplaceTyped(space interface{}, tuple interface{}, result interface{}) (err error) { +func (conn *Connection) ReplaceTyped(space interface{}, tuple interface{}, + result interface{}) error { return conn.ReplaceAsync(space, tuple).GetTyped(result) } @@ -366,7 +370,8 @@ func (conn *Connection) ReplaceTyped(space interface{}, tuple interface{}, resul // // Deprecated: the method will be removed in the next major version, // use a DeleteRequest object + Do() instead. -func (conn *Connection) DeleteTyped(space, index interface{}, key interface{}, result interface{}) (err error) { +func (conn *Connection) DeleteTyped(space, index interface{}, key interface{}, + result interface{}) error { return conn.DeleteAsync(space, index, key).GetTyped(result) } @@ -376,7 +381,8 @@ func (conn *Connection) DeleteTyped(space, index interface{}, key interface{}, r // // Deprecated: the method will be removed in the next major version, // use a UpdateRequest object + Do() instead. -func (conn *Connection) UpdateTyped(space, index interface{}, key, ops interface{}, result interface{}) (err error) { +func (conn *Connection) UpdateTyped(space, index interface{}, key, ops interface{}, + result interface{}) error { return conn.UpdateAsync(space, index, key, ops).GetTyped(result) } @@ -387,7 +393,8 @@ func (conn *Connection) UpdateTyped(space, index interface{}, key, ops interface // // Deprecated: the method will be removed in the next major version, // use a CallRequest object + Do() instead. -func (conn *Connection) CallTyped(functionName string, args interface{}, result interface{}) (err error) { +func (conn *Connection) CallTyped(functionName string, args interface{}, + result interface{}) error { return conn.CallAsync(functionName, args).GetTyped(result) } @@ -399,7 +406,8 @@ func (conn *Connection) CallTyped(functionName string, args interface{}, result // // Deprecated: the method will be removed in the next major version, // use a Call16Request object + Do() instead. -func (conn *Connection) Call16Typed(functionName string, args interface{}, result interface{}) (err error) { +func (conn *Connection) Call16Typed(functionName string, args interface{}, + result interface{}) error { return conn.Call16Async(functionName, args).GetTyped(result) } @@ -410,7 +418,8 @@ func (conn *Connection) Call16Typed(functionName string, args interface{}, resul // // Deprecated: the method will be removed in the next major version, // use a Call17Request object + Do() instead. -func (conn *Connection) Call17Typed(functionName string, args interface{}, result interface{}) (err error) { +func (conn *Connection) Call17Typed(functionName string, args interface{}, + result interface{}) error { return conn.Call17Async(functionName, args).GetTyped(result) } @@ -420,7 +429,7 @@ func (conn *Connection) Call17Typed(functionName string, args interface{}, resul // // Deprecated: the method will be removed in the next major version, // use an EvalRequest object + Do() instead. -func (conn *Connection) EvalTyped(expr string, args interface{}, result interface{}) (err error) { +func (conn *Connection) EvalTyped(expr string, args interface{}, result interface{}) error { return conn.EvalAsync(expr, args).GetTyped(result) } @@ -431,7 +440,8 @@ func (conn *Connection) EvalTyped(expr string, args interface{}, result interfac // // Deprecated: the method will be removed in the next major version, // use an ExecuteRequest object + Do() instead. -func (conn *Connection) ExecuteTyped(expr string, args interface{}, result interface{}) (SQLInfo, []ColumnMetaData, error) { +func (conn *Connection) ExecuteTyped(expr string, args interface{}, + result interface{}) (SQLInfo, []ColumnMetaData, error) { fut := conn.ExecuteAsync(expr, args) err := fut.GetTyped(&result) return fut.resp.SQLInfo, fut.resp.MetaData, err @@ -441,7 +451,8 @@ func (conn *Connection) ExecuteTyped(expr string, args interface{}, result inter // // Deprecated: the method will be removed in the next major version, // use a SelectRequest object + Do() instead. -func (conn *Connection) SelectAsync(space, index interface{}, offset, limit uint32, iterator Iter, key interface{}) *Future { +func (conn *Connection) SelectAsync(space, index interface{}, offset, limit uint32, iterator Iter, + key interface{}) *Future { req := NewSelectRequest(space). Index(index). Offset(offset). @@ -497,7 +508,8 @@ func (conn *Connection) UpdateAsync(space, index interface{}, key, ops interface // // Deprecated: the method will be removed in the next major version, // use a UpsertRequest object + Do() instead. -func (conn *Connection) UpsertAsync(space interface{}, tuple interface{}, ops interface{}) *Future { +func (conn *Connection) UpsertAsync(space interface{}, tuple interface{}, + ops interface{}) *Future { req := NewUpsertRequest(space).Tuple(tuple) req.ops = ops return conn.Do(req) diff --git a/request_test.go b/request_test.go index a7e70ec65..f44b12d52 100644 --- a/request_test.go +++ b/request_test.go @@ -41,7 +41,8 @@ var validProtocolInfo ProtocolInfo = ProtocolInfo{ type ValidSchemeResolver struct { } -func (*ValidSchemeResolver) ResolveSpaceIndex(s, i interface{}) (spaceNo, indexNo uint32, err error) { +func (*ValidSchemeResolver) ResolveSpaceIndex(s, i interface{}) (uint32, uint32, error) { + var spaceNo, indexNo uint32 if s != nil { spaceNo = uint32(s.(int)) } else { diff --git a/response.go b/response.go index 897b6ce73..7ee314e04 100644 --- a/response.go +++ b/response.go @@ -257,12 +257,12 @@ func (resp *Response) decodeBody() (err error) { } // Tarantool may send only version >= 1 - if (serverProtocolInfo.Version != ProtocolVersion(0)) || (serverProtocolInfo.Features != nil) { + if serverProtocolInfo.Version != ProtocolVersion(0) || serverProtocolInfo.Features != nil { if serverProtocolInfo.Version == ProtocolVersion(0) { - return fmt.Errorf("No protocol version provided in Id response") + return fmt.Errorf("no protocol version provided in Id response") } if serverProtocolInfo.Features == nil { - return fmt.Errorf("No features provided in Id response") + return fmt.Errorf("no features provided in Id response") } resp.Data = []interface{}{serverProtocolInfo} } diff --git a/schema.go b/schema.go index af7dd21f5..714f51c5b 100644 --- a/schema.go +++ b/schema.go @@ -374,20 +374,21 @@ func (conn *Connection) loadSchema() (err error) { // ResolveSpaceIndex tries to resolve space and index numbers. // Note: s can be a number, string, or an object of Space type. // Note: i can be a number, string, or an object of Index type. -func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (spaceNo, indexNo uint32, err error) { - var space *Space - var index *Index - var ok bool +func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (uint32, uint32, error) { + var ( + spaceNo, indexNo uint32 + space *Space + index *Index + ok bool + ) switch s := s.(type) { case string: if schema == nil { - err = fmt.Errorf("Schema is not loaded") - return + return spaceNo, indexNo, fmt.Errorf("Schema is not loaded") } if space, ok = schema.Spaces[s]; !ok { - err = fmt.Errorf("there is no space with name %s", s) - return + return spaceNo, indexNo, fmt.Errorf("there is no space with name %s", s) } spaceNo = space.Id case uint: @@ -395,7 +396,7 @@ func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (spaceNo, case uint64: spaceNo = uint32(s) case uint32: - spaceNo = uint32(s) + spaceNo = s case uint16: spaceNo = uint32(s) case uint8: @@ -422,18 +423,16 @@ func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (spaceNo, switch i := i.(type) { case string: if schema == nil { - err = fmt.Errorf("Schema is not loaded") - return + return spaceNo, indexNo, fmt.Errorf("schema is not loaded") } if space == nil { if space, ok = schema.SpacesById[spaceNo]; !ok { - err = fmt.Errorf("there is no space with id %d", spaceNo) - return + return spaceNo, indexNo, fmt.Errorf("there is no space with id %d", spaceNo) } } if index, ok = space.Indexes[i]; !ok { - err = fmt.Errorf("space %s has not index with name %s", space.Name, i) - return + err := fmt.Errorf("space %s has not index with name %s", space.Name, i) + return spaceNo, indexNo, err } indexNo = index.Id case uint: @@ -441,7 +440,7 @@ func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (spaceNo, case uint64: indexNo = uint32(i) case uint32: - indexNo = uint32(i) + indexNo = i case uint16: indexNo = uint32(i) case uint8: @@ -465,5 +464,5 @@ func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (spaceNo, } } - return + return spaceNo, indexNo, nil } diff --git a/settings/request.go b/settings/request.go index ae54aebf3..02252fe47 100644 --- a/settings/request.go +++ b/settings/request.go @@ -54,7 +54,8 @@ // // See also: // -// * Session settings https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_space/_session_settings/ +// - Session settings: +// https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_space/_session_settings/ package settings import ( diff --git a/settings/request_test.go b/settings/request_test.go index 477795d2d..2438f81cc 100644 --- a/settings/request_test.go +++ b/settings/request_test.go @@ -16,7 +16,8 @@ import ( type ValidSchemeResolver struct { } -func (*ValidSchemeResolver) ResolveSpaceIndex(s, i interface{}) (spaceNo, indexNo uint32, err error) { +func (*ValidSchemeResolver) ResolveSpaceIndex(s, i interface{}) (uint32, uint32, error) { + var spaceNo, indexNo uint32 if s == nil { if s == "_session_settings" { spaceNo = 380 @@ -43,7 +44,8 @@ func TestRequestsAPI(t *testing.T) { async bool rtype iproto.Type }{ - {req: NewErrorMarshalingEnabledSetRequest(false), async: false, rtype: iproto.IPROTO_UPDATE}, + {req: NewErrorMarshalingEnabledSetRequest(false), async: false, + rtype: iproto.IPROTO_UPDATE}, {req: NewErrorMarshalingEnabledGetRequest(), async: false, rtype: iproto.IPROTO_SELECT}, {req: NewSQLDefaultEngineSetRequest("memtx"), async: false, rtype: iproto.IPROTO_UPDATE}, {req: NewSQLDefaultEngineGetRequest(), async: false, rtype: iproto.IPROTO_SELECT}, @@ -57,8 +59,10 @@ func TestRequestsAPI(t *testing.T) { {req: NewSQLParserDebugGetRequest(), async: false, rtype: iproto.IPROTO_SELECT}, {req: NewSQLRecursiveTriggersSetRequest(false), async: false, rtype: iproto.IPROTO_UPDATE}, {req: NewSQLRecursiveTriggersGetRequest(), async: false, rtype: iproto.IPROTO_SELECT}, - {req: NewSQLReverseUnorderedSelectsSetRequest(false), async: false, rtype: iproto.IPROTO_UPDATE}, - {req: NewSQLReverseUnorderedSelectsGetRequest(), async: false, rtype: iproto.IPROTO_SELECT}, + {req: NewSQLReverseUnorderedSelectsSetRequest(false), async: false, + rtype: iproto.IPROTO_UPDATE}, + {req: NewSQLReverseUnorderedSelectsGetRequest(), async: false, + rtype: iproto.IPROTO_SELECT}, {req: NewSQLSelectDebugSetRequest(false), async: false, rtype: iproto.IPROTO_UPDATE}, {req: NewSQLSelectDebugGetRequest(), async: false, rtype: iproto.IPROTO_SELECT}, {req: NewSQLVDBEDebugSetRequest(false), async: false, rtype: iproto.IPROTO_UPDATE}, diff --git a/settings/tarantool_test.go b/settings/tarantool_test.go index 128e84328..645d48c73 100644 --- a/settings/tarantool_test.go +++ b/settings/tarantool_test.go @@ -175,7 +175,8 @@ func TestSQLDeferForeignKeysSetting(t *testing.T) { require.Equal(t, uint64(1), resp.SQLInfo.AffectedCount) // Create a space with reference to the parent space. - exec = tarantool.NewExecuteRequest("CREATE TABLE child(id INT PRIMARY KEY, x INT REFERENCES parent(y));") + exec = tarantool.NewExecuteRequest( + "CREATE TABLE child(id INT PRIMARY KEY, x INT REFERENCES parent(y));") resp, err = conn.Do(exec).Get() require.Nil(t, err) require.NotNil(t, resp) @@ -440,7 +441,8 @@ func TestSQLRecursiveTriggersSetting(t *testing.T) { exec = tarantool.NewExecuteRequest("UPDATE rec SET a=a+1, b=b+1;") _, err = conn.Do(exec).Get() require.NotNil(t, err) - require.ErrorContains(t, err, "Failed to execute SQL statement: too many levels of trigger recursion") + require.ErrorContains(t, err, + "Failed to execute SQL statement: too many levels of trigger recursion") // Disable SQL recursive triggers. resp, err = conn.Do(NewSQLRecursiveTriggersSetRequest(false)).Get() @@ -495,13 +497,15 @@ func TestSQLReverseUnorderedSelectsSetting(t *testing.T) { resp, err = conn.Do(NewSQLReverseUnorderedSelectsSetRequest(false)).Get() require.Nil(t, err) require.NotNil(t, resp) - require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", false}}, resp.Data) + require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", false}}, + resp.Data) // Fetch current setting value. resp, err = conn.Do(NewSQLReverseUnorderedSelectsGetRequest()).Get() require.Nil(t, err) require.NotNil(t, resp) - require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", false}}, resp.Data) + require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", false}}, + resp.Data) // Select multiple records. query := "SELECT * FROM seqscan data;" @@ -521,13 +525,15 @@ func TestSQLReverseUnorderedSelectsSetting(t *testing.T) { resp, err = conn.Do(NewSQLReverseUnorderedSelectsSetRequest(true)).Get() require.Nil(t, err) require.NotNil(t, resp) - require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", true}}, resp.Data) + require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", true}}, + resp.Data) // Fetch current setting value. resp, err = conn.Do(NewSQLReverseUnorderedSelectsGetRequest()).Get() require.Nil(t, err) require.NotNil(t, resp) - require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", true}}, resp.Data) + require.Equal(t, []interface{}{[]interface{}{"sql_reverse_unordered_selects", true}}, + resp.Data) // Select multiple records. resp, err = conn.Do(tarantool.NewExecuteRequest(query)).Get() diff --git a/shutdown_test.go b/shutdown_test.go index 7a6843811..bb4cfa099 100644 --- a/shutdown_test.go +++ b/shutdown_test.go @@ -204,7 +204,8 @@ func TestGracefulShutdownWithReconnect(t *testing.T) { err = test_helpers.RestartTarantool(&inst) require.Nilf(t, err, "Failed to restart tarantool") - connected := test_helpers.WaitUntilReconnected(conn, shtdnClntOpts.MaxReconnects, shtdnClntOpts.Reconnect) + connected := test_helpers.WaitUntilReconnected(conn, shtdnClntOpts.MaxReconnects, + shtdnClntOpts.Reconnect) require.Truef(t, connected, "Reconnect success") testGracefulShutdown(t, conn, &inst) diff --git a/smallbuf.go b/smallbuf.go index a5b926835..a6590b409 100644 --- a/smallbuf.go +++ b/smallbuf.go @@ -34,7 +34,7 @@ func (s *smallBuf) ReadByte() (b byte, err error) { func (s *smallBuf) UnreadByte() error { if s.p == 0 { - return errors.New("Could not unread") + return errors.New("could not unread") } s.p-- return nil diff --git a/ssl_test.go b/ssl_test.go index 58d03fa73..12cab7304 100644 --- a/ssl_test.go +++ b/ssl_test.go @@ -66,7 +66,7 @@ func clientSsl(network, address string, opts SslOpts) (net.Conn, error) { } func createClientServerSsl(t testing.TB, serverOpts, - clientOpts SslOpts) (net.Listener, net.Conn, error, <-chan string, <-chan error) { + clientOpts SslOpts) (net.Listener, net.Conn, <-chan string, <-chan error, error) { t.Helper() l, err := serverSsl("tcp", sslHost+":0", serverOpts) @@ -79,14 +79,14 @@ func createClientServerSsl(t testing.TB, serverOpts, port := l.Addr().(*net.TCPAddr).Port c, err := clientSsl("tcp", sslHost+":"+strconv.Itoa(port), clientOpts) - return l, c, err, msgs, errs + return l, c, msgs, errs, err } func createClientServerSslOk(t testing.TB, serverOpts, clientOpts SslOpts) (net.Listener, net.Conn, <-chan string, <-chan error) { t.Helper() - l, c, err, msgs, errs := createClientServerSsl(t, serverOpts, clientOpts) + l, c, msgs, errs, err := createClientServerSsl(t, serverOpts, clientOpts) if err != nil { t.Fatalf("Unable to create client, error %q", err.Error()) } @@ -142,7 +142,7 @@ func serverTntStop(inst test_helpers.TarantoolInstance) { func assertConnectionSslFail(t testing.TB, serverOpts, clientOpts SslOpts) { t.Helper() - l, c, err, _, _ := createClientServerSsl(t, serverOpts, clientOpts) + l, c, _, _, err := createClientServerSsl(t, serverOpts, clientOpts) l.Close() if err == nil { c.Close() diff --git a/stream.go b/stream.go index 939840d19..5144ea6f1 100644 --- a/stream.go +++ b/stream.go @@ -2,7 +2,7 @@ package tarantool import ( "context" - "fmt" + "errors" "time" "github.com/tarantool/go-iproto" @@ -25,6 +25,11 @@ const ( BestEffortLevel TxnIsolationLevel = 3 ) +var ( + errUnknownStreamRequest = errors.New("the passed connected request doesn't belong " + + "to the current connection or connection pool") +) + type Stream struct { Id uint64 Conn *Connection @@ -195,7 +200,7 @@ func (s *Stream) Do(req Request) *Future { if connectedReq, ok := req.(ConnectedRequest); ok { if connectedReq.Conn() != s.Conn { fut := NewFuture() - fut.SetError(fmt.Errorf("the passed connected request doesn't belong to the current connection or connection pool")) + fut.SetError(errUnknownStreamRequest) return fut } } diff --git a/tarantool_test.go b/tarantool_test.go index d58a6775f..6339164f1 100644 --- a/tarantool_test.go +++ b/tarantool_test.go @@ -196,7 +196,8 @@ func BenchmarkClientSerialSQL(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - _, err := conn.Execute("SELECT NAME0,NAME1,NAME2 FROM SQL_TEST WHERE NAME0=?", []interface{}{uint(1111)}) + _, err := conn.Execute("SELECT NAME0,NAME1,NAME2 FROM SQL_TEST WHERE NAME0=?", + []interface{}{uint(1111)}) if err != nil { b.Errorf("Select failed: %s", err.Error()) break @@ -614,7 +615,8 @@ func BenchmarkClientLargeSelectParallel(b *testing.B) { b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { - _, err := conn.Select(rSpaceNo, rIndexNo, offset, limit, IterEq, []interface{}{"test_name"}) + _, err := conn.Select(rSpaceNo, rIndexNo, offset, limit, IterEq, + []interface{}{"test_name"}) if err != nil { b.Fatal(err) } @@ -636,7 +638,8 @@ func BenchmarkClientParallelSQL(b *testing.B) { b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { - _, err := conn.Execute("SELECT NAME0,NAME1,NAME2 FROM SQL_TEST WHERE NAME0=?", []interface{}{uint(1111)}) + _, err := conn.Execute("SELECT NAME0,NAME1,NAME2 FROM SQL_TEST WHERE NAME0=?", + []interface{}{uint(1111)}) if err != nil { b.Errorf("Select failed: %s", err.Error()) break @@ -692,7 +695,8 @@ func BenchmarkSQLSerial(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - _, err := conn.Execute("SELECT NAME0,NAME1,NAME2 FROM SQL_TEST WHERE NAME0=?", []interface{}{uint(1111)}) + _, err := conn.Execute("SELECT NAME0,NAME1,NAME2 FROM SQL_TEST WHERE NAME0=?", + []interface{}{uint(1111)}) if err != nil { b.Errorf("Select failed: %s", err.Error()) break @@ -909,7 +913,6 @@ func TestClient(t *testing.T) { t.Errorf("Unexpected body of Insert (1)") } } - //resp, err = conn.Insert(spaceNo, []interface{}{uint(1), "hello", "world"}) resp, err = conn.Insert(spaceNo, &Tuple{Id: 1, Msg: "hello", Name: "world"}) if tntErr, ok := err.(Error); !ok || tntErr.Code != iproto.ER_TUPLE_FOUND { t.Errorf("Expected %s but got: %v", iproto.ER_TUPLE_FOUND, err) @@ -995,7 +998,8 @@ func TestClient(t *testing.T) { } // Update - resp, err = conn.Update(spaceNo, indexNo, []interface{}{uint(2)}, []interface{}{[]interface{}{"=", 1, "bye"}, []interface{}{"#", 2, 1}}) + resp, err = conn.Update(spaceNo, indexNo, []interface{}{uint(2)}, + []interface{}{[]interface{}{"=", 1, "bye"}, []interface{}{"#", 2, 1}}) if err != nil { t.Fatalf("Failed to Update: %s", err.Error()) } @@ -1023,7 +1027,8 @@ func TestClient(t *testing.T) { } // Upsert - resp, err = conn.Upsert(spaceNo, []interface{}{uint(3), 1}, []interface{}{[]interface{}{"+", 1, 1}}) + resp, err = conn.Upsert(spaceNo, []interface{}{uint(3), 1}, + []interface{}{[]interface{}{"+", 1, 1}}) if err != nil { t.Fatalf("Failed to Upsert (insert): %s", err.Error()) } @@ -1033,7 +1038,8 @@ func TestClient(t *testing.T) { if resp.Pos != nil { t.Errorf("Response should not have a position") } - resp, err = conn.Upsert(spaceNo, []interface{}{uint(3), 1}, []interface{}{[]interface{}{"+", 1, 1}}) + resp, err = conn.Upsert(spaceNo, []interface{}{uint(3), 1}, + []interface{}{[]interface{}{"+", 1, 1}}) if err != nil { t.Fatalf("Failed to Upsert (update): %s", err.Error()) } @@ -1101,10 +1107,8 @@ func TestClient(t *testing.T) { } if len(tpl) != 1 { t.Errorf("Result len of SelectTyped != 1") - } else { - if tpl[0].Id != 10 { - t.Errorf("Bad value loaded from SelectTyped") - } + } else if tpl[0].Id != 10 { + t.Errorf("Bad value loaded from SelectTyped") } // Get Typed @@ -1125,10 +1129,8 @@ func TestClient(t *testing.T) { } if len(tpl) != 1 { t.Errorf("Result len of SelectTyped != 1") - } else { - if tpl[0].Id != 10 { - t.Errorf("Bad value loaded from SelectTyped") - } + } else if tpl[0].Id != 10 { + t.Errorf("Bad value loaded from SelectTyped") } // Get Typed Empty @@ -1280,12 +1282,14 @@ func TestClientSessionPush(t *testing.T) { } if resp.Code == PushCode { pushCnt += 1 - if val, err := test_helpers.ConvertUint64(resp.Data[0]); err != nil || val != pushCnt { + val, err := test_helpers.ConvertUint64(resp.Data[0]) + if err != nil || val != pushCnt { t.Errorf("Unexpected push data = %v", resp.Data) } } else { respCnt += 1 - if val, err := test_helpers.ConvertUint64(resp.Data[0]); err != nil || val != pushMax { + val, err := test_helpers.ConvertUint64(resp.Data[0]) + if err != nil || val != pushMax { t.Errorf("Result is not %d: %v", pushMax, resp.Data) } } @@ -1309,7 +1313,9 @@ func TestClientSessionPush(t *testing.T) { resp, err := fut.Get() if err != nil { t.Errorf("Unable to call fut.Get(): %s", err) - } else if val, err := test_helpers.ConvertUint64(resp.Data[0]); err != nil || val != pushMax { + } + val, err := test_helpers.ConvertUint64(resp.Data[0]) + if err != nil || val != pushMax { t.Errorf("Result is not %d: %v", pushMax, resp.Data) } @@ -1326,7 +1332,8 @@ func TestClientSessionPush(t *testing.T) { } const ( - createTableQuery = "CREATE TABLE SQL_SPACE (id STRING PRIMARY KEY, name STRING COLLATE \"unicode\" DEFAULT NULL);" + createTableQuery = "CREATE TABLE SQL_SPACE (id STRING PRIMARY KEY, name " + + "STRING COLLATE \"unicode\" DEFAULT NULL);" insertQuery = "INSERT INTO SQL_SPACE VALUES (?, ?);" selectNamedQuery = "SELECT id, name FROM SQL_SPACE WHERE id=:id AND name=:name;" selectPosQuery = "SELECT id, name FROM SQL_SPACE WHERE id=? AND name=?;" @@ -1429,7 +1436,8 @@ func TestSQL(t *testing.T) { selectSpanDifQuery, []interface{}{"test_test"}, Response{ - SQLInfo: SQLInfo{AffectedCount: 0}, Data: []interface{}{[]interface{}{"11", "test_test", "1"}}, + SQLInfo: SQLInfo{AffectedCount: 0}, + Data: []interface{}{[]interface{}{"11", "test_test", "1"}}, MetaData: []ColumnMetaData{ { FieldType: "string", @@ -1513,13 +1521,17 @@ func TestSQL(t *testing.T) { for j := range resp.Data { assert.Equal(t, resp.Data[j], test.Resp.Data[j], "Response data is wrong") } - assert.Equal(t, resp.SQLInfo.AffectedCount, test.Resp.SQLInfo.AffectedCount, "Affected count is wrong") + assert.Equal(t, resp.SQLInfo.AffectedCount, test.Resp.SQLInfo.AffectedCount, + "Affected count is wrong") errorMsg := "Response Metadata is wrong" for j := range resp.MetaData { - assert.Equal(t, resp.MetaData[j].FieldIsAutoincrement, test.Resp.MetaData[j].FieldIsAutoincrement, errorMsg) - assert.Equal(t, resp.MetaData[j].FieldIsNullable, test.Resp.MetaData[j].FieldIsNullable, errorMsg) - assert.Equal(t, resp.MetaData[j].FieldCollation, test.Resp.MetaData[j].FieldCollation, errorMsg) + assert.Equal(t, resp.MetaData[j].FieldIsAutoincrement, + test.Resp.MetaData[j].FieldIsAutoincrement, errorMsg) + assert.Equal(t, resp.MetaData[j].FieldIsNullable, + test.Resp.MetaData[j].FieldIsNullable, errorMsg) + assert.Equal(t, resp.MetaData[j].FieldCollation, + test.Resp.MetaData[j].FieldCollation, errorMsg) assert.Equal(t, resp.MetaData[j].FieldName, test.Resp.MetaData[j].FieldName, errorMsg) assert.Equal(t, resp.MetaData[j].FieldSpan, test.Resp.MetaData[j].FieldSpan, errorMsg) assert.Equal(t, resp.MetaData[j].FieldType, test.Resp.MetaData[j].FieldType, errorMsg) @@ -1591,7 +1603,7 @@ func TestSQLBindings(t *testing.T) { sqlBind4, } - //positioned sql bind + // positioned sql bind sqlBind5 := []interface{}{ 1, "test", } @@ -1831,7 +1843,8 @@ func TestNewPrepared(t *testing.T) { } func TestConnection_DoWithStrangerConn(t *testing.T) { - expectedErr := fmt.Errorf("the passed connected request doesn't belong to the current connection or connection pool") + expectedErr := fmt.Errorf("the passed connected request doesn't belong to the current" + + " connection or connection pool") conn1 := &Connection{} req := test_helpers.NewStrangerRequest() @@ -2014,7 +2027,8 @@ func TestSchema(t *testing.T) { if ifield1.Id != 1 || ifield2.Id != 2 { t.Errorf("index field has incorrect Id") } - if (ifield1.Type != "num" && ifield1.Type != "unsigned") || (ifield2.Type != "STR" && ifield2.Type != "string") { + if (ifield1.Type != "num" && ifield1.Type != "unsigned") || + (ifield2.Type != "STR" && ifield2.Type != "string") { t.Errorf("index field has incorrect Type '%s'", ifield2.Type) } @@ -2113,7 +2127,10 @@ func TestClientNamed(t *testing.T) { } // Update - resp, err = conn.Update(spaceName, indexName, []interface{}{uint(1002)}, []interface{}{[]interface{}{"=", 1, "bye"}, []interface{}{"#", 2, 1}}) + resp, err = conn.Update(spaceName, indexName, + []interface{}{ + uint(1002)}, + []interface{}{[]interface{}{"=", 1, "bye"}, []interface{}{"#", 2, 1}}) if err != nil { t.Fatalf("Failed to Update: %s", err.Error()) } @@ -2122,14 +2139,16 @@ func TestClientNamed(t *testing.T) { } // Upsert - resp, err = conn.Upsert(spaceName, []interface{}{uint(1003), 1}, []interface{}{[]interface{}{"+", 1, 1}}) + resp, err = conn.Upsert(spaceName, + []interface{}{uint(1003), 1}, []interface{}{[]interface{}{"+", 1, 1}}) if err != nil { t.Fatalf("Failed to Upsert (insert): %s", err.Error()) } if resp == nil { t.Errorf("Response is nil after Upsert (insert)") } - resp, err = conn.Upsert(spaceName, []interface{}{uint(1003), 1}, []interface{}{[]interface{}{"+", 1, 1}}) + resp, err = conn.Upsert(spaceName, + []interface{}{uint(1003), 1}, []interface{}{[]interface{}{"+", 1, 1}}) if err != nil { t.Fatalf("Failed to Upsert (update): %s", err.Error()) } @@ -2139,7 +2158,8 @@ func TestClientNamed(t *testing.T) { // Select for i := 1010; i < 1020; i++ { - resp, err = conn.Replace(spaceName, []interface{}{uint(i), fmt.Sprintf("val %d", i), "bla"}) + resp, err = conn.Replace(spaceName, + []interface{}{uint(i), fmt.Sprintf("val %d", i), "bla"}) if err != nil { t.Fatalf("Failed to Replace: %s", err.Error()) } @@ -2795,7 +2815,9 @@ func TestComplexStructs(t *testing.T) { return } - if tuple.Cid != tuples[0].Cid || len(tuple.Members) != len(tuples[0].Members) || tuple.Members[1].Name != tuples[0].Members[1].Name { + if tuple.Cid != tuples[0].Cid || + len(tuple.Members) != len(tuples[0].Members) || + tuple.Members[1].Name != tuples[0].Members[1].Name { t.Errorf("Failed to selectTyped: incorrect data") return } @@ -3437,7 +3459,8 @@ func TestConnectionProtocolFeatureRequirementFail(t *testing.T) { require.Nilf(t, conn, "Connect fail") require.NotNilf(t, err, "Got error on connect") - require.Contains(t, err.Error(), "invalid server protocol: protocol feature TransactionsFeature is not supported") + require.Contains(t, err.Error(), + "invalid server protocol: protocol feature TransactionsFeature is not supported") } func TestConnectionProtocolFeatureRequirementManyFail(t *testing.T) { @@ -3454,7 +3477,8 @@ func TestConnectionProtocolFeatureRequirementManyFail(t *testing.T) { require.NotNilf(t, err, "Got error on connect") require.Contains(t, err.Error(), - "invalid server protocol: protocol features TransactionsFeature, Unknown feature (code 15532) are not supported") + "invalid server protocol: protocol features TransactionsFeature, "+ + "Unknown feature (code 15532) are not supported") } func TestConnectionFeatureOptsImmutable(t *testing.T) { @@ -3466,7 +3490,8 @@ func TestConnectionFeatureOptsImmutable(t *testing.T) { defer test_helpers.StopTarantoolWithCleanup(inst) if err != nil { - log.Fatalf("Failed to prepare test tarantool: %s", err) + log.Printf("Failed to prepare test tarantool: %s", err) + return } retries := uint(10) @@ -4012,7 +4037,8 @@ func runTestMain(m *testing.M) int { defer test_helpers.StopTarantoolWithCleanup(inst) if err != nil { - log.Fatalf("Failed to prepare test tarantool: %s", err) + log.Printf("Failed to prepare test tarantool: %s", err) + return 1 } return m.Run() diff --git a/test_helpers/main.go b/test_helpers/main.go index c777f2f26..894ebb653 100644 --- a/test_helpers/main.go +++ b/test_helpers/main.go @@ -102,7 +102,7 @@ func isReady(server string, opts *tarantool.Opts) error { return err } if conn == nil { - return errors.New("Conn is nil after connect") + return errors.New("connection is nil after connect") } defer conn.Close() @@ -111,7 +111,7 @@ func isReady(server string, opts *tarantool.Opts) error { return err } if resp == nil { - return errors.New("Response is nil after ping") + return errors.New("response is nil after ping") } return nil @@ -386,7 +386,7 @@ func ConvertUint64(v interface{}) (result uint64, err error) { case uint32: result = uint64(v) case uint64: - result = uint64(v) + result = v case int: result = uint64(v) case int8: @@ -398,7 +398,7 @@ func ConvertUint64(v interface{}) (result uint64, err error) { case int64: result = uint64(v) default: - err = fmt.Errorf("Non-number value %T", v) + err = fmt.Errorf("non-number value %T", v) } return } diff --git a/test_helpers/pool_helper.go b/test_helpers/pool_helper.go index 7dcd70cbc..c44df2f6a 100644 --- a/test_helpers/pool_helper.go +++ b/test_helpers/pool_helper.go @@ -26,12 +26,12 @@ type CheckStatusesArgs struct { func compareTuples(expectedTpl []interface{}, actualTpl []interface{}) error { if len(actualTpl) != len(expectedTpl) { - return fmt.Errorf("Unexpected body of Insert (tuple len)") + return fmt.Errorf("unexpected body of Insert (tuple len)") } for i, field := range actualTpl { if field != expectedTpl[i] { - return fmt.Errorf("Unexpected field, expected: %v actual: %v", expectedTpl[i], field) + return fmt.Errorf("unexpected field, expected: %v actual: %v", expectedTpl[i], field) } } @@ -104,7 +104,8 @@ func ProcessListenOnInstance(args interface{}) error { equal := reflect.DeepEqual(actualPorts, listenArgs.ExpectedPorts) if !equal { - return fmt.Errorf("expected ports: %v, actual ports: %v", actualPorts, listenArgs.ExpectedPorts) + return fmt.Errorf("expected ports: %v, actual ports: %v", + actualPorts, listenArgs.ExpectedPorts) } return nil @@ -129,10 +130,11 @@ func Retry(f func(interface{}) error, args interface{}, count int, timeout time. return err } -func InsertOnInstance(server string, connOpts tarantool.Opts, space interface{}, tuple interface{}) error { +func InsertOnInstance(server string, connOpts tarantool.Opts, space interface{}, + tuple interface{}) error { conn, err := tarantool.Connect(server, connOpts) if err != nil { - return fmt.Errorf("Fail to connect to %s: %s", server, err.Error()) + return fmt.Errorf("fail to connect to %s: %s", server, err.Error()) } if conn == nil { return fmt.Errorf("conn is nil after Connect") @@ -141,20 +143,20 @@ func InsertOnInstance(server string, connOpts tarantool.Opts, space interface{}, resp, err := conn.Do(tarantool.NewInsertRequest(space).Tuple(tuple)).Get() if err != nil { - return fmt.Errorf("Failed to Insert: %s", err.Error()) + return fmt.Errorf("failed to Insert: %s", err.Error()) } if resp == nil { - return fmt.Errorf("Response is nil after Insert") + return fmt.Errorf("response is nil after Insert") } if len(resp.Data) != 1 { - return fmt.Errorf("Response Body len != 1") + return fmt.Errorf("response Body len != 1") } if tpl, ok := resp.Data[0].([]interface{}); !ok { - return fmt.Errorf("Unexpected body of Insert") + return fmt.Errorf("unexpected body of Insert") } else { expectedTpl, ok := tuple.([]interface{}) if !ok { - return fmt.Errorf("Failed to cast") + return fmt.Errorf("failed to cast") } err = compareTuples(expectedTpl, tpl) @@ -166,7 +168,8 @@ func InsertOnInstance(server string, connOpts tarantool.Opts, space interface{}, return nil } -func InsertOnInstances(servers []string, connOpts tarantool.Opts, space interface{}, tuple interface{}) error { +func InsertOnInstances(servers []string, connOpts tarantool.Opts, space interface{}, + tuple interface{}) error { serversNumber := len(servers) roles := make([]bool, serversNumber) for i := 0; i < serversNumber; i++ { @@ -220,7 +223,8 @@ func SetClusterRO(servers []string, connOpts tarantool.Opts, roles []bool) error return nil } -func StartTarantoolInstances(servers []string, workDirs []string, opts StartOpts) ([]TarantoolInstance, error) { +func StartTarantoolInstances(servers []string, workDirs []string, + opts StartOpts) ([]TarantoolInstance, error) { isUserWorkDirs := (workDirs != nil) if isUserWorkDirs && (len(servers) != len(workDirs)) { return nil, fmt.Errorf("number of servers should be equal to number of workDirs") diff --git a/uuid/uuid.go b/uuid/uuid.go index eadd42ae1..cc2be736f 100644 --- a/uuid/uuid.go +++ b/uuid/uuid.go @@ -6,11 +6,14 @@ // // # See also // -// * Tarantool commit with UUID support https://github.com/tarantool/tarantool/commit/d68fc29246714eee505bc9bbcd84a02de17972c5 +// - Tarantool commit with UUID support: +// https://github.com/tarantool/tarantool/commit/d68fc29246714eee505bc9bbcd84a02de17972c5 // -// * Tarantool data model https://www.tarantool.io/en/doc/latest/book/box/data_model/ +// - Tarantool data model: +// https://www.tarantool.io/en/doc/latest/book/box/data_model/ // -// * Module UUID https://www.tarantool.io/en/doc/latest/reference/reference_lua/uuid/ +// - Module UUID: +// https://www.tarantool.io/en/doc/latest/reference/reference_lua/uuid/ package uuid import ( @@ -41,7 +44,7 @@ func encodeUUID(e *msgpack.Encoder, v reflect.Value) error { } func decodeUUID(d *msgpack.Decoder, v reflect.Value) error { - var bytesCount int = 16 + var bytesCount = 16 bytes := make([]byte, bytesCount) n, err := d.Buffered().Read(bytes) diff --git a/uuid/uuid_test.go b/uuid/uuid_test.go index 84abd42d2..94baaa6ea 100644 --- a/uuid/uuid_test.go +++ b/uuid/uuid_test.go @@ -177,7 +177,8 @@ func runTestMain(m *testing.M) int { defer test_helpers.StopTarantoolWithCleanup(inst) if err != nil { - log.Fatalf("Failed to prepare test tarantool: %s", err) + log.Printf("Failed to prepare test tarantool: %s", err) + return 1 } return m.Run()