diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 791444dc5073..4d803df0783c 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -48,7 +48,7 @@ const ( var _ abci.Application = (*BaseApp)(nil) // BaseApp reflects the ABCI application implementation. -type BaseApp struct { //nolint: maligned +type BaseApp struct { // initialized on creation logger log.Logger name string // application name from abci.Info diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index 788b96c2f2f3..6c0d3a7eb2b5 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -1,7 +1,7 @@ package tx_test import ( - gocontext "context" + "context" "fmt" "strings" "testing" @@ -40,7 +40,7 @@ type mockContext struct { wantErr bool } -func (m mockContext) Invoke(grpcCtx gocontext.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) { +func (m mockContext) Invoke(grpcCtx context.Context, method string, req, reply interface{}, opts ...grpc.CallOption) (err error) { if m.wantErr { return fmt.Errorf("mock err") } @@ -53,7 +53,7 @@ func (m mockContext) Invoke(grpcCtx gocontext.Context, method string, req, reply return nil } -func (mockContext) NewStream(gocontext.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { +func (mockContext) NewStream(context.Context, *grpc.StreamDesc, string, ...grpc.CallOption) (grpc.ClientStream, error) { panic("not implemented") } @@ -347,7 +347,7 @@ func TestSign(t *testing.T) { var prevSigs []signingtypes.SignatureV2 for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - err = tx.Sign(nil, tc.txf, tc.from, tc.txb, tc.overwrite) //nolint:staticcheck + err = tx.Sign(context.TODO(), tc.txf, tc.from, tc.txb, tc.overwrite) if len(tc.expectedPKs) == 0 { requireT.Error(err) } else { @@ -418,7 +418,7 @@ func TestPreprocessHook(t *testing.T) { txb, err := txfDirect.BuildUnsignedTx(msg1, msg2) requireT.NoError(err) - err = tx.Sign(nil, txfDirect, from, txb, false) //nolint:staticcheck + err = tx.Sign(context.TODO(), txfDirect, from, txb, false) requireT.NoError(err) // Run preprocessing diff --git a/codec/proto_codec.go b/codec/proto_codec.go index 6d4fec199bdd..32560b617ced 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -137,8 +137,6 @@ func (pc *ProtoCodec) MustUnmarshalLengthPrefixed(bz []byte, ptr gogoproto.Messa // it marshals to JSON using proto codec. // NOTE: this function must be used with a concrete type which // implements proto.Message. For interface please use the codec.MarshalInterfaceJSON -// -//nolint:stdmethods func (pc *ProtoCodec) MarshalJSON(o gogoproto.Message) ([]byte, error) { if o == nil { return nil, fmt.Errorf("cannot protobuf JSON encode nil") diff --git a/codec/types/any.go b/codec/types/any.go index 5ecc297f8e6b..c08b08d855be 100644 --- a/codec/types/any.go +++ b/codec/types/any.go @@ -1,4 +1,3 @@ -// nolint package types import ( diff --git a/codec/types/any_internal_test.go b/codec/types/any_internal_test.go index b2b12b123bdb..9adab2946653 100644 --- a/codec/types/any_internal_test.go +++ b/codec/types/any_internal_test.go @@ -17,7 +17,7 @@ func (d Dog) Greet() string { return d.Name } func (d *Dog) Reset() { d.Name = "" } func (d *Dog) String() string { return d.Name } func (d *Dog) ProtoMessage() {} -func (d *Dog) XXX_MessageName() string { return "tests/dog" } //nolint:revive +func (d *Dog) XXX_MessageName() string { return "tests/dog" } type Animal interface { Greet() string diff --git a/codec/types/any_test.go b/codec/types/any_test.go index 656344414a7e..7202f92e37b7 100644 --- a/codec/types/any_test.go +++ b/codec/types/any_test.go @@ -19,7 +19,7 @@ var _ proto.Message = (*errOnMarshal)(nil) var errAlways = fmt.Errorf("always erroring") -func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { //nolint:revive +func (eom *errOnMarshal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { //nolint:revive // ignore var-naming here return nil, errAlways } diff --git a/codec/types/types_test.go b/codec/types/types_test.go index 2c24a87ce0c7..8c3627154b7c 100644 --- a/codec/types/types_test.go +++ b/codec/types/types_test.go @@ -44,7 +44,7 @@ var ( func (dog FakeDog) Reset() {} func (dog FakeDog) String() string { return "fakedog" } func (dog FakeDog) ProtoMessage() {} -func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } //nolint:revive +func (dog FakeDog) XXX_MessageName() string { return proto.MessageName(&testdata.Dog{}) } //nolint:revive // ignore var-naming here func (dog FakeDog) Greet() string { return "fakedog" } func TestRegister(t *testing.T) { diff --git a/crypto/hd/hdpath_test.go b/crypto/hd/hdpath_test.go index 126a2a24f0ef..797a013f16ce 100644 --- a/crypto/hd/hdpath_test.go +++ b/crypto/hd/hdpath_test.go @@ -185,7 +185,7 @@ func TestDeriveHDPathRange(t *testing.T) { } } -func ExampleStringifyPathParams() { //nolint:govet +func ExampleStringifyPathParams() { path := hd.NewParams(44, 0, 0, false, 0) fmt.Println(path.String()) path = hd.NewParams(44, 33, 7, true, 9) @@ -195,7 +195,7 @@ func ExampleStringifyPathParams() { //nolint:govet // m/44'/33'/7'/1/9 } -func ExampleSomeBIP32TestVecs() { //nolint:govet +func ExampleSomeBIP32TestVecs() { seed := mnemonicToSeed("barrel original fuel morning among eternal " + "filter ball stove pluck matrix mechanic") master, ch := hd.ComputeMastersFromSeed(seed) diff --git a/crypto/keys/bcrypt/bcrypt.go b/crypto/keys/bcrypt/bcrypt.go index 7e2b0d0dc190..28cb8f990c7c 100644 --- a/crypto/keys/bcrypt/bcrypt.go +++ b/crypto/keys/bcrypt/bcrypt.go @@ -210,7 +210,7 @@ func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cip // Bug compatibility with C bcrypt implementations. They use the trailing // NULL in the key string during expansion. // We copy the key to prevent changing the underlying array. - ckey := append(key[:len(key):len(key)], 0) //nolint:gocritic // used in original https://cs.opensource.google/go/x/crypto/+/master:bcrypt/bcrypt.go + ckey := append(key[:len(key):len(key)], 0) c, err := blowfish.NewSaltedCipher(ckey, csalt) if err != nil { diff --git a/crypto/keys/multisig/amino.go b/crypto/keys/multisig/amino.go index 8c83b27021f1..459c4fc05d93 100644 --- a/crypto/keys/multisig/amino.go +++ b/crypto/keys/multisig/amino.go @@ -66,7 +66,7 @@ func tmToProto(tmPk tmMultisig) (*LegacyAminoPubKey, error) { } // MarshalAminoJSON overrides amino JSON unmarshaling. -func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { //nolint:golint,revive +func (m LegacyAminoPubKey) MarshalAminoJSON() (tmMultisig, error) { return protoToTm(&m) } diff --git a/crypto/keys/secp256k1/secp256k1_internal_test.go b/crypto/keys/secp256k1/secp256k1_internal_test.go index 56bef18f6bb4..01704dc23a14 100644 --- a/crypto/keys/secp256k1/secp256k1_internal_test.go +++ b/crypto/keys/secp256k1/secp256k1_internal_test.go @@ -16,7 +16,7 @@ func Test_genPrivKey(t *testing.T) { copy(onePadded[32-len(oneB):32], oneB) t.Logf("one padded: %v, len=%v", onePadded, len(onePadded)) - validOne := append(empty, onePadded...) //nolint:gocritic // append is fine here + validOne := append(empty, onePadded...) tests := []struct { name string notSoRand []byte diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index f9ce2418fd8b..099c8e91a38e 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -24,7 +24,7 @@ func checkAminoJSON(t *testing.T, src, dst interface{}, isNil bool) { require.Nil(t, err, "%+v", err) } -func ExamplePrintRegisteredTypes() { //nolint:govet +func ExamplePrintRegisteredTypes() { _ = cdc.PrintTypes(os.Stdout) // | Type | Name | Prefix | Length | Notes | // | ---- | ---- | ------ | ----- | ------ | diff --git a/internal/conv/string_test.go b/internal/conv/string_test.go index 3e051d37b907..7029e3190aec 100644 --- a/internal/conv/string_test.go +++ b/internal/conv/string_test.go @@ -26,7 +26,7 @@ func (s *StringSuite) TestUnsafeStrToBytes() { b := unsafeConvertStr() runtime.GC() <-time.NewTimer(2 * time.Millisecond).C - b2 := append(b, 'd') //nolint:gocritic // append is fine here + b2 := append(b, 'd') s.Equal("abc", string(b)) s.Equal("abcd", string(b2)) } diff --git a/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go b/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go index 9428c514d6e5..6923cc9416c6 100644 --- a/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go +++ b/orm/cmd/protoc-gen-go-cosmos-orm-proto/main.go @@ -1,9 +1,8 @@ package main import ( - "google.golang.org/protobuf/compiler/protogen" - "github.com/cosmos/cosmos-sdk/orm/internal/codegen" + "google.golang.org/protobuf/compiler/protogen" ) func main() { diff --git a/orm/cmd/protoc-gen-go-cosmos-orm/main.go b/orm/cmd/protoc-gen-go-cosmos-orm/main.go index 9c06f9ac8b7c..ce75b2f39dc1 100644 --- a/orm/cmd/protoc-gen-go-cosmos-orm/main.go +++ b/orm/cmd/protoc-gen-go-cosmos-orm/main.go @@ -1,9 +1,8 @@ package main import ( - "google.golang.org/protobuf/compiler/protogen" - "github.com/cosmos/cosmos-sdk/orm/internal/codegen" + "google.golang.org/protobuf/compiler/protogen" ) func main() { diff --git a/orm/encoding/encodeutil/util.go b/orm/encoding/encodeutil/util.go index d8fe8a1c2ed3..b126c834ea57 100644 --- a/orm/encoding/encodeutil/util.go +++ b/orm/encoding/encodeutil/util.go @@ -14,9 +14,10 @@ import ( func SkipPrefix(r *bytes.Reader, prefix []byte) error { n := len(prefix) if n > 0 { - // we skip checking the prefix for performance reasons because we assume - // that it was checked by the caller + // We skip checking the prefix for performance reasons because we assume + // that it was checked by the caller. _, err := r.Seek(int64(n), io.SeekCurrent) + return err } return nil @@ -33,12 +34,12 @@ func AppendVarUInt32(prefix []byte, x uint32) []byte { } // ValuesOf takes the arguments and converts them to protoreflect.Value's. -func ValuesOf(values ...interface{}) []protoreflect.Value { +func ValuesOf(values ...any) []protoreflect.Value { n := len(values) res := make([]protoreflect.Value, n) for i := 0; i < n; i++ { - // we catch the case of proto messages here and call ProtoReflect. - // this allows us to use imported messages, such as timestamppb.Timestamp + // We catch the case of proto messages here and call ProtoReflect. + // This allows us to use imported messages, such as timestamppb.Timestamp // in iterators. value := values[i] switch value.(type) { diff --git a/orm/encoding/ormfield/bool.go b/orm/encoding/ormfield/bool.go index 8fac99becb4c..faf9080f5fe5 100644 --- a/orm/encoding/ormfield/bool.go +++ b/orm/encoding/ormfield/bool.go @@ -9,7 +9,7 @@ import ( // BoolCodec encodes a bool value as a single byte 0 or 1. type BoolCodec struct{} -func (b BoolCodec) Decode(r Reader) (protoreflect.Value, error) { +func (BoolCodec) Decode(r Reader) (protoreflect.Value, error) { x, err := r.ReadByte() return protoreflect.ValueOfBool(x != 0), err } @@ -19,7 +19,7 @@ var ( oneBz = []byte{1} ) -func (b BoolCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (BoolCodec) Encode(value protoreflect.Value, w io.Writer) error { var err error if !value.IsValid() || !value.Bool() { _, err = w.Write(zeroBz) @@ -29,7 +29,7 @@ func (b BoolCodec) Encode(value protoreflect.Value, w io.Writer) error { return err } -func (b BoolCodec) Compare(v1, v2 protoreflect.Value) int { +func (BoolCodec) Compare(v1, v2 protoreflect.Value) int { var b1, b2 bool if v1.IsValid() { b1 = v1.Bool() @@ -46,11 +46,11 @@ func (b BoolCodec) Compare(v1, v2 protoreflect.Value) int { } } -func (b BoolCodec) IsOrdered() bool { +func (BoolCodec) IsOrdered() bool { return false } -func (b BoolCodec) FixedBufferSize() int { +func (BoolCodec) FixedBufferSize() int { return 1 } diff --git a/orm/encoding/ormfield/bytes.go b/orm/encoding/ormfield/bytes.go index 0eea476b8a47..e91aafa68416 100644 --- a/orm/encoding/ormfield/bytes.go +++ b/orm/encoding/ormfield/bytes.go @@ -12,12 +12,12 @@ import ( // than 255 bytes. type BytesCodec struct{} -func (b BytesCodec) FixedBufferSize() int { +func (BytesCodec) FixedBufferSize() int { return -1 } // ComputeBufferSize returns the bytes size of the value. -func (b BytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (BytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { return bytesSize(value), nil } @@ -28,16 +28,16 @@ func bytesSize(value protoreflect.Value) int { return len(value.Bytes()) } -func (b BytesCodec) IsOrdered() bool { +func (BytesCodec) IsOrdered() bool { return false } -func (b BytesCodec) Decode(r Reader) (protoreflect.Value, error) { +func (BytesCodec) Decode(r Reader) (protoreflect.Value, error) { bz, err := io.ReadAll(r) return protoreflect.ValueOfBytes(bz), err } -func (b BytesCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (BytesCodec) Encode(value protoreflect.Value, w io.Writer) error { if !value.IsValid() { return nil } @@ -45,7 +45,7 @@ func (b BytesCodec) Encode(value protoreflect.Value, w io.Writer) error { return err } -func (b BytesCodec) Compare(v1, v2 protoreflect.Value) int { +func (BytesCodec) Compare(v1, v2 protoreflect.Value) int { return compareBytes(v1, v2) } @@ -53,16 +53,16 @@ func (b BytesCodec) Compare(v1, v2 protoreflect.Value) int { // byte. It errors if the byte array is longer than 255 bytes. type NonTerminalBytesCodec struct{} -func (b NonTerminalBytesCodec) FixedBufferSize() int { +func (NonTerminalBytesCodec) FixedBufferSize() int { return -1 } // ComputeBufferSize returns the bytes size of the value plus the length of the // varint length-prefix. -func (b NonTerminalBytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (NonTerminalBytesCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { n := bytesSize(value) prefixLen := 1 - // we use varint, if the first bit of a byte is 1 then we need to signal continuation + // We use varint, if the first bit of a byte is 1 then we need to signal continuation. for n >= 0x80 { prefixLen++ n >>= 7 @@ -70,15 +70,15 @@ func (b NonTerminalBytesCodec) ComputeBufferSize(value protoreflect.Value) (int, return n + prefixLen, nil } -func (b NonTerminalBytesCodec) IsOrdered() bool { +func (NonTerminalBytesCodec) IsOrdered() bool { return false } -func (b NonTerminalBytesCodec) Compare(v1, v2 protoreflect.Value) int { +func (NonTerminalBytesCodec) Compare(v1, v2 protoreflect.Value) int { return compareBytes(v1, v2) } -func (b NonTerminalBytesCodec) Decode(r Reader) (protoreflect.Value, error) { +func (NonTerminalBytesCodec) Decode(r Reader) (protoreflect.Value, error) { n, err := binary.ReadUvarint(r) if err != nil { return protoreflect.Value{}, err @@ -93,7 +93,7 @@ func (b NonTerminalBytesCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfBytes(bz), err } -func (b NonTerminalBytesCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (NonTerminalBytesCodec) Encode(value protoreflect.Value, w io.Writer) error { var bz []byte if value.IsValid() { bz = value.Bytes() diff --git a/orm/encoding/ormfield/codec.go b/orm/encoding/ormfield/codec.go index 14a1d4804c71..1626058ddc7d 100644 --- a/orm/encoding/ormfield/codec.go +++ b/orm/encoding/ormfield/codec.go @@ -4,11 +4,9 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - + "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" - - "google.golang.org/protobuf/reflect/protoreflect" ) // Codec defines an interface for decoding and encoding values in ORM index keys. @@ -50,37 +48,37 @@ var ( ) // GetCodec returns the Codec for the provided field if one is defined. -// nonTerminal should be set to true if this value is being encoded as a +// NonTerminal should be set to true if this value is being encoded as a // non-terminal segment of a multi-part key. func GetCodec(field protoreflect.FieldDescriptor, nonTerminal bool) (Codec, error) { if field == nil { - return nil, ormerrors.InvalidKeyField.Wrap("nil field") + return nil, ormerrors.ErrInvalidKeyField.Wrap("nil field") } if field.IsList() { - return nil, ormerrors.InvalidKeyField.Wrapf("repeated field %s", field.FullName()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("repeated field %s", field.FullName()) } if field.ContainingOneof() != nil { - return nil, ormerrors.InvalidKeyField.Wrapf("oneof field %s", field.FullName()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("oneof field %s", field.FullName()) } if field.HasOptionalKeyword() { - return nil, ormerrors.InvalidKeyField.Wrapf("optional field %s", field.FullName()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("optional field %s", field.FullName()) } switch field.Kind() { case protoreflect.BytesKind: if nonTerminal { return NonTerminalBytesCodec{}, nil - } else { - return BytesCodec{}, nil } + return BytesCodec{}, nil + case protoreflect.StringKind: if nonTerminal { return NonTerminalStringCodec{}, nil - } else { - return StringCodec{}, nil } + return StringCodec{}, nil + case protoreflect.Uint32Kind: return CompactUint32Codec{}, nil case protoreflect.Fixed32Kind: @@ -105,9 +103,9 @@ func GetCodec(field protoreflect.FieldDescriptor, nonTerminal bool) (Codec, erro case durationFullName: return DurationCodec{}, nil default: - return nil, ormerrors.InvalidKeyField.Wrapf("%s of type %s", field.FullName(), msgName) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("%s of type %s", field.FullName(), msgName) } default: - return nil, ormerrors.InvalidKeyField.Wrapf("%s of kind %s", field.FullName(), field.Kind()) + return nil, ormerrors.ErrInvalidKeyField.Wrapf("%s of kind %s", field.FullName(), field.Kind()) } } diff --git a/orm/encoding/ormfield/codec_test.go b/orm/encoding/ormfield/codec_test.go index abab4d2d5a9b..5a5db3598c94 100644 --- a/orm/encoding/ormfield/codec_test.go +++ b/orm/encoding/ormfield/codec_test.go @@ -6,26 +6,23 @@ import ( "testing" "time" - "google.golang.org/protobuf/types/known/timestamppb" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" - + "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/timestamppb" "gotest.tools/v3/assert" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" ) func TestCodec(t *testing.T) { for _, ks := range testutil.TestFieldSpecs { - testCodec(t, ks) + doTestCodec(t, ks) } } -func testCodec(t *testing.T, spec testutil.TestFieldSpec) { +func doTestCodec(t *testing.T, spec testutil.TestFieldSpec) { + t.Helper() t.Run(fmt.Sprintf("%s %v", spec.FieldName, false), func(t *testing.T) { testCodecNT(t, spec.FieldName, spec.Gen, false) }) @@ -35,6 +32,7 @@ func testCodec(t *testing.T, spec testutil.TestFieldSpec) { } func testCodecNT(t *testing.T, fname protoreflect.Name, generator *rapid.Generator[any], nonTerminal bool) { + t.Helper() cdc, err := testutil.MakeTestCodec(fname, nonTerminal) assert.NilError(t, err) rapid.Check(t, func(t *rapid.T) { @@ -68,15 +66,15 @@ func checkEncodeDecodeSize(t *rapid.T, x protoreflect.Value, cdc ormfield.Codec) func TestUnsupportedFields(t *testing.T) { _, err := ormfield.GetCodec(nil, false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("repeated"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("map"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("msg"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) _, err = ormfield.GetCodec(testutil.GetTestField("oneof"), false) - assert.ErrorContains(t, err, ormerrors.InvalidKeyField.Error()) + assert.ErrorContains(t, err, ormerrors.ErrInvalidKeyField.Error()) } func TestCompactUInt32(t *testing.T) { @@ -99,7 +97,7 @@ func TestCompactUInt32(t *testing.T) { testEncodeDecode(1073741823, 4) testEncodeDecode(1073741824, 5) - // randomized tests + // Randomized tests. rapid.Check(t, func(t *rapid.T) { x := rapid.Uint32().Draw(t, "x") y := rapid.Uint32().Draw(t, "y") @@ -147,7 +145,7 @@ func TestCompactUInt64(t *testing.T) { testEncodeDecode(70368744177663, 6) testEncodeDecode(70368744177664, 9) - // randomized tests + // Randomized tests. rapid.Check(t, func(t *rapid.T) { x := rapid.Uint64().Draw(t, "x") y := rapid.Uint64().Draw(t, "y") @@ -176,7 +174,7 @@ func TestCompactUInt64(t *testing.T) { func TestTimestamp(t *testing.T) { cdc := ormfield.TimestampCodec{} - // nil value + // Nil value. buf := &bytes.Buffer{} assert.NilError(t, cdc.Encode(protoreflect.Value{}, buf)) assert.Equal(t, 1, len(buf.Bytes())) @@ -184,7 +182,7 @@ func TestTimestamp(t *testing.T) { assert.NilError(t, err) assert.Assert(t, !val.IsValid()) - // no nanos + // No nanos. ts := timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 0, time.UTC)) val = protoreflect.ValueOfMessage(ts.ProtoReflect()) buf = &bytes.Buffer{} @@ -194,7 +192,7 @@ func TestTimestamp(t *testing.T) { assert.NilError(t, err) assert.Equal(t, 0, cdc.Compare(val, val2)) - // nanos + // Nanos. ts = timestamppb.New(time.Date(2022, 1, 1, 12, 30, 15, 235809753, time.UTC)) val = protoreflect.ValueOfMessage(ts.ProtoReflect()) buf = &bytes.Buffer{} diff --git a/orm/encoding/ormfield/duration.go b/orm/encoding/ormfield/duration.go index f01e2a60e235..9b0d6cbd9ab8 100644 --- a/orm/encoding/ormfield/duration.go +++ b/orm/encoding/ormfield/duration.go @@ -21,7 +21,7 @@ func getDurationSecondsAndNanos(value protoreflect.Value) (protoreflect.Value, p // sorted iteration. type DurationCodec struct{} -func (d DurationCodec) Decode(r Reader) (protoreflect.Value, error) { +func (DurationCodec) Decode(r Reader) (protoreflect.Value, error) { seconds, err := int64Codec.Decode(r) if err != nil { return protoreflect.Value{}, err @@ -36,7 +36,7 @@ func (d DurationCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(msg), nil } -func (d DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { seconds, nanos := getDurationSecondsAndNanos(value) err := int64Codec.Encode(seconds, w) if err != nil { @@ -45,22 +45,21 @@ func (d DurationCodec) Encode(value protoreflect.Value, w io.Writer) error { return int32Codec.Encode(nanos, w) } -func (d DurationCodec) Compare(v1, v2 protoreflect.Value) int { +func (DurationCodec) Compare(v1, v2 protoreflect.Value) int { s1, n1 := getDurationSecondsAndNanos(v1) s2, n2 := getDurationSecondsAndNanos(v2) c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + return compareInt(n1, n2) } -func (d DurationCodec) IsOrdered() bool { +func (DurationCodec) IsOrdered() bool { return true } -func (d DurationCodec) FixedBufferSize() int { +func (DurationCodec) FixedBufferSize() int { return 12 } diff --git a/orm/encoding/ormfield/enum.go b/orm/encoding/ormfield/enum.go index 106ac311a8ff..397490877257 100644 --- a/orm/encoding/ormfield/enum.go +++ b/orm/encoding/ormfield/enum.go @@ -10,12 +10,12 @@ import ( // EnumCodec encodes enum values as varints. type EnumCodec struct{} -func (e EnumCodec) Decode(r Reader) (protoreflect.Value, error) { +func (EnumCodec) Decode(r Reader) (protoreflect.Value, error) { x, err := binary.ReadVarint(r) return protoreflect.ValueOfEnum(protoreflect.EnumNumber(x)), err } -func (e EnumCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (EnumCodec) Encode(value protoreflect.Value, w io.Writer) error { var x protoreflect.EnumNumber if value.IsValid() { x = value.Enum() @@ -26,7 +26,7 @@ func (e EnumCodec) Encode(value protoreflect.Value, w io.Writer) error { return err } -func (e EnumCodec) Compare(v1, v2 protoreflect.Value) int { +func (EnumCodec) Compare(v1, v2 protoreflect.Value) int { var x, y protoreflect.EnumNumber if v1.IsValid() { x = v1.Enum() @@ -43,11 +43,11 @@ func (e EnumCodec) Compare(v1, v2 protoreflect.Value) int { } } -func (e EnumCodec) IsOrdered() bool { +func (EnumCodec) IsOrdered() bool { return false } -func (e EnumCodec) FixedBufferSize() int { +func (EnumCodec) FixedBufferSize() int { return binary.MaxVarintLen32 } diff --git a/orm/encoding/ormfield/int32.go b/orm/encoding/ormfield/int32.go index 8b2dd9331af8..9d2cccb9c748 100644 --- a/orm/encoding/ormfield/int32.go +++ b/orm/encoding/ormfield/int32.go @@ -19,14 +19,14 @@ const ( int32Offset = int32Max + 1 ) -func (i Int32Codec) Decode(r Reader) (protoreflect.Value, error) { +func (Int32Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint32 err := binary.Read(r, binary.BigEndian, &x) y := int64(x) - int32Offset return protoreflect.ValueOfInt32(int32(y)), err } -func (i Int32Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (Int32Codec) Encode(value protoreflect.Value, w io.Writer) error { var x int64 if value.IsValid() { x = value.Int() @@ -35,15 +35,15 @@ func (i Int32Codec) Encode(value protoreflect.Value, w io.Writer) error { return binary.Write(w, binary.BigEndian, uint32(x)) } -func (i Int32Codec) Compare(v1, v2 protoreflect.Value) int { +func (Int32Codec) Compare(v1, v2 protoreflect.Value) int { return compareInt(v1, v2) } -func (i Int32Codec) IsOrdered() bool { +func (Int32Codec) IsOrdered() bool { return true } -func (i Int32Codec) FixedBufferSize() int { +func (Int32Codec) FixedBufferSize() int { return 4 } diff --git a/orm/encoding/ormfield/int64.go b/orm/encoding/ormfield/int64.go index cbe13420d7d5..58d754d01d99 100644 --- a/orm/encoding/ormfield/int64.go +++ b/orm/encoding/ormfield/int64.go @@ -16,19 +16,18 @@ var int64Codec = Int64Codec{} const int64Max = 9223372036854775807 -func (i Int64Codec) Decode(r Reader) (protoreflect.Value, error) { +func (Int64Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint64 err := binary.Read(r, binary.BigEndian, &x) if x >= int64Max { x = x - int64Max - 1 return protoreflect.ValueOfInt64(int64(x)), err - } else { - y := int64(x) - int64Max - 1 - return protoreflect.ValueOfInt64(y), err } + y := int64(x) - int64Max - 1 + return protoreflect.ValueOfInt64(y), err } -func (i Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { var x int64 if value.IsValid() { x = value.Int() @@ -36,22 +35,21 @@ func (i Int64Codec) Encode(value protoreflect.Value, w io.Writer) error { if x >= -1 { y := uint64(x) + int64Max + 1 return binary.Write(w, binary.BigEndian, y) - } else { - x += int64Max - x += 1 - return binary.Write(w, binary.BigEndian, uint64(x)) } + x += int64Max + x++ + return binary.Write(w, binary.BigEndian, uint64(x)) } -func (i Int64Codec) Compare(v1, v2 protoreflect.Value) int { +func (Int64Codec) Compare(v1, v2 protoreflect.Value) int { return compareInt(v1, v2) } -func (i Int64Codec) IsOrdered() bool { +func (Int64Codec) IsOrdered() bool { return true } -func (i Int64Codec) FixedBufferSize() int { +func (Int64Codec) FixedBufferSize() int { return 8 } diff --git a/orm/encoding/ormfield/string.go b/orm/encoding/ormfield/string.go index e052efab31d4..b15bb93509f4 100644 --- a/orm/encoding/ormfield/string.go +++ b/orm/encoding/ormfield/string.go @@ -11,11 +11,11 @@ import ( // StringCodec encodes strings as raw bytes. type StringCodec struct{} -func (s StringCodec) FixedBufferSize() int { +func (StringCodec) FixedBufferSize() int { return -1 } -func (s StringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (StringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { if !value.IsValid() { return 0, nil } @@ -23,20 +23,20 @@ func (s StringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { return len(value.String()), nil } -func (s StringCodec) IsOrdered() bool { +func (StringCodec) IsOrdered() bool { return true } -func (s StringCodec) Compare(v1, v2 protoreflect.Value) int { +func (StringCodec) Compare(v1, v2 protoreflect.Value) int { return compareStrings(v1, v2) } -func (s StringCodec) Decode(r Reader) (protoreflect.Value, error) { +func (StringCodec) Decode(r Reader) (protoreflect.Value, error) { bz, err := io.ReadAll(r) return protoreflect.ValueOfString(string(bz)), err } -func (s StringCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (StringCodec) Encode(value protoreflect.Value, w io.Writer) error { var x string if value.IsValid() { x = value.String() @@ -49,23 +49,23 @@ func (s StringCodec) Encode(value protoreflect.Value, w io.Writer) error { // values within strings will produce an error. type NonTerminalStringCodec struct{} -func (s NonTerminalStringCodec) FixedBufferSize() int { +func (NonTerminalStringCodec) FixedBufferSize() int { return -1 } -func (s NonTerminalStringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { +func (NonTerminalStringCodec) ComputeBufferSize(value protoreflect.Value) (int, error) { return len(value.String()) + 1, nil } -func (s NonTerminalStringCodec) IsOrdered() bool { +func (NonTerminalStringCodec) IsOrdered() bool { return true } -func (s NonTerminalStringCodec) Compare(v1, v2 protoreflect.Value) int { +func (NonTerminalStringCodec) Compare(v1, v2 protoreflect.Value) int { return compareStrings(v1, v2) } -func (s NonTerminalStringCodec) Decode(r Reader) (protoreflect.Value, error) { +func (NonTerminalStringCodec) Decode(r Reader) (protoreflect.Value, error) { var bz []byte for { b, err := r.ReadByte() @@ -76,7 +76,7 @@ func (s NonTerminalStringCodec) Decode(r Reader) (protoreflect.Value, error) { } } -func (s NonTerminalStringCodec) Encode(value protoreflect.Value, w io.Writer) error { +func (NonTerminalStringCodec) Encode(value protoreflect.Value, w io.Writer) error { var str string if value.IsValid() { str = value.String() diff --git a/orm/encoding/ormfield/timestamp.go b/orm/encoding/ormfield/timestamp.go index eb13c3de74b0..7b59195b8988 100644 --- a/orm/encoding/ormfield/timestamp.go +++ b/orm/encoding/ormfield/timestamp.go @@ -33,8 +33,8 @@ var ( timestampZeroNanosBz = []byte{timestampZeroNanosValue} ) -func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { - // nil case +func (TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { + // Nil case. if !value.IsValid() { _, err := w.Write(timestampNilBz) return err @@ -47,7 +47,7 @@ func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { } secondsInt -= timestampSecondsMin var secondsBz [5]byte - // write the seconds buffer from the end to the front + // Write the seconds buffer from the end to the front. for i := 4; i >= 0; i-- { secondsBz[i] = byte(secondsInt) secondsInt >>= 8 @@ -72,12 +72,12 @@ func (t TimestampCodec) Encode(value protoreflect.Value, w io.Writer) error { nanosBz[i] = byte(nanosInt) nanosInt >>= 8 } - nanosBz[0] = nanosBz[0] | 0xC0 + nanosBz[0] |= 0xC0 _, err = w.Write(nanosBz[:]) return err } -func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { +func (TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { b0, err := r.ReadByte() if err != nil { return protoreflect.Value{}, err @@ -124,7 +124,7 @@ func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.Value{}, io.EOF } - nanos := int32(b0) & 0x3F // clear first two bits + nanos := int32(b0) & 0x3F // Clear first two bits. for i := 0; i < 3; i++ { nanos <<= 8 nanos |= int32(nanosBz[i]) @@ -134,7 +134,7 @@ func (t TimestampCodec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(msg), nil } -func (t TimestampCodec) Compare(v1, v2 protoreflect.Value) int { +func (TimestampCodec) Compare(v1, v2 protoreflect.Value) int { if !v1.IsValid() { if !v2.IsValid() { return 0 @@ -151,20 +151,19 @@ func (t TimestampCodec) Compare(v1, v2 protoreflect.Value) int { c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + return compareInt(n1, n2) } -func (t TimestampCodec) IsOrdered() bool { +func (TimestampCodec) IsOrdered() bool { return true } -func (t TimestampCodec) FixedBufferSize() int { +func (TimestampCodec) FixedBufferSize() int { return 9 } -func (t TimestampCodec) ComputeBufferSize(protoreflect.Value) (int, error) { +func (TimestampCodec) ComputeBufferSize(protoreflect.Value) (int, error) { return 9, nil } @@ -185,7 +184,7 @@ func getTimestampSecondsAndNanos(value protoreflect.Value) (protoreflect.Value, return msg.Get(timestampSecondsField), msg.Get(timestampNanosField) } -func (t TimestampV0Codec) Decode(r Reader) (protoreflect.Value, error) { +func (TimestampV0Codec) Decode(r Reader) (protoreflect.Value, error) { seconds, err := int64Codec.Decode(r) if err != nil { return protoreflect.Value{}, err @@ -200,7 +199,7 @@ func (t TimestampV0Codec) Decode(r Reader) (protoreflect.Value, error) { return protoreflect.ValueOfMessage(msg), nil } -func (t TimestampV0Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (TimestampV0Codec) Encode(value protoreflect.Value, w io.Writer) error { seconds, nanos := getTimestampSecondsAndNanos(value) err := int64Codec.Encode(seconds, w) if err != nil { @@ -209,22 +208,21 @@ func (t TimestampV0Codec) Encode(value protoreflect.Value, w io.Writer) error { return int32Codec.Encode(nanos, w) } -func (t TimestampV0Codec) Compare(v1, v2 protoreflect.Value) int { +func (TimestampV0Codec) Compare(v1, v2 protoreflect.Value) int { s1, n1 := getTimestampSecondsAndNanos(v1) s2, n2 := getTimestampSecondsAndNanos(v2) c := compareInt(s1, s2) if c != 0 { return c - } else { - return compareInt(n1, n2) } + return compareInt(n1, n2) } -func (t TimestampV0Codec) IsOrdered() bool { +func (TimestampV0Codec) IsOrdered() bool { return true } -func (t TimestampV0Codec) FixedBufferSize() int { +func (TimestampV0Codec) FixedBufferSize() int { return 12 } diff --git a/orm/encoding/ormfield/uint32.go b/orm/encoding/ormfield/uint32.go index 0e770ad6b482..1ec6b147a026 100644 --- a/orm/encoding/ormfield/uint32.go +++ b/orm/encoding/ormfield/uint32.go @@ -11,7 +11,7 @@ import ( // FixedUint32Codec encodes uint32 values as 4-byte big-endian integers. type FixedUint32Codec struct{} -func (u FixedUint32Codec) FixedBufferSize() int { +func (FixedUint32Codec) FixedBufferSize() int { return 4 } @@ -19,21 +19,21 @@ func (u FixedUint32Codec) ComputeBufferSize(protoreflect.Value) (int, error) { return u.FixedBufferSize(), nil } -func (u FixedUint32Codec) IsOrdered() bool { +func (FixedUint32Codec) IsOrdered() bool { return true } -func (u FixedUint32Codec) Compare(v1, v2 protoreflect.Value) int { +func (FixedUint32Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (u FixedUint32Codec) Decode(r Reader) (protoreflect.Value, error) { +func (FixedUint32Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint32 err := binary.Read(r, binary.BigEndian, &x) return protoreflect.ValueOfUint32(x), err } -func (u FixedUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (FixedUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -44,12 +44,12 @@ func (u FixedUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { // CompactUint32Codec encodes uint32 values using EncodeCompactUint32. type CompactUint32Codec struct{} -func (c CompactUint32Codec) Decode(r Reader) (protoreflect.Value, error) { +func (CompactUint32Codec) Decode(r Reader) (protoreflect.Value, error) { x, err := DecodeCompactUint32(r) return protoreflect.ValueOfUint32(x), err } -func (c CompactUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (CompactUint32Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -58,15 +58,15 @@ func (c CompactUint32Codec) Encode(value protoreflect.Value, w io.Writer) error return err } -func (c CompactUint32Codec) Compare(v1, v2 protoreflect.Value) int { +func (CompactUint32Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (c CompactUint32Codec) IsOrdered() bool { +func (CompactUint32Codec) IsOrdered() bool { return true } -func (c CompactUint32Codec) FixedBufferSize() int { +func (CompactUint32Codec) FixedBufferSize() int { return 5 } @@ -83,19 +83,19 @@ func (c CompactUint32Codec) ComputeBufferSize(protoreflect.Value) (int, error) { // fit in 3, and values less than 2^30 will fit in 4. func EncodeCompactUint32(x uint32) []byte { switch { - case x < 16384: // 2^14 + case x < 16384: // 2^14. buf := make([]byte, 2) buf[0] = byte(x >> 8) buf[1] = byte(x) return buf - case x < 4194304: // 2^22 + case x < 4194304: // 2^22. buf := make([]byte, 3) buf[0] = 0x40 buf[0] |= byte(x >> 16) buf[1] = byte(x >> 8) buf[2] = byte(x) return buf - case x < 1073741824: // 2^30 + case x < 1073741824: // 2^30. buf := make([]byte, 4) buf[0] = 0x80 buf[0] |= byte(x >> 24) diff --git a/orm/encoding/ormfield/uint64.go b/orm/encoding/ormfield/uint64.go index e4f654239905..7573ad584245 100644 --- a/orm/encoding/ormfield/uint64.go +++ b/orm/encoding/ormfield/uint64.go @@ -11,7 +11,7 @@ import ( // FixedUint64Codec encodes uint64 values as 8-byte big-endian integers. type FixedUint64Codec struct{} -func (u FixedUint64Codec) FixedBufferSize() int { +func (FixedUint64Codec) FixedBufferSize() int { return 8 } @@ -19,21 +19,21 @@ func (u FixedUint64Codec) ComputeBufferSize(protoreflect.Value) (int, error) { return u.FixedBufferSize(), nil } -func (u FixedUint64Codec) IsOrdered() bool { +func (FixedUint64Codec) IsOrdered() bool { return true } -func (u FixedUint64Codec) Compare(v1, v2 protoreflect.Value) int { +func (FixedUint64Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (u FixedUint64Codec) Decode(r Reader) (protoreflect.Value, error) { +func (FixedUint64Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint64 err := binary.Read(r, binary.BigEndian, &x) return protoreflect.ValueOfUint64(x), err } -func (u FixedUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (FixedUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -61,12 +61,12 @@ func compareUint(v1, v2 protoreflect.Value) int { // CompactUint64Codec encodes uint64 values using EncodeCompactUint64. type CompactUint64Codec struct{} -func (c CompactUint64Codec) Decode(r Reader) (protoreflect.Value, error) { +func (CompactUint64Codec) Decode(r Reader) (protoreflect.Value, error) { x, err := DecodeCompactUint64(r) return protoreflect.ValueOfUint64(x), err } -func (c CompactUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { +func (CompactUint64Codec) Encode(value protoreflect.Value, w io.Writer) error { var x uint64 if value.IsValid() { x = value.Uint() @@ -75,15 +75,15 @@ func (c CompactUint64Codec) Encode(value protoreflect.Value, w io.Writer) error return err } -func (c CompactUint64Codec) Compare(v1, v2 protoreflect.Value) int { +func (CompactUint64Codec) Compare(v1, v2 protoreflect.Value) int { return compareUint(v1, v2) } -func (c CompactUint64Codec) IsOrdered() bool { +func (CompactUint64Codec) IsOrdered() bool { return true } -func (c CompactUint64Codec) FixedBufferSize() int { +func (CompactUint64Codec) FixedBufferSize() int { return 9 } @@ -100,12 +100,12 @@ func (c CompactUint64Codec) ComputeBufferSize(protoreflect.Value) (int, error) { // fit in 4, and values less than 2^46 will fit in 6. func EncodeCompactUint64(x uint64) []byte { switch { - case x < 16384: // 2^14 + case x < 16384: // 2^14. buf := make([]byte, 2) buf[0] = byte(x >> 8) buf[1] = byte(x) return buf - case x < 1073741824: // 2^30 + case x < 1073741824: // 2^30. buf := make([]byte, 4) buf[0] = 0x40 buf[0] |= byte(x >> 24) @@ -113,7 +113,7 @@ func EncodeCompactUint64(x uint64) []byte { buf[2] = byte(x >> 8) buf[3] = byte(x) return buf - case x < 70368744177664: // 2^46 + case x < 70368744177664: // 2^46. buf := make([]byte, 6) buf[0] = 0x80 buf[0] |= byte(x >> 40) diff --git a/orm/encoding/ormkv/entry.go b/orm/encoding/ormkv/entry.go index 2098afbac6a9..7105b514b7c6 100644 --- a/orm/encoding/ormkv/entry.go +++ b/orm/encoding/ormkv/entry.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" ) @@ -18,7 +17,7 @@ type Entry interface { // proto message name) this entry corresponds to. GetTableName() protoreflect.FullName - // to allow new methods to be added without breakage, this interface + // To allow new methods to be added without breakage, this interface // shouldn't be implemented outside this package, // see https://go.dev/blog/module-compatibility doNotImplement() @@ -43,14 +42,13 @@ func (p *PrimaryKeyEntry) GetTableName() protoreflect.FullName { func (p *PrimaryKeyEntry) String() string { if p.Value == nil { return fmt.Sprintf("PK %s %s -> _", p.TableName, fmtValues(p.Key)) - } else { - valBz, err := stablejson.Marshal(p.Value) - valStr := string(valBz) - if err != nil { - valStr = fmt.Sprintf("ERR %v", err) - } - return fmt.Sprintf("PK %s %s -> %s", p.TableName, fmtValues(p.Key), valStr) } + valBz, err := stablejson.Marshal(p.Value) + valStr := string(valBz) + if err != nil { + valStr = fmt.Sprintf("ERR %v", err) + } + return fmt.Sprintf("PK %s %s -> %s", p.TableName, fmtValues(p.Key), valStr) } func fmtValues(values []protoreflect.Value) string { @@ -66,7 +64,7 @@ func fmtValues(values []protoreflect.Value) string { return strings.Join(parts, "/") } -func (p *PrimaryKeyEntry) doNotImplement() {} +func (*PrimaryKeyEntry) doNotImplement() {} // IndexKeyEntry represents a logically decoded index entry. type IndexKeyEntry struct { @@ -83,7 +81,7 @@ type IndexKeyEntry struct { IndexValues []protoreflect.Value // PrimaryKey represents the primary key values, it is empty if this is a - // prefix key + // prefix key. PrimaryKey []protoreflect.Value } @@ -91,9 +89,9 @@ func (i *IndexKeyEntry) GetTableName() protoreflect.FullName { return i.TableName } -func (i *IndexKeyEntry) doNotImplement() {} +func (*IndexKeyEntry) doNotImplement() {} -func (i *IndexKeyEntry) string() string { +func (i *IndexKeyEntry) returnString() string { return fmt.Sprintf("%s %s : %s -> %s", i.TableName, fmtFields(i.Fields), fmtValues(i.IndexValues), fmtValues(i.PrimaryKey)) } @@ -107,10 +105,9 @@ func fmtFields(fields []protoreflect.Name) string { func (i *IndexKeyEntry) String() string { if i.IsUnique { - return fmt.Sprintf("UNIQ %s", i.string()) - } else { - return fmt.Sprintf("IDX %s", i.string()) + return fmt.Sprintf("UNIQ %s", i.returnString()) } + return fmt.Sprintf("IDX %s", i.returnString()) } // SeqEntry represents a sequence for tables with auto-incrementing primary keys. @@ -126,7 +123,7 @@ func (s *SeqEntry) GetTableName() protoreflect.FullName { return s.TableName } -func (s *SeqEntry) doNotImplement() {} +func (*SeqEntry) doNotImplement() {} func (s *SeqEntry) String() string { return fmt.Sprintf("SEQ %s %d", s.TableName, s.Value) diff --git a/orm/encoding/ormkv/entry_test.go b/orm/encoding/ormkv/entry_test.go index 9a78d60825ac..3f23703e1e9d 100644 --- a/orm/encoding/ormkv/entry_test.go +++ b/orm/encoding/ormkv/entry_test.go @@ -3,12 +3,11 @@ package ormkv_test import ( "testing" - "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "google.golang.org/protobuf/reflect/protoreflect" + "gotest.tools/v3/assert" ) var aFullName = (&testpb.ExampleTable{}).ProtoReflect().Descriptor().FullName() @@ -22,7 +21,7 @@ func TestPrimaryKeyEntry(t *testing.T) { assert.Equal(t, `PK testpb.ExampleTable 1/abc -> {"i32":-1}`, entry.String()) assert.Equal(t, aFullName, entry.GetTableName()) - // prefix key + // Prefix key. entry = &ormkv.PrimaryKeyEntry{ TableName: aFullName, Key: encodeutil.ValuesOf(uint32(1), "abc"), @@ -53,7 +52,7 @@ func TestIndexKeyEntry(t *testing.T) { assert.Equal(t, `UNIQ testpb.ExampleTable u32 : 10 -> abc/-1`, entry.String()) assert.Equal(t, aFullName, entry.GetTableName()) - // prefix key + // Prefix key. entry = &ormkv.IndexKeyEntry{ TableName: aFullName, Fields: []protoreflect.Name{"u32", "i32", "str"}, @@ -63,7 +62,7 @@ func TestIndexKeyEntry(t *testing.T) { assert.Equal(t, `IDX testpb.ExampleTable u32/i32/str : 10/-1 -> _`, entry.String()) assert.Equal(t, aFullName, entry.GetTableName()) - // prefix key + // Prefix key. entry = &ormkv.IndexKeyEntry{ TableName: aFullName, Fields: []protoreflect.Name{"str", "i32"}, diff --git a/orm/encoding/ormkv/index_key.go b/orm/encoding/ormkv/index_key.go index 55284f220636..50b023d0bb68 100644 --- a/orm/encoding/ormkv/index_key.go +++ b/orm/encoding/ormkv/index_key.go @@ -5,7 +5,6 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -21,11 +20,11 @@ var _ IndexCodec = &IndexKeyCodec{} // provided message descriptor, index and primary key fields. func NewIndexKeyCodec(prefix []byte, messageType protoreflect.MessageType, indexFields, primaryKeyFields []protoreflect.Name) (*IndexKeyCodec, error) { if len(indexFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("index fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("index fields are empty") } if len(primaryKeyFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("primary key fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("primary key fields are empty") } indexFieldMap := map[protoreflect.Name]int{} @@ -63,14 +62,14 @@ func NewIndexKeyCodec(prefix []byte, messageType protoreflect.MessageType, index func (cdc IndexKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey []protoreflect.Value, err error) { values, err := cdc.DecodeKey(bytes.NewReader(k)) - // got prefix key + // Got prefix key. if err == io.EOF { return values, nil, nil } else if err != nil { return nil, nil, err } - // got prefix key + // Got prefix key. if len(values) < len(cdc.fieldCodecs) { return values, nil, nil } @@ -102,11 +101,11 @@ func (cdc IndexKeyCodec) DecodeEntry(k, v []byte) (Entry, error) { func (cdc IndexKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { indexEntry, ok := entry.(*IndexKeyEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } if indexEntry.TableName != cdc.messageType.Descriptor().FullName() { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } bz, err := cdc.KeyCodec.EncodeKey(indexEntry.IndexValues) diff --git a/orm/encoding/ormkv/index_key_test.go b/orm/encoding/ormkv/index_key_test.go index 9625641bf1c6..0146011370b1 100644 --- a/orm/encoding/ormkv/index_key_test.go +++ b/orm/encoding/ormkv/index_key_test.go @@ -5,12 +5,11 @@ import ( "fmt" "testing" - "gotest.tools/v3/assert" - "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "gotest.tools/v3/assert" + "pgregory.net/rapid" ) func TestIndexKeyCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/key_codec.go b/orm/encoding/ormkv/key_codec.go index 4d16a7bb9b8c..13eb1537443d 100644 --- a/orm/encoding/ormkv/key_codec.go +++ b/orm/encoding/ormkv/key_codec.go @@ -4,12 +4,10 @@ import ( "bytes" "io" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - - "google.golang.org/protobuf/reflect/protoreflect" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "google.golang.org/protobuf/reflect/protoreflect" ) type KeyCodec struct { @@ -43,7 +41,7 @@ func NewKeyCodec(prefix []byte, messageType protoreflect.MessageType, fieldNames nonTerminal := i != n-1 field := messageFields.ByName(fieldNames[i]) if field == nil { - return nil, ormerrors.FieldNotFound.Wrapf("field %s on %s", fieldNames[i], messageType.Descriptor().FullName()) + return nil, ormerrors.ErrFieldNotFound.Wrapf("field %s on %s", fieldNames[i], messageType.Descriptor().FullName()) } cdc, err := ormfield.GetCodec(field, nonTerminal) if err != nil { @@ -89,11 +87,11 @@ func (cdc *KeyCodec) EncodeKey(values []protoreflect.Value) ([]byte, error) { n := len(values) if n > len(cdc.fieldCodecs) { - return nil, ormerrors.IndexOutOfBounds.Wrapf("cannot encode %d values into %d fields", n, len(cdc.fieldCodecs)) + return nil, ormerrors.ErrIndexOutOfBounds.Wrapf("cannot encode %d values into %d fields", n, len(cdc.fieldCodecs)) } for i := 0; i < n; i++ { - if err = cdc.fieldCodecs[i].Encode(values[i], w); err != nil { + if err := cdc.fieldCodecs[i].Encode(values[i], w); err != nil { return nil, err } } @@ -170,13 +168,13 @@ func (cdc *KeyCodec) CompareKeys(values1, values2 []protoreflect.Value) int { var cmp int for i := 0; i < n; i++ { cmp = cdc.fieldCodecs[i].Compare(values1[i], values2[i]) - // any non-equal parts determine our ordering + // Any non-equal parts determine our ordering. if cmp != 0 { return cmp } } - // values are equal but arrays of different length + // Values are equal but arrays of different length. if j == k { return 0 } else if j < k { @@ -192,7 +190,7 @@ func (cdc KeyCodec) ComputeKeyBufferSize(values []protoreflect.Value) (int, erro size := cdc.fixedSize n := len(values) for _, sz := range cdc.variableSizers { - // handle prefix key encoding case where don't need all the sizers + // Handle prefix key encoding case where don't need all the sizers. if sz.i >= n { return size, nil } @@ -235,7 +233,7 @@ func (cdc KeyCodec) CheckValidRangeIterationKeys(start, end []protoreflect.Value } if longest > len(cdc.fieldCodecs) { - return ormerrors.IndexOutOfBounds + return ormerrors.ErrIndexOutOfBounds } i := 0 @@ -248,13 +246,13 @@ func (cdc KeyCodec) CheckValidRangeIterationKeys(start, end []protoreflect.Value cmp = fieldCdc.Compare(x, y) if cmp > 0 { - return ormerrors.InvalidRangeIterationKeys.Wrapf( + return ormerrors.ErrInvalidRangeIterationKeys.Wrapf( "start must be before end for field %s", cdc.fieldDescriptors[i].FullName(), ) } else if !fieldCdc.IsOrdered() && cmp != 0 { descriptor := cdc.fieldDescriptors[i] - return ormerrors.InvalidRangeIterationKeys.Wrapf( + return ormerrors.ErrInvalidRangeIterationKeys.Wrapf( "field %s of kind %s doesn't support ordered range iteration", descriptor.FullName(), descriptor.Kind(), @@ -264,16 +262,16 @@ func (cdc KeyCodec) CheckValidRangeIterationKeys(start, end []protoreflect.Value } } - // the last prefix value must not be equal if the key lengths are the same + // The last prefix value must not be equal if the key lengths are the same. if lenStart == lenEnd { if cmp == 0 { - return ormerrors.InvalidRangeIterationKeys + return ormerrors.ErrInvalidRangeIterationKeys } } else { - // check any remaining values in start or end + // Check any remaining values in start or end. for j := i; j < longest; j++ { if !cdc.fieldCodecs[j].IsOrdered() { - return ormerrors.InvalidRangeIterationKeys.Wrapf( + return ormerrors.ErrInvalidRangeIterationKeys.Wrapf( "field %s of kind %s doesn't support ordered range iteration", cdc.fieldDescriptors[j].FullName(), cdc.fieldDescriptors[j].Kind(), diff --git a/orm/encoding/ormkv/key_codec_test.go b/orm/encoding/ormkv/key_codec_test.go index 2b5ae8e7d7d6..1eef903bd2c9 100644 --- a/orm/encoding/ormkv/key_codec_test.go +++ b/orm/encoding/ormkv/key_codec_test.go @@ -5,14 +5,13 @@ import ( "io" "testing" - "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" - "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" + "google.golang.org/protobuf/reflect/protoreflect" + "gotest.tools/v3/assert" + "pgregory.net/rapid" ) func TestKeyCodec(t *testing.T) { @@ -24,10 +23,10 @@ func TestKeyCodec(t *testing.T) { bz1 := assertEncDecKey(t, key, keyValues) if key.Codec.IsFullyOrdered() { - // check if ordered keys have ordered encodings + // Check if ordered keys have ordered encodings. keyValues2 := key.Draw(t, "values2") bz2 := assertEncDecKey(t, key, keyValues2) - // bytes comparison should equal comparison of values + // Bytes comparison should equal comparison of values. assert.Equal(t, key.Codec.CompareKeys(keyValues, keyValues2), bytes.Compare(bz1, bz2)) } } @@ -170,12 +169,13 @@ func TestCompareValues(t *testing.T) { }, } for _, test := range tests { + test := test t.Run(test.name, func(t *testing.T) { assert.Equal( t, test.expect, cdc.CompareKeys(test.values1, test.values2), ) - // CheckValidRangeIterationKeys should give comparable results + // CheckValidRangeIterationKeys should give comparable results. err := cdc.CheckValidRangeIterationKeys(test.values1, test.values2) if test.validRange { assert.NilError(t, err) @@ -202,6 +202,7 @@ func TestDecodePrefixKey(t *testing.T) { }, } for _, test := range tests { + test := test t.Run(test.name, func(t *testing.T) { bz, err := cdc.EncodeKey(test.values) assert.NilError(t, err) @@ -286,6 +287,7 @@ func TestValidRangeIterationKeys(t *testing.T) { }, } for _, test := range tests { + test := test t.Run(test.name, func(t *testing.T) { err := cdc.CheckValidRangeIterationKeys(test.values1, test.values2) if test.expectErr { diff --git a/orm/encoding/ormkv/primary_key.go b/orm/encoding/ormkv/primary_key.go index ff4509cb562e..7c6589622b9a 100644 --- a/orm/encoding/ormkv/primary_key.go +++ b/orm/encoding/ormkv/primary_key.go @@ -5,9 +5,7 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -38,7 +36,7 @@ var _ IndexCodec = PrimaryKeyCodec{} func (p PrimaryKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey []protoreflect.Value, err error) { indexFields, err = p.DecodeKey(bytes.NewReader(k)) - // got prefix key + // Got prefix key. if err == io.EOF { return indexFields, nil, nil } else if err != nil { @@ -46,8 +44,8 @@ func (p PrimaryKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey [] } if len(indexFields) == len(p.fieldCodecs) { - // for primary keys the index fields are the primary key - // but only if we don't have a prefix key + // For primary keys the index fields are the primary key + // but only if we don't have a prefix key. primaryKey = indexFields } return indexFields, primaryKey, nil @@ -77,11 +75,11 @@ func (p PrimaryKeyCodec) DecodeEntry(k, v []byte) (Entry, error) { func (p PrimaryKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { pkEntry, ok := entry.(*PrimaryKeyEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("expected %T, got %T", &PrimaryKeyEntry{}, entry) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("expected %T, got %T", &PrimaryKeyEntry{}, entry) } if pkEntry.TableName != p.messageType.Descriptor().FullName() { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf( + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf( "wrong table name, got %s, expected %s", pkEntry.TableName, p.messageType.Descriptor().FullName(), @@ -98,8 +96,8 @@ func (p PrimaryKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { } func (p PrimaryKeyCodec) marshal(key []protoreflect.Value, message proto.Message) (v []byte, err error) { - // first clear the priamry key values because these are already stored in - // the key so we don't need to store them again in the value + // First clear the priamry key values because these are already stored in + // the key so we don't need to store them again in the value. p.ClearValues(message.ProtoReflect()) v, err = proto.MarshalOptions{Deterministic: true}.Marshal(message) @@ -107,7 +105,7 @@ func (p PrimaryKeyCodec) marshal(key []protoreflect.Value, message proto.Message return nil, err } - // set the primary key values again returning the message to its original state + // Set the primary key values again returning the message to its original state. p.SetKeyValues(message.ProtoReflect(), key) return v, nil @@ -125,7 +123,7 @@ func (p *PrimaryKeyCodec) Unmarshal(key []protoreflect.Value, value []byte, mess return err } - // rehydrate primary key + // Rehydrate primary key. p.SetKeyValues(message.ProtoReflect(), key) return nil } diff --git a/orm/encoding/ormkv/primary_key_test.go b/orm/encoding/ormkv/primary_key_test.go index ece72754a7ec..22bf3b0de8eb 100644 --- a/orm/encoding/ormkv/primary_key_test.go +++ b/orm/encoding/ormkv/primary_key_test.go @@ -5,14 +5,13 @@ import ( "fmt" "testing" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" + "github.com/cosmos/cosmos-sdk/orm/internal/testpb" + "github.com/cosmos/cosmos-sdk/orm/internal/testutil" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/testing/protocmp" "gotest.tools/v3/assert" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" - "github.com/cosmos/cosmos-sdk/orm/internal/testutil" ) func TestPrimaryKeyCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/seq.go b/orm/encoding/ormkv/seq.go index 59e38dc0e67f..2f958203fe6b 100644 --- a/orm/encoding/ormkv/seq.go +++ b/orm/encoding/ormkv/seq.go @@ -5,7 +5,6 @@ import ( "encoding/binary" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -24,7 +23,7 @@ var _ EntryCodec = &SeqCodec{} func (s SeqCodec) DecodeEntry(k, v []byte) (Entry, error) { if !bytes.Equal(k, s.prefix) { - return nil, ormerrors.UnexpectedDecodePrefix + return nil, ormerrors.ErrUnexpectedDecodePrefix } x, err := s.DecodeValue(v) @@ -41,11 +40,11 @@ func (s SeqCodec) DecodeEntry(k, v []byte) (Entry, error) { func (s SeqCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { seqEntry, ok := entry.(*SeqEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } if seqEntry.TableName != s.messageType { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } return s.prefix, s.EncodeValue(seqEntry.Value), nil @@ -55,13 +54,13 @@ func (s SeqCodec) Prefix() []byte { return s.prefix } -func (s SeqCodec) EncodeValue(seq uint64) (v []byte) { +func (SeqCodec) EncodeValue(seq uint64) (v []byte) { bz := make([]byte, binary.MaxVarintLen64) n := binary.PutUvarint(bz, seq) return bz[:n] } -func (s SeqCodec) DecodeValue(v []byte) (uint64, error) { +func (SeqCodec) DecodeValue(v []byte) (uint64, error) { if len(v) == 0 { return 0, nil } diff --git a/orm/encoding/ormkv/seq_test.go b/orm/encoding/ormkv/seq_test.go index 90a3c2b8c201..d22fd0f62af5 100644 --- a/orm/encoding/ormkv/seq_test.go +++ b/orm/encoding/ormkv/seq_test.go @@ -5,11 +5,9 @@ import ( "testing" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - + "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "gotest.tools/v3/assert" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" ) func TestSeqCodec(t *testing.T) { diff --git a/orm/encoding/ormkv/unique_key.go b/orm/encoding/ormkv/unique_key.go index e9d36cb5ae6f..39c671b9d6d7 100644 --- a/orm/encoding/ormkv/unique_key.go +++ b/orm/encoding/ormkv/unique_key.go @@ -5,7 +5,6 @@ import ( "io" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" - "google.golang.org/protobuf/reflect/protoreflect" ) @@ -25,11 +24,11 @@ var _ IndexCodec = &UniqueKeyCodec{} // provided message descriptor, index and primary key fields. func NewUniqueKeyCodec(prefix []byte, messageType protoreflect.MessageType, indexFields, primaryKeyFields []protoreflect.Name) (*UniqueKeyCodec, error) { if len(indexFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("index fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("index fields are empty") } if len(primaryKeyFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("primary key fields are empty") + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("primary key fields are empty") } keyCodec, err := NewKeyCodec(prefix, messageType, indexFields) @@ -64,10 +63,10 @@ func NewUniqueKeyCodec(prefix []byte, messageType protoreflect.MessageType, inde } } - // if there is nothing in the value we have a trivial unique index - // which shouldn't actually be a unique index at all + // If there is nothing in the value we have a trivial unique index + // which shouldn't actually be a unique index at all. if len(valueFields) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("unique index %s on table %s introduces no new uniqueness constraint not already in the primary key and should not be marked as unique", + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("unique index %s on table %s introduces no new uniqueness constraint not already in the primary key and should not be marked as unique", indexFields, messageType.Descriptor().FullName()) } @@ -86,14 +85,14 @@ func NewUniqueKeyCodec(prefix []byte, messageType protoreflect.MessageType, inde func (u UniqueKeyCodec) DecodeIndexKey(k, v []byte) (indexFields, primaryKey []protoreflect.Value, err error) { ks, err := u.keyCodec.DecodeKey(bytes.NewReader(k)) - // got prefix key + // Got prefix key. if err == io.EOF { return ks, nil, err } else if err != nil { return nil, nil, err } - // got prefix key + // Got prefix key. if len(ks) < len(u.keyCodec.fieldCodecs) { return ks, nil, err } @@ -107,12 +106,12 @@ func (u UniqueKeyCodec) DecodeIndexKey(k, v []byte) (indexFields, primaryKey []p return ks, pk, nil } -func (cdc UniqueKeyCodec) extractPrimaryKey(keyValues, valueValues []protoreflect.Value) []protoreflect.Value { - numPkFields := len(cdc.pkFieldOrder) +func (u UniqueKeyCodec) extractPrimaryKey(keyValues, valueValues []protoreflect.Value) []protoreflect.Value { + numPkFields := len(u.pkFieldOrder) pkValues := make([]protoreflect.Value, numPkFields) for i := 0; i < numPkFields; i++ { - fo := cdc.pkFieldOrder[i] + fo := u.pkFieldOrder[i] if fo.inKey { pkValues[i] = keyValues[fo.i] } else { @@ -141,7 +140,7 @@ func (u UniqueKeyCodec) DecodeEntry(k, v []byte) (Entry, error) { func (u UniqueKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { indexEntry, ok := entry.(*IndexKeyEntry) if !ok { - return nil, nil, ormerrors.BadDecodeEntry + return nil, nil, ormerrors.ErrBadDecodeEntry } k, err = u.keyCodec.EncodeKey(indexEntry.IndexValues) if err != nil { @@ -150,7 +149,7 @@ func (u UniqueKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { n := len(indexEntry.PrimaryKey) if n != len(u.pkFieldOrder) { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("wrong primary key length") + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("wrong primary key length") } var values []protoreflect.Value @@ -158,13 +157,11 @@ func (u UniqueKeyCodec) EncodeEntry(entry Entry) (k, v []byte, err error) { value := indexEntry.PrimaryKey[i] fieldOrder := u.pkFieldOrder[i] if !fieldOrder.inKey { - // goes in values because it is not present in the index key otherwise + // Goes in values because it is not present in the index key otherwise. values = append(values, value) - } else { - // does not go in values, but we need to verify that the value in index values matches the primary key value - if u.keyCodec.fieldCodecs[fieldOrder.i].Compare(value, indexEntry.IndexValues[fieldOrder.i]) != 0 { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("value in primary key does not match corresponding value in index key") - } + // Does not go in values, but we need to verify that the value in index values matches the primary key value. + } else if u.keyCodec.fieldCodecs[fieldOrder.i].Compare(value, indexEntry.IndexValues[fieldOrder.i]) != 0 { + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("value in primary key does not match corresponding value in index key") } } diff --git a/orm/encoding/ormkv/unique_key_test.go b/orm/encoding/ormkv/unique_key_test.go index c015e671e397..f30c343a4e0c 100644 --- a/orm/encoding/ormkv/unique_key_test.go +++ b/orm/encoding/ormkv/unique_key_test.go @@ -5,14 +5,13 @@ import ( "fmt" "testing" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" - "pgregory.net/rapid" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + "gotest.tools/v3/assert" + "pgregory.net/rapid" ) func TestUniqueKeyCodec(t *testing.T) { @@ -20,9 +19,9 @@ func TestUniqueKeyCodec(t *testing.T) { keyCodec := testutil.TestKeyCodecGen(1, 5).Draw(t, "keyCodec") pkCodec := testutil.TestKeyCodecGen(1, 5).Draw(t, "primaryKeyCodec") - // check if we have a trivial unique index where all of the fields + // Check if we have a trivial unique index where all of the fields // in the primary key are in the unique key, we should expect an - // error in this case + // error in this case. isInPk := map[protoreflect.Name]bool{} for _, spec := range pkCodec.KeySpecs { isInPk[spec.FieldName] = true @@ -46,9 +45,8 @@ func TestUniqueKeyCodec(t *testing.T) { if isTrivialUniqueKey { assert.ErrorContains(t, err, "no new uniqueness constraint") return - } else { - assert.NilError(t, err) } + assert.NilError(t, err) for i := 0; i < 100; i++ { a := testutil.GenA.Draw(t, fmt.Sprintf("a%d", i)) @@ -89,5 +87,5 @@ func TestUniqueKeyCodec(t *testing.T) { func TestTrivialUnique(t *testing.T) { _, err := ormkv.NewUniqueKeyCodec(nil, (&testpb.ExampleTable{}).ProtoReflect().Type(), []protoreflect.Name{"u32", "str"}, []protoreflect.Name{"str", "u32"}) - assert.ErrorIs(t, err, ormerrors.InvalidTableDefinition) + assert.ErrorIs(t, err, ormerrors.ErrInvalidTableDefinition) } diff --git a/orm/internal/codegen/codegen.go b/orm/internal/codegen/codegen.go index b895d9909cfc..bd58330805cc 100644 --- a/orm/internal/codegen/codegen.go +++ b/orm/internal/codegen/codegen.go @@ -4,12 +4,11 @@ import ( "fmt" "os" + ormv1 "cosmossdk.io/api/cosmos/orm/v1" + "github.com/cosmos/cosmos-proto/generator" "google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/pluginpb" - - ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-proto/generator" ) const ( diff --git a/orm/internal/codegen/file.go b/orm/internal/codegen/file.go index 681e49cf89e2..28b8255d68cc 100644 --- a/orm/internal/codegen/file.go +++ b/orm/internal/codegen/file.go @@ -33,7 +33,7 @@ func (f fileGen) gen() error { } singletonDesc := proto.GetExtension(msg.Desc.Options(), ormv1.E_Singleton).(*ormv1.SingletonDescriptor) if singletonDesc != nil { - // do some singleton magic + // Do some singleton magic. singletonGen, err := newSingletonGen(f, msg, singletonDesc) if err != nil { return err @@ -41,7 +41,7 @@ func (f fileGen) gen() error { singletonGen.gen() } - if tableDesc != nil || singletonDesc != nil { // message is one of the tables, + if tableDesc != nil || singletonDesc != nil { // Message is one of the tables,. stores = append(stores, msg) } } @@ -66,7 +66,7 @@ func (f fileGen) genStoreInterface(stores []*protogen.Message) { } func (f fileGen) genStoreStruct(stores []*protogen.Message) { - // struct + // Struct. f.P("type ", f.storeStructName(), " struct {") for _, message := range stores { f.P(f.param(message.GoIdent.GoName), " ", f.messageTableInterfaceName(message)) @@ -74,10 +74,6 @@ func (f fileGen) genStoreStruct(stores []*protogen.Message) { f.P("}") } -func (f fileGen) storeAccessorName() string { - return f.storeInterfaceName() -} - func (f fileGen) storeInterfaceName() string { return strcase.ToCamel(f.fileShortName()) + "Store" } @@ -100,19 +96,11 @@ func fileShortName(file *protogen.File) string { return strcase.ToCamel(shortName) } -func (f fileGen) messageTableInterfaceName(m *protogen.Message) string { +func (fileGen) messageTableInterfaceName(m *protogen.Message) string { return m.GoIdent.GoName + "Table" } -func (f fileGen) messageReaderInterfaceName(m *protogen.Message) string { - return m.GoIdent.GoName + "Reader" -} - -func (f fileGen) messageTableVar(m *protogen.Message) string { - return f.param(m.GoIdent.GoName + "Table") -} - -func (f fileGen) param(name string) string { +func (fileGen) param(name string) string { return strcase.ToLowerCamel(name) } @@ -125,7 +113,7 @@ func (f fileGen) messageConstructorName(m *protogen.Message) string { } func (f fileGen) genStoreMethods(stores []*protogen.Message) { - // getters + // Getters. for _, msg := range stores { name := f.messageTableInterfaceName(msg) f.P("func(x ", f.storeStructName(), ") ", name, "() ", name, "{") diff --git a/orm/internal/codegen/index.go b/orm/internal/codegen/index.go index 9b889d431e46..ce64b2ec50af 100644 --- a/orm/internal/codegen/index.go +++ b/orm/internal/codegen/index.go @@ -5,19 +5,18 @@ import ( "strings" "github.com/iancoleman/strcase" - "google.golang.org/protobuf/reflect/protoreflect" ) func (t tableGen) genIndexKeys() { - // interface that all keys must adhere to + // Interface that all keys must adhere to. t.P("type ", t.indexKeyInterfaceName(), " interface {") t.P("id() uint32") - t.P("values() []interface{}") + t.P("values() []any") t.P(t.param(t.indexKeyInterfaceName()), "()") t.P("}") t.P() - // start with primary key.. + // Start with primary key.. t.P("// primary key starting index..") t.genIndex(t.table.PrimaryKey.Fields, 0, true) for _, idx := range t.table.Index { @@ -43,47 +42,10 @@ func (t tableGen) genValueFunc() { t.P("}") } -func (t tableGen) genIndexMethods(idxKeyName string) { - receiverFunc := fmt.Sprintf("func (x %s) ", idxKeyName) - t.P(receiverFunc, "id() uint32 { return ", t.table.Id, " /* primary key */ }") - t.P(receiverFunc, "values() []interface{} { return x.vs }") - t.P(receiverFunc, t.param(t.indexKeyInterfaceName()), "() {}") - t.P() -} - -func (t tableGen) genIndexInterfaceGuard(idxKeyName string) { - t.P("var _ ", t.indexKeyInterfaceName(), " = ", idxKeyName, "{}") - t.P() -} - func (t tableGen) indexKeyInterfaceName() string { return t.msg.GoIdent.GoName + "IndexKey" } -func (t tableGen) genIndexKey(idxKeyName string) { - t.P("type ", idxKeyName, " struct {") - t.P("vs []interface{}") - t.P("}") - t.P() -} - -func (t tableGen) indexKeyParts(names []protoreflect.Name) string { - cnames := make([]string, len(names)) - for i, name := range names { - cnames[i] = strcase.ToCamel(string(name)) - } - return strings.Join(cnames, "") -} - -func (t tableGen) indexKeyName(names []protoreflect.Name) string { - cnames := make([]string, len(names)) - for i, name := range names { - cnames[i] = strcase.ToCamel(string(name)) - } - joinedNames := strings.Join(cnames, "") - return t.msg.GoIdent.GoName + joinedNames + "IndexKey" -} - func (t tableGen) indexStructName(fields []string) string { names := make([]string, len(fields)) for i, field := range fields { @@ -103,7 +65,7 @@ func (t tableGen) genIndex(fields string, id uint32, isPrimaryKey bool) { } t.P("type ", idxKeyName, " struct {") - t.P("vs []interface{}") + t.P("vs []any") t.P("}") t.genIndexInterfaceMethods(id, idxKeyName) @@ -116,7 +78,7 @@ func (t tableGen) genIndex(fields string, id uint32, isPrimaryKey bool) { func (t tableGen) genIndexInterfaceMethods(id uint32, indexStructName string) { funPrefix := fmt.Sprintf("func (x %s) ", indexStructName) t.P(funPrefix, "id() uint32 {return ", id, "}") - t.P(funPrefix, "values() []interface{} {return x.vs}") + t.P(funPrefix, "values() []any {return x.vs}") t.P(funPrefix, t.param(t.indexKeyInterfaceName()), "() {}") t.P() } @@ -130,7 +92,7 @@ func (t tableGen) genWithMethods(indexStructName string, parts []string) { funcName := "With" + strings.Join(camelParts, "") t.P(funcPrefix, funcName, "(", t.fieldArgsFromStringSlice(parts), ") ", indexStructName, "{") - t.P("this.vs = []interface{}{", strings.Join(parts, ","), "}") + t.P("this.vs = []any{", strings.Join(parts, ","), "}") t.P("return this") t.P("}") t.P() diff --git a/orm/internal/codegen/query.go b/orm/internal/codegen/query.go index 974a6b40c24c..e799c9b396a0 100644 --- a/orm/internal/codegen/query.go +++ b/orm/internal/codegen/query.go @@ -84,7 +84,7 @@ func (g queryProtoGen) gen() error { func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.TableDescriptor) error { name := msg.Desc.Name() g.svc.F("// Get queries the %s table by its primary key.", name) - g.svc.F("rpc Get%s(Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway + g.svc.F("rpc Get%s(Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway. g.startRequestType("Get%sRequest", name) g.msgs.Indent() @@ -118,7 +118,7 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab fieldsCamel := fieldsToCamelCase(idx.Fields) methodName := fmt.Sprintf("Get%sBy%s", name, fieldsCamel) g.svc.F("// %s queries the %s table by its %s index", methodName, name, fieldsCamel) - g.svc.F("rpc %s(%sRequest) returns (%sResponse) {}", methodName, methodName, methodName) // TODO grpc gateway + g.svc.F("rpc %s(%sRequest) returns (%sResponse) {}", methodName, methodName, methodName) // TODO grpc gateway. g.startRequestType("%sRequest", methodName) g.msgs.Indent() @@ -144,7 +144,7 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab g.imports["cosmos/base/query/v1beta1/pagination.proto"] = true g.svc.F("// List%s queries the %s table using prefix and range queries against defined indexes.", name, name) - g.svc.F("rpc List%s(List%sRequest) returns (List%sResponse) {}", name, name, name) // TODO grpc gateway + g.svc.F("rpc List%s(List%sRequest) returns (List%sResponse) {}", name, name, name) // TODO grpc gateway. g.startRequestType("List%sRequest", name) g.msgs.Indent() g.msgs.F("// IndexKey specifies the value of an index key to use in prefix and range queries.") @@ -152,11 +152,11 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab g.msgs.Indent() indexFields := []string{desc.PrimaryKey.Fields} - // the primary key has field number 1 + // The primary key has field number 1. fieldNums := []uint32{1} for _, index := range desc.Index { indexFields = append(indexFields, index.Fields) - // index field numbers are their id + 1 + // Index field numbers are their id + 1. fieldNums = append(fieldNums, index.Id+1) } @@ -231,7 +231,7 @@ func (g queryProtoGen) genTableRPCMethods(msg *protogen.Message, desc *ormv1.Tab func (g queryProtoGen) genSingletonRPCMethods(msg *protogen.Message) error { name := msg.Desc.Name() g.svc.F("// Get%s queries the %s singleton.", name, name) - g.svc.F("rpc Get%s (Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway + g.svc.F("rpc Get%s (Get%sRequest) returns (Get%sResponse) {}", name, name, name) // TODO grpc gateway. g.startRequestType("Get%sRequest", name) g.msgs.F("}") g.msgs.F("") @@ -284,8 +284,8 @@ func newWriter() *writer { } } -func (w *writer) F(format string, args ...interface{}) { - _, err := w.Write([]byte(w.indentStr)) +func (w *writer) F(format string, args ...any) { + _, err := w.WriteString(w.indentStr) if err != nil { panic(err) } @@ -302,7 +302,7 @@ func (w *writer) F(format string, args ...interface{}) { } func (w *writer) Indent() { - w.indent += 1 + w.indent++ w.updateIndent() } @@ -314,6 +314,6 @@ func (w *writer) updateIndent() { } func (w *writer) Dedent() { - w.indent -= 1 + w.indent-- w.updateIndent() } diff --git a/orm/internal/codegen/singleton.go b/orm/internal/codegen/singleton.go index 40a265235c04..84422c8183b1 100644 --- a/orm/internal/codegen/singleton.go +++ b/orm/internal/codegen/singleton.go @@ -3,12 +3,10 @@ package codegen import ( "fmt" - "google.golang.org/protobuf/compiler/protogen" - "google.golang.org/protobuf/types/dynamicpb" - ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/types/dynamicpb" ) type singletonGen struct { @@ -59,7 +57,7 @@ func (s singletonGen) genInterfaceGuard() { func (s singletonGen) genMethods() { receiver := fmt.Sprintf("func (x %s) ", s.messageTableReceiverName(s.msg)) varName := s.param(s.msg.GoIdent.GoName) - // Get + // Get. s.P(receiver, "Get(ctx ", contextPkg.Ident("Context"), ") (*", s.msg.GoIdent.GoName, ", error) {") s.P(varName, " := &", s.msg.GoIdent.GoName, "{}") s.P("_, err := x.table.Get(ctx, ", varName, ")") @@ -67,7 +65,7 @@ func (s singletonGen) genMethods() { s.P("}") s.P() - // Save + // Save. s.P(receiver, "Save(ctx ", contextPkg.Ident("Context"), ", ", varName, " *", s.msg.GoIdent.GoName, ") error {") s.P("return x.table.Save(ctx, ", varName, ")") s.P("}") diff --git a/orm/internal/codegen/table.go b/orm/internal/codegen/table.go index d629b0c29802..c2a64b99dce3 100644 --- a/orm/internal/codegen/table.go +++ b/orm/internal/codegen/table.go @@ -4,14 +4,12 @@ import ( "fmt" "strings" - "google.golang.org/protobuf/compiler/protogen" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/types/dynamicpb" - ormv1 "cosmossdk.io/api/cosmos/orm/v1" - "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/dynamicpb" ) type tableGen struct { @@ -48,7 +46,7 @@ func newTableGen(fileGen fileGen, msg *protogen.Message, table *ormv1.TableDescr } func (t tableGen) gen() { - t.getTableInterface() + t.tableInterface() t.genIterator() t.genIndexKeys() t.genStruct() @@ -57,7 +55,7 @@ func (t tableGen) gen() { t.genConstructor() } -func (t tableGen) getTableInterface() { +func (t tableGen) tableInterface() { t.P("type ", t.messageTableInterfaceName(t.msg), " interface {") t.P("Insert(ctx ", contextPkg.Ident("Context"), ", ", t.param(t.msg.GoIdent.GoName), " *", t.QualifiedGoIdent(t.msg.GoIdent), ") error") if t.table.PrimaryKey.AutoIncrement { @@ -85,16 +83,16 @@ func (t tableGen) getTableInterface() { } // returns the has and get (in that order) function signature for unique indexes. -func (t tableGen) uniqueIndexSig(idxFields string) (string, string, string) { +func (t tableGen) uniqueIndexSig(idxFields string) (hasFuncSig, getFuncSig, getFuncName string) { fieldsSlc := strings.Split(idxFields, ",") camelFields := fieldsToCamelCase(idxFields) hasFuncName := "HasBy" + camelFields - getFuncName := "GetBy" + camelFields + getFuncName = "GetBy" + camelFields args := t.fieldArgsFromStringSlice(fieldsSlc) - hasFuncSig := fmt.Sprintf("%s (ctx context.Context, %s) (found bool, err error)", hasFuncName, args) - getFuncSig := fmt.Sprintf("%s (ctx context.Context, %s) (*%s, error)", getFuncName, args, t.msg.GoIdent.GoName) + hasFuncSig = fmt.Sprintf("%s (ctx context.Context, %s) (found bool, err error)", hasFuncName, args) + getFuncSig = fmt.Sprintf("%s (ctx context.Context, %s) (*%s, error)", getFuncName, args, t.msg.GoIdent.GoName) return hasFuncSig, getFuncSig, getFuncName } @@ -109,27 +107,6 @@ func (t tableGen) iteratorName() string { return t.msg.GoIdent.GoName + "Iterator" } -func (t tableGen) getSig() string { - res := "Get" + t.msg.GoIdent.GoName + "(" - res += t.fieldsArgs(t.primaryKeyFields.Names()) - res += ") (*" + t.QualifiedGoIdent(t.msg.GoIdent) + ", error)" - return res -} - -func (t tableGen) hasSig() string { - t.P("Has(ctx ", contextPkg.Ident("Context"), ", ", t.fieldsArgs(t.primaryKeyFields.Names()), ") (found bool, err error)") - return "" -} - -func (t tableGen) listSig() string { - res := "List" + t.msg.GoIdent.GoName + "(" - res += t.indexKeyInterfaceName() - res += ") (" - res += t.iteratorName() - res += ", error)" - return res -} - func (t tableGen) fieldArgsFromStringSlice(names []string) string { args := make([]string, len(names)) for i, name := range names { @@ -171,7 +148,7 @@ func (t tableGen) genTableImpl() { varName := t.param(t.msg.GoIdent.GoName) varTypeName := t.QualifiedGoIdent(t.msg.GoIdent) - // these methods all have the same impl sans their names. so we can just loop and replace. + // These methods all have the same impl sans their names. So we can just loop and replace. methods := []string{"Insert", "Update", "Save", "Delete"} for _, method := range methods { t.P(receiver, method, "(ctx ", contextPkg.Ident("Context"), ", ", varName, " *", varTypeName, ") error {") @@ -192,13 +169,13 @@ func (t tableGen) genTableImpl() { t.P() } - // Has + // Has. t.P(receiver, "Has(ctx ", contextPkg.Ident("Context"), ", ", t.fieldsArgs(t.primaryKeyFields.Names()), ") (found bool, err error) {") t.P("return ", receiverVar, ".table.PrimaryKey().Has(ctx, ", t.primaryKeyFields.String(), ")") t.P("}") t.P() - // Get + // Get. t.P(receiver, "Get(ctx ", contextPkg.Ident("Context"), ", ", t.fieldsArgs(t.primaryKeyFields.Names()), ") (*", varTypeName, ", error) {") t.P("var ", varName, " ", varTypeName) t.P("found, err := ", receiverVar, ".table.PrimaryKey().Get(ctx, &", varName, ", ", t.primaryKeyFields.String(), ")") @@ -216,7 +193,7 @@ func (t tableGen) genTableImpl() { fields := strings.Split(idx.Fields, ",") hasName, getName, _ := t.uniqueIndexSig(idx.Fields) - // has + // Has. t.P("func (", receiverVar, " ", t.messageTableReceiverName(t.msg), ") ", hasName, "{") t.P("return ", receiverVar, ".table.GetIndexByID(", idx.Id, ").(", ormTablePkg.Ident("UniqueIndex"), ").Has(ctx,") @@ -227,7 +204,7 @@ func (t tableGen) genTableImpl() { t.P("}") t.P() - // get + // Get. varName := t.param(t.msg.GoIdent.GoName) varTypeName := t.msg.GoIdent.GoName t.P("func (", receiverVar, " ", t.messageTableReceiverName(t.msg), ") ", getName, "{") @@ -249,28 +226,28 @@ func (t tableGen) genTableImpl() { t.P() } - // List + // List. t.P(receiver, "List(ctx ", contextPkg.Ident("Context"), ", prefixKey ", t.indexKeyInterfaceName(), ", opts ...", ormListPkg.Ident("Option"), ") (", t.iteratorName(), ", error) {") t.P("it, err := ", receiverVar, ".table.GetIndexByID(prefixKey.id()).List(ctx, prefixKey.values(), opts...)") t.P("return ", t.iteratorName(), "{it}, err") t.P("}") t.P() - // ListRange + // ListRange. t.P(receiver, "ListRange(ctx ", contextPkg.Ident("Context"), ", from, to ", t.indexKeyInterfaceName(), ", opts ...", ormListPkg.Ident("Option"), ") (", t.iteratorName(), ", error) {") t.P("it, err := ", receiverVar, ".table.GetIndexByID(from.id()).ListRange(ctx, from.values(), to.values(), opts...)") t.P("return ", t.iteratorName(), "{it}, err") t.P("}") t.P() - // DeleteBy + // DeleteBy. t.P(receiver, "DeleteBy(ctx ", contextPkg.Ident("Context"), ", prefixKey ", t.indexKeyInterfaceName(), ") error {") t.P("return ", receiverVar, ".table.GetIndexByID(prefixKey.id()).DeleteBy(ctx, prefixKey.values()...)") t.P("}") t.P() t.P() - // DeleteRange + // DeleteRange. t.P(receiver, "DeleteRange(ctx ", contextPkg.Ident("Context"), ", from, to ", t.indexKeyInterfaceName(), ") error {") t.P("return ", receiverVar, ".table.GetIndexByID(from.id()).DeleteRange(ctx, from.values(), to.values())") t.P("}") diff --git a/orm/internal/fieldnames/fieldnames.go b/orm/internal/fieldnames/fieldnames.go index e348e3a1971b..2ecdde2f6cac 100644 --- a/orm/internal/fieldnames/fieldnames.go +++ b/orm/internal/fieldnames/fieldnames.go @@ -15,7 +15,7 @@ type FieldNames struct { // CommaSeparatedFieldNames creates a FieldNames instance from a list of comma-separated // fields. func CommaSeparatedFieldNames(fields string) FieldNames { - // normalize cases where there are spaces + // Normalize cases where there are spaces. if strings.IndexByte(fields, ' ') >= 0 { parts := strings.Split(fields, ",") for i, part := range parts { diff --git a/orm/internal/fieldnames/fieldnames_test.go b/orm/internal/fieldnames/fieldnames_test.go index f341fd7e3fe4..379221752374 100644 --- a/orm/internal/fieldnames/fieldnames_test.go +++ b/orm/internal/fieldnames/fieldnames_test.go @@ -4,7 +4,6 @@ import ( "testing" "google.golang.org/protobuf/reflect/protoreflect" - "gotest.tools/v3/assert" ) @@ -22,7 +21,7 @@ func TestFieldNames(t *testing.T) { assert.DeepEqual(t, names, f.Names()) assert.Equal(t, abc, f.String()) - // empty okay + // Empty okay. f = CommaSeparatedFieldNames("") assert.Equal(t, FieldNames{""}, f) assert.Equal(t, 0, len(f.Names())) @@ -33,7 +32,7 @@ func TestFieldNames(t *testing.T) { assert.DeepEqual(t, names, f.Names()) assert.Equal(t, abc, f.String()) - // empty okay + // Empty okay. f = FieldsFromNames([]protoreflect.Name{}) assert.Equal(t, FieldNames{""}, f) f = FieldsFromNames(nil) diff --git a/orm/internal/stablejson/encode.go b/orm/internal/stablejson/encode.go index e9dd143773d0..4e1281420548 100644 --- a/orm/internal/stablejson/encode.go +++ b/orm/internal/stablejson/encode.go @@ -34,9 +34,9 @@ func Marshal(message proto.Message) ([]byte, error) { fd = last.Step.FieldDescriptor() _, _ = fmt.Fprintf(buf, "%q:", fd.Name()) case protopath.ListIndexStep: - fd = beforeLast.Step.FieldDescriptor() // lists always appear in the context of a repeated field + fd = beforeLast.Step.FieldDescriptor() // Lists always appear in the context of a repeated field. case protopath.MapIndexStep: - fd = beforeLast.Step.FieldDescriptor() // maps always appear in the context of a repeated field + fd = beforeLast.Step.FieldDescriptor() // Maps always appear in the context of a repeated field. _, _ = fmt.Fprintf(buf, "%v:", last.Step.MapIndex().Interface()) case protopath.AnyExpandStep: _, _ = fmt.Fprintf(buf, `"@type":%q`, last.Value.Message().Descriptor().FullName()) diff --git a/orm/internal/stablejson/encode_test.go b/orm/internal/stablejson/encode_test.go index 85d8acd57920..87b11f8f9b4e 100644 --- a/orm/internal/stablejson/encode_test.go +++ b/orm/internal/stablejson/encode_test.go @@ -3,15 +3,13 @@ package stablejson_test import ( "testing" - "github.com/stretchr/testify/require" - - "google.golang.org/protobuf/types/known/anypb" - bankv1beta1 "cosmossdk.io/api/cosmos/bank/v1beta1" basev1beta1 "cosmossdk.io/api/cosmos/base/v1beta1" txv1beta1 "cosmossdk.io/api/cosmos/tx/v1beta1" "github.com/cosmos/cosmos-proto/anyutil" "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/anypb" ) func TestStableJSON(t *testing.T) { diff --git a/orm/internal/testkv/compare.go b/orm/internal/testkv/compare.go index 8b3878f4738f..a5f9a9dd66fc 100644 --- a/orm/internal/testkv/compare.go +++ b/orm/internal/testkv/compare.go @@ -3,10 +3,9 @@ package testkv import ( "bytes" - "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "github.com/cosmos/cosmos-sdk/orm/types/kv" + "gotest.tools/v3/assert" ) func AssertBackendsEqual(t assert.TestingT, b1, b2 ormtable.Backend) { diff --git a/orm/internal/testkv/debug.go b/orm/internal/testkv/debug.go index 5891528942b1..b5626bc42cb1 100644 --- a/orm/internal/testkv/debug.go +++ b/orm/internal/testkv/debug.go @@ -4,12 +4,11 @@ import ( "context" "fmt" - "google.golang.org/protobuf/proto" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/stablejson" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "github.com/cosmos/cosmos-sdk/orm/types/kv" + "google.golang.org/protobuf/proto" ) // Debugger is an interface that handles debug info from the debug store wrapper. @@ -217,42 +216,42 @@ type debugHooks struct { writeHooks ormtable.WriteHooks } -func (d debugHooks) ValidateInsert(context context.Context, message proto.Message) error { - jsonBz, err := stablejson.Marshal(message) +func (d debugHooks) ValidateInsert(ctx context.Context, insertMessage proto.Message) error { + jsonBz, err := stablejson.Marshal(insertMessage) if err != nil { return err } d.debugger.Log(fmt.Sprintf( "ORM BEFORE INSERT %s %s", - message.ProtoReflect().Descriptor().FullName(), + insertMessage.ProtoReflect().Descriptor().FullName(), jsonBz, )) if d.validateHooks != nil { - return d.validateHooks.ValidateInsert(context, message) + return d.validateHooks.ValidateInsert(ctx, insertMessage) } return nil } -func (d debugHooks) ValidateUpdate(ctx context.Context, existing, new proto.Message) error { - existingJson, err := stablejson.Marshal(existing) +func (d debugHooks) ValidateUpdate(ctx context.Context, existingMsg, newMsg proto.Message) error { + existingJSON, err := stablejson.Marshal(existingMsg) if err != nil { return err } - newJson, err := stablejson.Marshal(new) + newJSON, err := stablejson.Marshal(newMsg) if err != nil { return err } d.debugger.Log(fmt.Sprintf( "ORM BEFORE UPDATE %s %s -> %s", - existing.ProtoReflect().Descriptor().FullName(), - existingJson, - newJson, + existingMsg.ProtoReflect().Descriptor().FullName(), + existingJSON, + newJSON, )) if d.validateHooks != nil { - return d.validateHooks.ValidateUpdate(ctx, existing, new) + return d.validateHooks.ValidateUpdate(ctx, existingMsg, newMsg) } return nil } @@ -290,25 +289,25 @@ func (d debugHooks) OnInsert(ctx context.Context, message proto.Message) { } } -func (d debugHooks) OnUpdate(ctx context.Context, existing, new proto.Message) { - existingJson, err := stablejson.Marshal(existing) +func (d debugHooks) OnUpdate(ctx context.Context, existingMsg, newMsg proto.Message) { + existingJSON, err := stablejson.Marshal(existingMsg) if err != nil { panic(err) } - newJson, err := stablejson.Marshal(new) + newJSON, err := stablejson.Marshal(newMsg) if err != nil { panic(err) } d.debugger.Log(fmt.Sprintf( "ORM AFTER UPDATE %s %s -> %s", - existing.ProtoReflect().Descriptor().FullName(), - existingJson, - newJson, + existingMsg.ProtoReflect().Descriptor().FullName(), + existingJSON, + newJSON, )) if d.writeHooks != nil { - d.writeHooks.OnUpdate(ctx, existing, new) + d.writeHooks.OnUpdate(ctx, existingMsg, newMsg) } } diff --git a/orm/internal/testkv/leveldb.go b/orm/internal/testkv/leveldb.go index 4e03f3642138..2ee777fff91d 100644 --- a/orm/internal/testkv/leveldb.go +++ b/orm/internal/testkv/leveldb.go @@ -4,14 +4,14 @@ import ( "testing" dbm "github.com/cosmos/cosmos-db" - "gotest.tools/v3/assert" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "gotest.tools/v3/assert" ) -func NewGoLevelDBBackend(t testing.TB) ormtable.Backend { - db, err := dbm.NewGoLevelDB("test", t.TempDir(), nil) - assert.NilError(t, err) +func NewGoLevelDBBackend(tb testing.TB) ormtable.Backend { + tb.Helper() + db, err := dbm.NewGoLevelDB("test", tb.TempDir(), nil) + assert.NilError(tb, err) return ormtable.NewBackend(ormtable.BackendOptions{ CommitmentStore: db, }) diff --git a/orm/internal/testkv/mem.go b/orm/internal/testkv/mem.go index d2c89a2e8db4..26d6ba4fdda9 100644 --- a/orm/internal/testkv/mem.go +++ b/orm/internal/testkv/mem.go @@ -2,7 +2,6 @@ package testkv import ( dbm "github.com/cosmos/cosmos-db" - "github.com/cosmos/cosmos-sdk/orm/model/ormtable" ) @@ -22,6 +21,6 @@ func NewSplitMemBackend() ormtable.Backend { func NewSharedMemBackend() ormtable.Backend { return ormtable.NewBackend(ormtable.BackendOptions{ CommitmentStore: dbm.NewMemDB(), - // commit store is automatically used as the index store + // Commit store is automatically used as the index store. }) } diff --git a/orm/internal/testpb/bank.cosmos_orm.go b/orm/internal/testpb/bank.cosmos_orm.go index 0635179c20e8..4fac9828d4d5 100644 --- a/orm/internal/testpb/bank.cosmos_orm.go +++ b/orm/internal/testpb/bank.cosmos_orm.go @@ -37,7 +37,7 @@ func (i BalanceIterator) Value() (*Balance, error) { type BalanceIndexKey interface { id() uint32 - values() []interface{} + values() []any balanceIndexKey() } @@ -45,33 +45,33 @@ type BalanceIndexKey interface { type BalancePrimaryKey = BalanceAddressDenomIndexKey type BalanceAddressDenomIndexKey struct { - vs []interface{} + vs []any } func (x BalanceAddressDenomIndexKey) id() uint32 { return 0 } -func (x BalanceAddressDenomIndexKey) values() []interface{} { return x.vs } +func (x BalanceAddressDenomIndexKey) values() []any { return x.vs } func (x BalanceAddressDenomIndexKey) balanceIndexKey() {} func (this BalanceAddressDenomIndexKey) WithAddress(address string) BalanceAddressDenomIndexKey { - this.vs = []interface{}{address} + this.vs = []any{address} return this } func (this BalanceAddressDenomIndexKey) WithAddressDenom(address string, denom string) BalanceAddressDenomIndexKey { - this.vs = []interface{}{address, denom} + this.vs = []any{address, denom} return this } type BalanceDenomIndexKey struct { - vs []interface{} + vs []any } func (x BalanceDenomIndexKey) id() uint32 { return 1 } -func (x BalanceDenomIndexKey) values() []interface{} { return x.vs } +func (x BalanceDenomIndexKey) values() []any { return x.vs } func (x BalanceDenomIndexKey) balanceIndexKey() {} func (this BalanceDenomIndexKey) WithDenom(denom string) BalanceDenomIndexKey { - this.vs = []interface{}{denom} + this.vs = []any{denom} return this } @@ -106,7 +106,7 @@ func (this balanceTable) Get(ctx context.Context, address string, denom string) return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &balance, nil } @@ -136,7 +136,7 @@ var _ BalanceTable = balanceTable{} func NewBalanceTable(db ormtable.Schema) (BalanceTable, error) { table := db.GetTable(&Balance{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&Balance{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&Balance{}).ProtoReflect().Descriptor().FullName())) } return balanceTable{table}, nil } @@ -169,7 +169,7 @@ func (i SupplyIterator) Value() (*Supply, error) { type SupplyIndexKey interface { id() uint32 - values() []interface{} + values() []any supplyIndexKey() } @@ -177,15 +177,15 @@ type SupplyIndexKey interface { type SupplyPrimaryKey = SupplyDenomIndexKey type SupplyDenomIndexKey struct { - vs []interface{} + vs []any } func (x SupplyDenomIndexKey) id() uint32 { return 0 } -func (x SupplyDenomIndexKey) values() []interface{} { return x.vs } +func (x SupplyDenomIndexKey) values() []any { return x.vs } func (x SupplyDenomIndexKey) supplyIndexKey() {} func (this SupplyDenomIndexKey) WithDenom(denom string) SupplyDenomIndexKey { - this.vs = []interface{}{denom} + this.vs = []any{denom} return this } @@ -220,7 +220,7 @@ func (this supplyTable) Get(ctx context.Context, denom string) (*Supply, error) return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &supply, nil } @@ -250,7 +250,7 @@ var _ SupplyTable = supplyTable{} func NewSupplyTable(db ormtable.Schema) (SupplyTable, error) { table := db.GetTable(&Supply{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&Supply{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&Supply{}).ProtoReflect().Descriptor().FullName())) } return supplyTable{table}, nil } diff --git a/orm/internal/testpb/test_schema.cosmos_orm.go b/orm/internal/testpb/test_schema.cosmos_orm.go index 93ce0cda021f..5eb4c5398b72 100644 --- a/orm/internal/testpb/test_schema.cosmos_orm.go +++ b/orm/internal/testpb/test_schema.cosmos_orm.go @@ -41,7 +41,7 @@ func (i ExampleTableIterator) Value() (*ExampleTable, error) { type ExampleTableIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleTableIndexKey() } @@ -49,79 +49,79 @@ type ExampleTableIndexKey interface { type ExampleTablePrimaryKey = ExampleTableU32I64StrIndexKey type ExampleTableU32I64StrIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableU32I64StrIndexKey) id() uint32 { return 0 } -func (x ExampleTableU32I64StrIndexKey) values() []interface{} { return x.vs } +func (x ExampleTableU32I64StrIndexKey) values() []any { return x.vs } func (x ExampleTableU32I64StrIndexKey) exampleTableIndexKey() {} func (this ExampleTableU32I64StrIndexKey) WithU32(u32 uint32) ExampleTableU32I64StrIndexKey { - this.vs = []interface{}{u32} + this.vs = []any{u32} return this } func (this ExampleTableU32I64StrIndexKey) WithU32I64(u32 uint32, i64 int64) ExampleTableU32I64StrIndexKey { - this.vs = []interface{}{u32, i64} + this.vs = []any{u32, i64} return this } func (this ExampleTableU32I64StrIndexKey) WithU32I64Str(u32 uint32, i64 int64, str string) ExampleTableU32I64StrIndexKey { - this.vs = []interface{}{u32, i64, str} + this.vs = []any{u32, i64, str} return this } type ExampleTableU64StrIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableU64StrIndexKey) id() uint32 { return 1 } -func (x ExampleTableU64StrIndexKey) values() []interface{} { return x.vs } +func (x ExampleTableU64StrIndexKey) values() []any { return x.vs } func (x ExampleTableU64StrIndexKey) exampleTableIndexKey() {} func (this ExampleTableU64StrIndexKey) WithU64(u64 uint64) ExampleTableU64StrIndexKey { - this.vs = []interface{}{u64} + this.vs = []any{u64} return this } func (this ExampleTableU64StrIndexKey) WithU64Str(u64 uint64, str string) ExampleTableU64StrIndexKey { - this.vs = []interface{}{u64, str} + this.vs = []any{u64, str} return this } type ExampleTableStrU32IndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableStrU32IndexKey) id() uint32 { return 2 } -func (x ExampleTableStrU32IndexKey) values() []interface{} { return x.vs } +func (x ExampleTableStrU32IndexKey) values() []any { return x.vs } func (x ExampleTableStrU32IndexKey) exampleTableIndexKey() {} func (this ExampleTableStrU32IndexKey) WithStr(str string) ExampleTableStrU32IndexKey { - this.vs = []interface{}{str} + this.vs = []any{str} return this } func (this ExampleTableStrU32IndexKey) WithStrU32(str string, u32 uint32) ExampleTableStrU32IndexKey { - this.vs = []interface{}{str, u32} + this.vs = []any{str, u32} return this } type ExampleTableBzStrIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTableBzStrIndexKey) id() uint32 { return 3 } -func (x ExampleTableBzStrIndexKey) values() []interface{} { return x.vs } +func (x ExampleTableBzStrIndexKey) values() []any { return x.vs } func (x ExampleTableBzStrIndexKey) exampleTableIndexKey() {} func (this ExampleTableBzStrIndexKey) WithBz(bz []byte) ExampleTableBzStrIndexKey { - this.vs = []interface{}{bz} + this.vs = []any{bz} return this } func (this ExampleTableBzStrIndexKey) WithBzStr(bz []byte, str string) ExampleTableBzStrIndexKey { - this.vs = []interface{}{bz, str} + this.vs = []any{bz, str} return this } @@ -156,7 +156,7 @@ func (this exampleTableTable) Get(ctx context.Context, u32 uint32, i64 int64, st return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleTable, nil } @@ -178,7 +178,7 @@ func (this exampleTableTable) GetByU64Str(ctx context.Context, u64 uint64, str s return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleTable, nil } @@ -208,7 +208,7 @@ var _ ExampleTableTable = exampleTableTable{} func NewExampleTableTable(db ormtable.Schema) (ExampleTableTable, error) { table := db.GetTable(&ExampleTable{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleTable{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleTable{}).ProtoReflect().Descriptor().FullName())) } return exampleTableTable{table}, nil } @@ -246,7 +246,7 @@ func (i ExampleAutoIncrementTableIterator) Value() (*ExampleAutoIncrementTable, type ExampleAutoIncrementTableIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleAutoIncrementTableIndexKey() } @@ -254,28 +254,28 @@ type ExampleAutoIncrementTableIndexKey interface { type ExampleAutoIncrementTablePrimaryKey = ExampleAutoIncrementTableIdIndexKey type ExampleAutoIncrementTableIdIndexKey struct { - vs []interface{} + vs []any } func (x ExampleAutoIncrementTableIdIndexKey) id() uint32 { return 0 } -func (x ExampleAutoIncrementTableIdIndexKey) values() []interface{} { return x.vs } +func (x ExampleAutoIncrementTableIdIndexKey) values() []any { return x.vs } func (x ExampleAutoIncrementTableIdIndexKey) exampleAutoIncrementTableIndexKey() {} func (this ExampleAutoIncrementTableIdIndexKey) WithId(id uint64) ExampleAutoIncrementTableIdIndexKey { - this.vs = []interface{}{id} + this.vs = []any{id} return this } type ExampleAutoIncrementTableXIndexKey struct { - vs []interface{} + vs []any } func (x ExampleAutoIncrementTableXIndexKey) id() uint32 { return 1 } -func (x ExampleAutoIncrementTableXIndexKey) values() []interface{} { return x.vs } +func (x ExampleAutoIncrementTableXIndexKey) values() []any { return x.vs } func (x ExampleAutoIncrementTableXIndexKey) exampleAutoIncrementTableIndexKey() {} func (this ExampleAutoIncrementTableXIndexKey) WithX(x string) ExampleAutoIncrementTableXIndexKey { - this.vs = []interface{}{x} + this.vs = []any{x} return this } @@ -318,7 +318,7 @@ func (this exampleAutoIncrementTableTable) Get(ctx context.Context, id uint64) ( return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleAutoIncrementTable, nil } @@ -338,7 +338,7 @@ func (this exampleAutoIncrementTableTable) GetByX(ctx context.Context, x string) return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleAutoIncrementTable, nil } @@ -368,7 +368,7 @@ var _ ExampleAutoIncrementTableTable = exampleAutoIncrementTableTable{} func NewExampleAutoIncrementTableTable(db ormtable.Schema) (ExampleAutoIncrementTableTable, error) { table := db.GetTable(&ExampleAutoIncrementTable{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleAutoIncrementTable{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleAutoIncrementTable{}).ProtoReflect().Descriptor().FullName())) } return exampleAutoIncrementTableTable{table.(ormtable.AutoIncrementTable)}, nil } @@ -398,7 +398,7 @@ func (x exampleSingletonTable) Save(ctx context.Context, exampleSingleton *Examp func NewExampleSingletonTable(db ormtable.Schema) (ExampleSingletonTable, error) { table := db.GetTable(&ExampleSingleton{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleSingleton{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleSingleton{}).ProtoReflect().Descriptor().FullName())) } return &exampleSingletonTable{table}, nil } @@ -433,7 +433,7 @@ func (i ExampleTimestampIterator) Value() (*ExampleTimestamp, error) { type ExampleTimestampIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleTimestampIndexKey() } @@ -441,28 +441,28 @@ type ExampleTimestampIndexKey interface { type ExampleTimestampPrimaryKey = ExampleTimestampIdIndexKey type ExampleTimestampIdIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTimestampIdIndexKey) id() uint32 { return 0 } -func (x ExampleTimestampIdIndexKey) values() []interface{} { return x.vs } +func (x ExampleTimestampIdIndexKey) values() []any { return x.vs } func (x ExampleTimestampIdIndexKey) exampleTimestampIndexKey() {} func (this ExampleTimestampIdIndexKey) WithId(id uint64) ExampleTimestampIdIndexKey { - this.vs = []interface{}{id} + this.vs = []any{id} return this } type ExampleTimestampTsIndexKey struct { - vs []interface{} + vs []any } func (x ExampleTimestampTsIndexKey) id() uint32 { return 1 } -func (x ExampleTimestampTsIndexKey) values() []interface{} { return x.vs } +func (x ExampleTimestampTsIndexKey) values() []any { return x.vs } func (x ExampleTimestampTsIndexKey) exampleTimestampIndexKey() {} func (this ExampleTimestampTsIndexKey) WithTs(ts *timestamppb.Timestamp) ExampleTimestampTsIndexKey { - this.vs = []interface{}{ts} + this.vs = []any{ts} return this } @@ -505,7 +505,7 @@ func (this exampleTimestampTable) Get(ctx context.Context, id uint64) (*ExampleT return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleTimestamp, nil } @@ -535,7 +535,7 @@ var _ ExampleTimestampTable = exampleTimestampTable{} func NewExampleTimestampTable(db ormtable.Schema) (ExampleTimestampTable, error) { table := db.GetTable(&ExampleTimestamp{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleTimestamp{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleTimestamp{}).ProtoReflect().Descriptor().FullName())) } return exampleTimestampTable{table.(ormtable.AutoIncrementTable)}, nil } @@ -571,7 +571,7 @@ func (i SimpleExampleIterator) Value() (*SimpleExample, error) { type SimpleExampleIndexKey interface { id() uint32 - values() []interface{} + values() []any simpleExampleIndexKey() } @@ -579,28 +579,28 @@ type SimpleExampleIndexKey interface { type SimpleExamplePrimaryKey = SimpleExampleNameIndexKey type SimpleExampleNameIndexKey struct { - vs []interface{} + vs []any } func (x SimpleExampleNameIndexKey) id() uint32 { return 0 } -func (x SimpleExampleNameIndexKey) values() []interface{} { return x.vs } +func (x SimpleExampleNameIndexKey) values() []any { return x.vs } func (x SimpleExampleNameIndexKey) simpleExampleIndexKey() {} func (this SimpleExampleNameIndexKey) WithName(name string) SimpleExampleNameIndexKey { - this.vs = []interface{}{name} + this.vs = []any{name} return this } type SimpleExampleUniqueIndexKey struct { - vs []interface{} + vs []any } func (x SimpleExampleUniqueIndexKey) id() uint32 { return 1 } -func (x SimpleExampleUniqueIndexKey) values() []interface{} { return x.vs } +func (x SimpleExampleUniqueIndexKey) values() []any { return x.vs } func (x SimpleExampleUniqueIndexKey) simpleExampleIndexKey() {} func (this SimpleExampleUniqueIndexKey) WithUnique(unique string) SimpleExampleUniqueIndexKey { - this.vs = []interface{}{unique} + this.vs = []any{unique} return this } @@ -635,7 +635,7 @@ func (this simpleExampleTable) Get(ctx context.Context, name string) (*SimpleExa return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &simpleExample, nil } @@ -655,7 +655,7 @@ func (this simpleExampleTable) GetByUnique(ctx context.Context, unique string) ( return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &simpleExample, nil } @@ -685,7 +685,7 @@ var _ SimpleExampleTable = simpleExampleTable{} func NewSimpleExampleTable(db ormtable.Schema) (SimpleExampleTable, error) { table := db.GetTable(&SimpleExample{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&SimpleExample{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&SimpleExample{}).ProtoReflect().Descriptor().FullName())) } return simpleExampleTable{table}, nil } @@ -720,7 +720,7 @@ func (i ExampleAutoIncFieldNameIterator) Value() (*ExampleAutoIncFieldName, erro type ExampleAutoIncFieldNameIndexKey interface { id() uint32 - values() []interface{} + values() []any exampleAutoIncFieldNameIndexKey() } @@ -728,15 +728,15 @@ type ExampleAutoIncFieldNameIndexKey interface { type ExampleAutoIncFieldNamePrimaryKey = ExampleAutoIncFieldNameFooIndexKey type ExampleAutoIncFieldNameFooIndexKey struct { - vs []interface{} + vs []any } func (x ExampleAutoIncFieldNameFooIndexKey) id() uint32 { return 0 } -func (x ExampleAutoIncFieldNameFooIndexKey) values() []interface{} { return x.vs } +func (x ExampleAutoIncFieldNameFooIndexKey) values() []any { return x.vs } func (x ExampleAutoIncFieldNameFooIndexKey) exampleAutoIncFieldNameIndexKey() {} func (this ExampleAutoIncFieldNameFooIndexKey) WithFoo(foo uint64) ExampleAutoIncFieldNameFooIndexKey { - this.vs = []interface{}{foo} + this.vs = []any{foo} return this } @@ -779,7 +779,7 @@ func (this exampleAutoIncFieldNameTable) Get(ctx context.Context, foo uint64) (* return nil, err } if !found { - return nil, ormerrors.NotFound + return nil, ormerrors.ErrNotFound } return &exampleAutoIncFieldName, nil } @@ -809,7 +809,7 @@ var _ ExampleAutoIncFieldNameTable = exampleAutoIncFieldNameTable{} func NewExampleAutoIncFieldNameTable(db ormtable.Schema) (ExampleAutoIncFieldNameTable, error) { table := db.GetTable(&ExampleAutoIncFieldName{}) if table == nil { - return nil, ormerrors.TableNotFound.Wrap(string((&ExampleAutoIncFieldName{}).ProtoReflect().Descriptor().FullName())) + return nil, ormerrors.ErrTableNotFound.Wrap(string((&ExampleAutoIncFieldName{}).ProtoReflect().Descriptor().FullName())) } return exampleAutoIncFieldNameTable{table.(ormtable.AutoIncrementTable)}, nil } diff --git a/orm/internal/testutil/testutil.go b/orm/internal/testutil/testutil.go index ce27964812f9..f6daf5a0307b 100644 --- a/orm/internal/testutil/testutil.go +++ b/orm/internal/testutil/testutil.go @@ -5,14 +5,13 @@ import ( "math" "strings" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" + "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormfield" - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/internal/testpb" ) // TestFieldSpec defines a test field against the testpb.ExampleTable message. @@ -33,7 +32,7 @@ var TestFieldSpecs = []TestFieldSpec{ { "str", rapid.String().Filter(func(x string) bool { - // filter out null terminators + // Filter out null terminators. return strings.IndexByte(x, 0) < 0 }).AsAny(), }, @@ -81,7 +80,7 @@ var TestFieldSpecs = []TestFieldSpec{ "ts", rapid.Custom(func(t *rapid.T) protoreflect.Message { isNil := rapid.Float32().Draw(t, "isNil") - if isNil >= 0.95 { // draw a nil 5% of the time + if isNil >= 0.95 { // Draw a nil 5% of the time. return nil } seconds := rapid.Int64Range(-9999999999, 9999999999).Draw(t, "seconds") diff --git a/orm/model/ormdb/file.go b/orm/model/ormdb/file.go index 37c01bcb1f29..8820b83b5295 100644 --- a/orm/model/ormdb/file.go +++ b/orm/model/ormdb/file.go @@ -30,7 +30,7 @@ type fileDescriptorDBOptions struct { type fileDescriptorDB struct { id uint32 prefix []byte - tablesById map[uint32]ormtable.Table + tablesByID map[uint32]ormtable.Table tablesByName map[protoreflect.FullName]ormtable.Table fileDescriptor protoreflect.FileDescriptor } @@ -41,7 +41,7 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil schema := &fileDescriptorDB{ id: options.ID, prefix: prefix, - tablesById: map[uint32]ormtable.Table{}, + tablesByID: map[uint32]ormtable.Table{}, tablesByName: map[protoreflect.FullName]ormtable.Table{}, fileDescriptor: fileDescriptor, } @@ -68,7 +68,7 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil JSONValidator: options.JSONValidator, BackendResolver: options.BackendResolver, }) - if errors.Is(err, ormerrors.NoTableDescriptor) { + if errors.Is(err, ormerrors.ErrNoTableDescriptor) { continue } if err != nil { @@ -76,13 +76,13 @@ func newFileDescriptorDB(fileDescriptor protoreflect.FileDescriptor, options fil } id := table.ID() - if _, ok := schema.tablesById[id]; ok { - return nil, ormerrors.InvalidTableId.Wrapf("duplicate ID %d for %s", id, tableName) + if _, ok := schema.tablesByID[id]; ok { + return nil, ormerrors.ErrInvalidTableID.Wrapf("duplicate ID %d for %s", id, tableName) } - schema.tablesById[id] = table + schema.tablesByID[id] = table if _, ok := schema.tablesByName[tableName]; ok { - return nil, ormerrors.InvalidTableDefinition.Wrapf("duplicate table %s", tableName) + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("duplicate table %s", tableName) } schema.tablesByName[tableName] = table } @@ -103,12 +103,12 @@ func (f fileDescriptorDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { } if id > math.MaxUint32 { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - table, ok := f.tablesById[uint32(id)] + table, ok := f.tablesByID[uint32(id)] if !ok { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find table with id %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("can't find table with id %d", id) } return table.DecodeEntry(k, v) @@ -117,7 +117,7 @@ func (f fileDescriptorDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { func (f fileDescriptorDB) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { table, ok := f.tablesByName[entry.GetTableName()] if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("can't find table %s", entry.GetTableName()) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("can't find table %s", entry.GetTableName()) } return table.EncodeEntry(entry) diff --git a/orm/model/ormdb/genesis.go b/orm/model/ormdb/genesis.go index 1f983704e164..e7479f2e30a0 100644 --- a/orm/model/ormdb/genesis.go +++ b/orm/model/ormdb/genesis.go @@ -18,9 +18,9 @@ type appModuleGenesisWrapper struct { moduleDB } -func (m appModuleGenesisWrapper) IsOnePerModuleType() {} +func (appModuleGenesisWrapper) IsOnePerModuleType() {} -func (m appModuleGenesisWrapper) IsAppModule() {} +func (appModuleGenesisWrapper) IsAppModule() {} func (m appModuleGenesisWrapper) DefaultGenesis(target appmodule.GenesisTarget) error { tableNames := maps.Keys(m.tablesByName) @@ -83,7 +83,7 @@ func (m appModuleGenesisWrapper) ValidateGenesis(source appmodule.GenesisSource) for name, err := range errMap { allErrors += fmt.Sprintf("Error in JSON for table %s: %v\n", name, err) } - return ormerrors.JSONValidationError.Wrap(allErrors) + return ormerrors.ErrJSONValidationError.Wrap(allErrors) } return nil diff --git a/orm/model/ormdb/module.go b/orm/model/ormdb/module.go index ff0c0ccf1afe..c54f579501a8 100644 --- a/orm/model/ormdb/module.go +++ b/orm/model/ormdb/module.go @@ -47,7 +47,7 @@ type ModuleDB interface { type moduleDB struct { prefix []byte - filesById map[uint32]*fileDescriptorDB + filesByID map[uint32]*fileDescriptorDB tablesByName map[protoreflect.FullName]ormtable.Table } @@ -83,7 +83,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt prefix := schema.Prefix db := &moduleDB{ prefix: prefix, - filesById: map[uint32]*fileDescriptorDB{}, + filesByID: map[uint32]*fileDescriptorDB{}, tablesByName: map[protoreflect.FullName]ormtable.Table{}, } @@ -146,7 +146,7 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt } if id == 0 { - return nil, ormerrors.InvalidFileDescriptorID.Wrapf("for %s", fileDescriptor.Path()) + return nil, ormerrors.ErrInvalidFileDescriptorID.Wrapf("for %s", fileDescriptor.Path()) } opts := fileDescriptorDBOptions{ @@ -162,10 +162,10 @@ func NewModuleDB(schema *ormv1alpha1.ModuleSchemaDescriptor, options ModuleDBOpt return nil, err } - db.filesById[id] = fdSchema + db.filesByID[id] = fdSchema for name, table := range fdSchema.tablesByName { if _, ok := db.tablesByName[name]; ok { - return nil, ormerrors.UnexpectedError.Wrapf("duplicate table %s", name) + return nil, ormerrors.ErrUnexpectedError.Wrapf("duplicate table %s", name) } db.tablesByName[name] = table @@ -188,12 +188,12 @@ func (m moduleDB) DecodeEntry(k, v []byte) (ormkv.Entry, error) { } if id > math.MaxUint32 { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - fileSchema, ok := m.filesById[uint32(id)] + fileSchema, ok := m.filesByID[uint32(id)] if !ok { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find FileDescriptor schema with id %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("can't find FileDescriptor schema with id %d", id) } return fileSchema.DecodeEntry(k, v) @@ -203,7 +203,7 @@ func (m moduleDB) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { tableName := entry.GetTableName() table, ok := m.tablesByName[tableName] if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("can't find table %s", tableName) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("can't find table %s", tableName) } return table.EncodeEntry(entry) diff --git a/orm/model/ormdb/module_test.go b/orm/model/ormdb/module_test.go index 71ca0a167f49..8825f4fd5a66 100644 --- a/orm/model/ormdb/module_test.go +++ b/orm/model/ormdb/module_test.go @@ -89,7 +89,7 @@ func (k keeper) Mint(ctx context.Context, acct, denom string, amount uint64) err if supply == nil { supply = &testpb.Supply{Denom: denom, Amount: amount} } else { - supply.Amount = supply.Amount + amount + supply.Amount += amount } err = k.store.SupplyTable().Save(ctx, supply) @@ -111,7 +111,7 @@ func (k keeper) Burn(ctx context.Context, acct, denom string, amount uint64) err return fmt.Errorf("insufficient supply") } - supply.Amount = supply.Amount - amount + supply.Amount -= amount if supply.Amount == 0 { err = supplyStore.Delete(ctx, supply) @@ -162,7 +162,7 @@ func (k keeper) addBalance(ctx context.Context, acct, denom string, amount uint6 Amount: amount, } } else { - balance.Amount = balance.Amount + amount + balance.Amount += amount } return k.store.BalanceTable().Save(ctx, balance) @@ -179,13 +179,12 @@ func (k keeper) safeSubBalance(ctx context.Context, acct, denom string, amount u return fmt.Errorf("insufficient funds") } - balance.Amount = balance.Amount - amount + balance.Amount -= amount if balance.Amount == 0 { return balanceStore.Delete(ctx, balance) - } else { - return balanceStore.Save(ctx, balance) } + return balanceStore.Save(ctx, balance) } func TestModuleDB(t *testing.T) { @@ -198,7 +197,7 @@ func TestModuleDB(t *testing.T) { backend, &testkv.EntryCodecDebugger{ EntryCodec: db, - Print: func(s string) { debugBuf.WriteString(s + "\n") }, + Print: func(s string) { debugBuf.WriteString(s + "\n") }, //nolint:errcheck,revive // ignore error }, )) @@ -206,7 +205,7 @@ func TestModuleDB(t *testing.T) { k, err := NewKeeper(db) assert.NilError(t, err) - runSimpleBankTests(t, k, ctx) + runSimpleBankTests(ctx, t, k) // check debug output golden.Assert(t, debugBuf.String(), "bank_scenario.golden") @@ -227,13 +226,13 @@ func TestModuleDB(t *testing.T) { // check JSON target := genesis.RawJSONTarget{} assert.NilError(t, db.GenesisHandler().DefaultGenesis(target.Target())) - rawJson, err := target.JSON() + rawJSON, err := target.JSON() assert.NilError(t, err) - golden.Assert(t, string(rawJson), "default_json.golden") + golden.Assert(t, string(rawJSON), "default_json.golden") target = genesis.RawJSONTarget{} assert.NilError(t, db.GenesisHandler().ExportGenesis(ctx, target.Target())) - rawJson, err = target.JSON() + rawJSON, err = target.JSON() assert.NilError(t, err) goodJSON := `{ @@ -251,18 +250,19 @@ func TestModuleDB(t *testing.T) { ` source, err = genesis.SourceFromRawJSON(json.RawMessage(badJSON)) assert.NilError(t, err) - assert.ErrorIs(t, db.GenesisHandler().ValidateGenesis(source), ormerrors.JSONValidationError) + assert.ErrorIs(t, db.GenesisHandler().ValidateGenesis(source), ormerrors.ErrJSONValidationError) backend2 := ormtest.NewMemoryBackend() ctx2 := ormtable.WrapContextDefault(backend2) - source, err = genesis.SourceFromRawJSON(rawJson) + source, err = genesis.SourceFromRawJSON(rawJSON) assert.NilError(t, err) assert.NilError(t, db.GenesisHandler().ValidateGenesis(source)) assert.NilError(t, db.GenesisHandler().InitGenesis(ctx2, source)) testkv.AssertBackendsEqual(t, backend, backend2) } -func runSimpleBankTests(t *testing.T, k Keeper, ctx context.Context) { +func runSimpleBankTests(ctx context.Context, t *testing.T, k Keeper) { + t.Helper() // mint coins denom := "foo" acct1 := "bob" @@ -415,5 +415,5 @@ func TestAppConfigModule(t *testing.T) { ), &k) assert.NilError(t, err) - runSimpleBankTests(t, k, context.Background()) + runSimpleBankTests(context.Background(), t, k) } diff --git a/orm/model/ormtable/auto_increment.go b/orm/model/ormtable/auto_increment.go index 982ce7987248..0e79c8e6e05e 100644 --- a/orm/model/ormtable/auto_increment.go +++ b/orm/model/ormtable/auto_increment.go @@ -28,7 +28,7 @@ func (t autoIncrementTable) InsertReturningPKey(ctx context.Context, message pro return 0, err } - return t.save(ctx, backend, message, saveModeInsert) + return t.saveAutoIncrement(ctx, backend, message, saveModeInsert) } func (t autoIncrementTable) Save(ctx context.Context, message proto.Message) error { @@ -37,7 +37,7 @@ func (t autoIncrementTable) Save(ctx context.Context, message proto.Message) err return err } - _, err = t.save(ctx, backend, message, saveModeDefault) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeDefault) return err } @@ -47,7 +47,7 @@ func (t autoIncrementTable) Insert(ctx context.Context, message proto.Message) e return err } - _, err = t.save(ctx, backend, message, saveModeInsert) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeInsert) return err } @@ -57,7 +57,7 @@ func (t autoIncrementTable) Update(ctx context.Context, message proto.Message) e return err } - _, err = t.save(ctx, backend, message, saveModeUpdate) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeUpdate) return err } @@ -70,7 +70,7 @@ func (t autoIncrementTable) LastInsertedSequence(ctx context.Context) (uint64, e return t.curSeqValue(backend.IndexStoreReader()) } -func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message proto.Message, mode saveMode) (newPK uint64, err error) { +func (t *autoIncrementTable) saveAutoIncrement(ctx context.Context, backend Backend, message proto.Message, mode saveMode) (newPK uint64, err error) { messageRef := message.ProtoReflect() val := messageRef.Get(t.autoIncField).Uint() writer := newBatchIndexCommitmentWriter(backend) @@ -78,7 +78,7 @@ func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message if val == 0 { if mode == saveModeUpdate { - return 0, ormerrors.PrimaryKeyInvalidOnUpdate + return 0, ormerrors.ErrPrimaryKeyInvalidOnUpdate } mode = saveModeInsert @@ -90,7 +90,7 @@ func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message messageRef.Set(t.autoIncField, protoreflect.ValueOfUint64(newPK)) } else { if mode == saveModeInsert { - return 0, ormerrors.AutoIncrementKeyAlreadySet + return 0, ormerrors.ErrAutoIncrementKeyAlreadySet } mode = saveModeUpdate @@ -99,8 +99,8 @@ func (t *autoIncrementTable) save(ctx context.Context, backend Backend, message return newPK, t.tableImpl.doSave(ctx, writer, message, mode) } -func (t *autoIncrementTable) curSeqValue(kv kv.ReadonlyStore) (uint64, error) { - bz, err := kv.Get(t.seqCodec.Prefix()) +func (t *autoIncrementTable) curSeqValue(kvro kv.ReadonlyStore) (uint64, error) { + bz, err := kvro.Get(t.seqCodec.Prefix()) if err != nil { return 0, err } @@ -108,18 +108,18 @@ func (t *autoIncrementTable) curSeqValue(kv kv.ReadonlyStore) (uint64, error) { return t.seqCodec.DecodeValue(bz) } -func (t *autoIncrementTable) nextSeqValue(kv kv.Store) (uint64, error) { - seq, err := t.curSeqValue(kv) +func (t *autoIncrementTable) nextSeqValue(kvstore kv.Store) (uint64, error) { + seq, err := t.curSeqValue(kvstore) if err != nil { return 0, err } seq++ - return seq, t.setSeqValue(kv, seq) + return seq, t.setSeqValue(kvstore, seq) } -func (t *autoIncrementTable) setSeqValue(kv kv.Store, seq uint64) error { - return kv.Set(t.seqCodec.Prefix(), t.seqCodec.EncodeValue(seq)) +func (t *autoIncrementTable) setSeqValue(kvstore kv.Store, seq uint64) error { + return kvstore.Set(t.seqCodec.Prefix(), t.seqCodec.EncodeValue(seq)) } func (t autoIncrementTable) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { @@ -130,7 +130,7 @@ func (t autoIncrementTable) EncodeEntry(entry ormkv.Entry) (k, v []byte, err err } func (t autoIncrementTable) ValidateJSON(reader io.Reader) error { - return t.decodeAutoIncJson(nil, reader, func(message proto.Message, maxSeq uint64) error { + return t.decodeAutoIncJSON(nil, reader, func(message proto.Message, maxSeq uint64) error { messageRef := message.ProtoReflect() pkey := messageRef.Get(t.autoIncField).Uint() if pkey > maxSeq { @@ -140,9 +140,8 @@ func (t autoIncrementTable) ValidateJSON(reader io.Reader) error { if t.customJSONValidator != nil { return t.customJSONValidator(message) - } else { - return DefaultJSONValidator(message) } + return DefaultJSONValidator(message) }) } @@ -152,37 +151,36 @@ func (t autoIncrementTable) ImportJSON(ctx context.Context, reader io.Reader) er return err } - return t.decodeAutoIncJson(backend, reader, func(message proto.Message, maxSeq uint64) error { + return t.decodeAutoIncJSON(backend, reader, func(message proto.Message, maxSeq uint64) error { messageRef := message.ProtoReflect() pkey := messageRef.Get(t.autoIncField).Uint() if pkey == 0 { // we don't have a primary key in the JSON, so we call Save to insert and // generate one - _, err = t.save(ctx, backend, message, saveModeInsert) + _, err = t.saveAutoIncrement(ctx, backend, message, saveModeInsert) return err - } else { - if pkey > maxSeq { - return fmt.Errorf("invalid auto increment primary key %d, expected a value <= %d, the highest "+ - "sequence number", pkey, maxSeq) - } - // we do have a primary key and calling Save will fail because it expects - // either no primary key or SAVE_MODE_UPDATE. So instead we drop one level - // down and insert using tableImpl which doesn't know about - // auto-incrementing primary keys. - return t.tableImpl.save(ctx, backend, message, saveModeInsert) } + if pkey > maxSeq { + return fmt.Errorf("invalid auto increment primary key %d, expected a value <= %d, the highest "+ + "sequence number", pkey, maxSeq) + } + // we do have a primary key and calling Save will fail because it expects + // either no primary key or SAVE_MODE_UPDATE. So instead we drop one level + // down and insert using tableImpl which doesn't know about + // auto-incrementing primary keys. + return t.tableImpl.write(ctx, backend, message, saveModeInsert) }) } -func (t autoIncrementTable) decodeAutoIncJson(backend Backend, reader io.Reader, onMsg func(message proto.Message, maxID uint64) error) error { - decoder, err := t.startDecodeJson(reader) +func (t autoIncrementTable) decodeAutoIncJSON(backend Backend, reader io.Reader, onMsg func(message proto.Message, maxID uint64) error) error { + decoder, err := t.startDecodeJSON(reader) if err != nil { return err } var seq uint64 - return t.doDecodeJson(decoder, + return t.doDecodeJSON(decoder, func(message json.RawMessage) bool { err = json.Unmarshal(message, &seq) if err == nil { diff --git a/orm/model/ormtable/auto_increment_test.go b/orm/model/ormtable/auto_increment_test.go index 5ba1fa4ed05a..175c61f5ed45 100644 --- a/orm/model/ormtable/auto_increment_test.go +++ b/orm/model/ormtable/auto_increment_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/orm/model/ormtable" ) +// TestAutoIncrementScenario runs a scenario with a table that has an auto-incrementing primary key. func TestAutoIncrementScenario(t *testing.T) { table, err := ormtable.Build(ormtable.Options{ MessageType: (&testpb.ExampleAutoIncrementTable{}).ProtoReflect().Type(), @@ -25,7 +26,7 @@ func TestAutoIncrementScenario(t *testing.T) { assert.Assert(t, ok) // first run tests with a split index-commitment store - runAutoIncrementScenario(t, autoTable, ormtable.WrapContextDefault(testkv.NewSplitMemBackend())) + runAutoIncrementScenario(ormtable.WrapContextDefault(testkv.NewSplitMemBackend()), t, autoTable) // now run with shared store and debugging debugBuf := &strings.Builder{} @@ -33,16 +34,18 @@ func TestAutoIncrementScenario(t *testing.T) { testkv.NewSharedMemBackend(), &testkv.EntryCodecDebugger{ EntryCodec: table, - Print: func(s string) { debugBuf.WriteString(s + "\n") }, + Print: func(s string) { debugBuf.WriteString(s + "\n") }, //nolint:errcheck,revive // ignore errors }, ) - runAutoIncrementScenario(t, autoTable, ormtable.WrapContextDefault(store)) + runAutoIncrementScenario(ormtable.WrapContextDefault(store), t, autoTable) golden.Assert(t, debugBuf.String(), "test_auto_inc.golden") checkEncodeDecodeEntries(t, table, store.IndexStoreReader()) } -func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, ctx context.Context) { +// runAutoIncrementScenario runs a simple scenario with an auto-increment table. +func runAutoIncrementScenario(ctx context.Context, t *testing.T, table ormtable.AutoIncrementTable) { + t.Helper() store, err := testpb.NewExampleAutoIncrementTableTable(table) assert.NilError(t, err) @@ -57,10 +60,10 @@ func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, c assert.Equal(t, curSeq, uint64(1)) ex2 := &testpb.ExampleAutoIncrementTable{X: "bar", Y: 10} - newId, err := table.InsertReturningPKey(ctx, ex2) + newID, err := table.InsertReturningPKey(ctx, ex2) assert.NilError(t, err) assert.Equal(t, uint64(2), ex2.Id) - assert.Equal(t, newId, ex2.Id) + assert.Equal(t, newID, ex2.Id) curSeq, err = table.LastInsertedSequence(ctx) assert.NilError(t, err) assert.Equal(t, curSeq, uint64(2)) @@ -70,7 +73,7 @@ func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, c assert.NilError(t, table.ValidateJSON(bytes.NewReader(buf.Bytes()))) store2 := ormtable.WrapContextDefault(testkv.NewSplitMemBackend()) assert.NilError(t, table.ImportJSON(store2, bytes.NewReader(buf.Bytes()))) - assertTablesEqual(t, table, ctx, store2) + assertTablesEqual(ctx, store2, t, table) // test edge case where we have deleted all entities but we're still exporting the sequence number assert.NilError(t, table.Delete(ctx, ex1)) @@ -89,6 +92,7 @@ func runAutoIncrementScenario(t *testing.T, table ormtable.AutoIncrementTable, c assert.Equal(t, curSeq, uint64(3)) } +// TestBadJSON tests that we get an error when importing bad JSON. func TestBadJSON(t *testing.T) { table, err := ormtable.Build(ormtable.Options{ MessageType: (&testpb.ExampleAutoIncrementTable{}).ProtoReflect().Type(), diff --git a/orm/model/ormtable/bench_test.go b/orm/model/ormtable/bench_test.go index 48d2621e84d6..d34ca44b5cae 100644 --- a/orm/model/ormtable/bench_test.go +++ b/orm/model/ormtable/bench_test.go @@ -18,20 +18,22 @@ import ( "github.com/cosmos/cosmos-sdk/orm/types/kv" ) -func initBalanceTable(t testing.TB) testpb.BalanceTable { +func initBalanceTable(tb testing.TB) testpb.BalanceTable { + tb.Helper() table, err := ormtable.Build(ormtable.Options{ MessageType: (&testpb.Balance{}).ProtoReflect().Type(), }) - assert.NilError(t, err) + assert.NilError(tb, err) balanceTable, err := testpb.NewBalanceTable(table) - assert.NilError(t, err) + assert.NilError(tb, err) return balanceTable } func BenchmarkMemory(b *testing.B) { bench(b, func(tb testing.TB) ormtable.Backend { + tb.Helper() return ormtest.NewMemoryBackend() }) } @@ -41,36 +43,38 @@ func BenchmarkLevelDB(b *testing.B) { } func bench(b *testing.B, newBackend func(testing.TB) ormtable.Backend) { + b.Helper() b.Run("insert", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) b.StartTimer() - benchInsert(b, ctx) + benchInsert(ctx, b) }) b.Run("update", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) - benchInsert(b, ctx) + benchInsert(ctx, b) b.StartTimer() - benchUpdate(b, ctx) + benchUpdate(ctx, b) }) b.Run("get", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) - benchInsert(b, ctx) + benchInsert(ctx, b) b.StartTimer() - benchGet(b, ctx) + benchGet(ctx, b) }) b.Run("delete", func(b *testing.B) { b.StopTimer() ctx := ormtable.WrapContextDefault(newBackend(b)) - benchInsert(b, ctx) + benchInsert(ctx, b) b.StartTimer() - benchDelete(b, ctx) + benchDelete(ctx, b) }) } -func benchInsert(b *testing.B, ctx context.Context) { +func benchInsert(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Insert(ctx, &testpb.Balance{ @@ -81,7 +85,8 @@ func benchInsert(b *testing.B, ctx context.Context) { } } -func benchUpdate(b *testing.B, ctx context.Context) { +func benchUpdate(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Update(ctx, &testpb.Balance{ @@ -92,7 +97,8 @@ func benchUpdate(b *testing.B, ctx context.Context) { } } -func benchGet(b *testing.B, ctx context.Context) { +func benchGet(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { balance, err := balanceTable.Get(ctx, fmt.Sprintf("acct%d", i), "bar") @@ -101,7 +107,8 @@ func benchGet(b *testing.B, ctx context.Context) { } } -func benchDelete(b *testing.B, ctx context.Context) { +func benchDelete(ctx context.Context, b *testing.B) { + b.Helper() balanceTable := initBalanceTable(b) for i := 0; i < b.N; i++ { assert.NilError(b, balanceTable.Delete(ctx, &testpb.Balance{ @@ -244,6 +251,7 @@ func BenchmarkManualInsertLevelDB(b *testing.B) { } func benchManual(b *testing.B, newStore func() (dbm.DB, error)) { + b.Helper() b.Run("insert", func(b *testing.B) { b.StopTimer() store, err := newStore() @@ -278,6 +286,7 @@ func benchManual(b *testing.B, newStore func() (dbm.DB, error)) { } func benchManualInsert(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { assert.NilError(b, insertBalance(store, &testpb.Balance{ Address: fmt.Sprintf("acct%d", i), @@ -288,6 +297,7 @@ func benchManualInsert(b *testing.B, store kv.Store) { } func benchManualUpdate(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { assert.NilError(b, updateBalance(store, &testpb.Balance{ Address: fmt.Sprintf("acct%d", i), @@ -298,6 +308,7 @@ func benchManualUpdate(b *testing.B, store kv.Store) { } func benchManualDelete(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { assert.NilError(b, deleteBalance(store, &testpb.Balance{ Address: fmt.Sprintf("acct%d", i), @@ -307,6 +318,7 @@ func benchManualDelete(b *testing.B, store kv.Store) { } func benchManualGet(b *testing.B, store kv.Store) { + b.Helper() for i := 0; i < b.N; i++ { balance, err := getBalance(store, fmt.Sprintf("acct%d", i), "bar") assert.NilError(b, err) diff --git a/orm/model/ormtable/build.go b/orm/model/ormtable/build.go index 3e9137665d0a..590fb8d11b1d 100644 --- a/orm/model/ormtable/build.go +++ b/orm/model/ormtable/build.go @@ -16,9 +16,9 @@ import ( ) const ( - primaryKeyId uint32 = 0 - indexIdLimit uint32 = 32768 - seqId = indexIdLimit + primaryKeyID uint32 = 0 + indexIDLimit uint32 = 32768 + seqID = indexIDLimit ) // Options are options for building a Table. @@ -84,8 +84,8 @@ func Build(options Options) (Table, error) { indexes: []Index{}, indexesByFields: map[fieldnames.FieldNames]concreteIndex{}, uniqueIndexesByFields: map[fieldnames.FieldNames]UniqueIndex{}, - entryCodecsById: map[uint32]ormkv.EntryCodec{}, - indexesById: map[uint32]Index{}, + entryCodecsByID: map[uint32]ormkv.EntryCodec{}, + indexesByID: map[uint32]Index{}, typeResolver: options.TypeResolver, customJSONValidator: options.JSONValidator, } @@ -105,11 +105,11 @@ func Build(options Options) (Table, error) { switch { case tableDesc != nil: if singletonDesc != nil { - return nil, ormerrors.InvalidTableDefinition.Wrapf("message %s cannot be declared as both a table and a singleton", messageDescriptor.FullName()) + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("message %s cannot be declared as both a table and a singleton", messageDescriptor.FullName()) } case singletonDesc != nil: if singletonDesc.Id == 0 { - return nil, ormerrors.InvalidTableId.Wrapf("%s", messageDescriptor.FullName()) + return nil, ormerrors.ErrInvalidTableID.Wrapf("%s", messageDescriptor.FullName()) } prefix := encodeutil.AppendVarUInt32(options.Prefix, singletonDesc.Id) @@ -125,35 +125,35 @@ func Build(options Options) (Table, error) { pkIndex.PrimaryKeyCodec = pkCodec table.tablePrefix = prefix - table.tableId = singletonDesc.Id + table.tableID = singletonDesc.Id return &singleton{table}, nil default: - return nil, ormerrors.NoTableDescriptor.Wrapf("missing table descriptor for %s", messageDescriptor.FullName()) + return nil, ormerrors.ErrNoTableDescriptor.Wrapf("missing table descriptor for %s", messageDescriptor.FullName()) } - tableId := tableDesc.Id - if tableId == 0 { - return nil, ormerrors.InvalidTableId.Wrapf("table %s", messageDescriptor.FullName()) + tableID := tableDesc.Id + if tableID == 0 { + return nil, ormerrors.ErrInvalidTableID.Wrapf("table %s", messageDescriptor.FullName()) } prefix := options.Prefix - prefix = encodeutil.AppendVarUInt32(prefix, tableId) + prefix = encodeutil.AppendVarUInt32(prefix, tableID) table.tablePrefix = prefix - table.tableId = tableId + table.tableID = tableID if tableDesc.PrimaryKey == nil { - return nil, ormerrors.MissingPrimaryKey.Wrap(string(messageDescriptor.FullName())) + return nil, ormerrors.ErrMissingPrimaryKey.Wrap(string(messageDescriptor.FullName())) } pkFields := fieldnames.CommaSeparatedFieldNames(tableDesc.PrimaryKey.Fields) table.primaryKeyIndex.fields = pkFields pkFieldNames := pkFields.Names() if len(pkFieldNames) == 0 { - return nil, ormerrors.InvalidTableDefinition.Wrapf("empty primary key fields for %s", messageDescriptor.FullName()) + return nil, ormerrors.ErrInvalidTableDefinition.Wrapf("empty primary key fields for %s", messageDescriptor.FullName()) } - pkPrefix := encodeutil.AppendVarUInt32(prefix, primaryKeyId) + pkPrefix := encodeutil.AppendVarUInt32(prefix, primaryKeyID) pkCodec, err := ormkv.NewPrimaryKeyCodec( pkPrefix, options.MessageType, @@ -167,18 +167,18 @@ func Build(options Options) (Table, error) { pkIndex.PrimaryKeyCodec = pkCodec table.indexesByFields[pkFields] = pkIndex table.uniqueIndexesByFields[pkFields] = pkIndex - table.entryCodecsById[primaryKeyId] = pkIndex - table.indexesById[primaryKeyId] = pkIndex + table.entryCodecsByID[primaryKeyID] = pkIndex + table.indexesByID[primaryKeyID] = pkIndex table.indexes = append(table.indexes, pkIndex) for _, idxDesc := range tableDesc.Index { id := idxDesc.Id - if id == 0 || id >= indexIdLimit { - return nil, ormerrors.InvalidIndexId.Wrapf("index on table %s with fields %s, invalid id %d", messageDescriptor.FullName(), idxDesc.Fields, id) + if id == 0 || id >= indexIDLimit { + return nil, ormerrors.ErrInvalidIndexID.Wrapf("index on table %s with fields %s, invalid id %d", messageDescriptor.FullName(), idxDesc.Fields, id) } - if _, ok := table.entryCodecsById[id]; ok { - return nil, ormerrors.DuplicateIndexId.Wrapf("id %d on table %s", id, messageDescriptor.FullName()) + if _, ok := table.entryCodecsByID[id]; ok { + return nil, ormerrors.ErrDuplicateIndexID.Wrapf("id %d on table %s", id, messageDescriptor.FullName()) } idxFields := fieldnames.CommaSeparatedFieldNames(idxDesc.Fields) @@ -264,8 +264,8 @@ func Build(options Options) (Table, error) { table.indexesByFields[name] = index } - table.entryCodecsById[id] = index - table.indexesById[id] = index + table.entryCodecsByID[id] = index + table.indexesByID[id] = index table.indexes = append(table.indexes, index) table.indexers = append(table.indexers, index.(indexer)) } @@ -273,12 +273,12 @@ func Build(options Options) (Table, error) { if tableDesc.PrimaryKey.AutoIncrement { autoIncField := pkCodec.GetFieldDescriptors()[0] if len(pkFieldNames) != 1 && autoIncField.Kind() != protoreflect.Uint64Kind { - return nil, ormerrors.InvalidAutoIncrementKey.Wrapf("field %s", autoIncField.FullName()) + return nil, ormerrors.ErrInvalidAutoIncrementKey.Wrapf("field %s", autoIncField.FullName()) } - seqPrefix := encodeutil.AppendVarUInt32(prefix, seqId) + seqPrefix := encodeutil.AppendVarUInt32(prefix, seqID) seqCodec := ormkv.NewSeqCodec(options.MessageType, seqPrefix) - table.entryCodecsById[seqId] = seqCodec + table.entryCodecsByID[seqID] = seqCodec return &autoIncrementTable{ tableImpl: table, autoIncField: autoIncField, diff --git a/orm/model/ormtable/index.go b/orm/model/ormtable/index.go index 903c19348505..1276833f9c09 100644 --- a/orm/model/ormtable/index.go +++ b/orm/model/ormtable/index.go @@ -20,7 +20,7 @@ type Index interface { // Prefix key values must correspond in type to the index's fields and the // number of values provided cannot exceed the number of fields in the index, // although fewer values can be provided. - List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) + List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) // ListRange does range iteration over the index with the provided from and to // values and options. @@ -36,13 +36,13 @@ type Index interface { // value for bytes. // // Range iteration is inclusive at both ends. - ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) + ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) // DeleteBy deletes any entries which match the provided prefix key. - DeleteBy(context context.Context, prefixKey ...interface{}) error + DeleteBy(context context.Context, prefixKey ...any) error // DeleteRange deletes any entries between the provided range keys. - DeleteRange(context context.Context, from, to []interface{}) error + DeleteRange(context context.Context, from, to []any) error // MessageType returns the protobuf message type of the index. MessageType() protoreflect.MessageType @@ -66,10 +66,10 @@ type UniqueIndex interface { Index // Has returns true if the key values are present in the store for this index. - Has(context context.Context, keyValues ...interface{}) (found bool, err error) + Has(context context.Context, keyValues ...any) (found bool, err error) // Get retrieves the message if one exists for the provided key values. - Get(context context.Context, message proto.Message, keyValues ...interface{}) (found bool, err error) + Get(context context.Context, message proto.Message, keyValues ...any) (found bool, err error) } type indexer interface { diff --git a/orm/model/ormtable/index_impl.go b/orm/model/ormtable/index_impl.go index 7289efc40af4..a51318ae12ca 100644 --- a/orm/model/ormtable/index_impl.go +++ b/orm/model/ormtable/index_impl.go @@ -25,7 +25,7 @@ type indexKeyIndex struct { getReadBackend func(context.Context) (ReadBackend, error) } -func (i indexKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) error { +func (i indexKeyIndex) DeleteBy(ctx context.Context, keyValues ...any) error { it, err := i.List(ctx, keyValues) if err != nil { return err @@ -34,7 +34,7 @@ func (i indexKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) e return i.primaryKey.deleteByIterator(ctx, it) } -func (i indexKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) error { +func (i indexKeyIndex) DeleteRange(ctx context.Context, from, to []any) error { it, err := i.ListRange(ctx, from, to) if err != nil { return err @@ -43,7 +43,7 @@ func (i indexKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) return i.primaryKey.deleteByIterator(ctx, it) } -func (i indexKeyIndex) List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) { +func (i indexKeyIndex) List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) { backend, err := i.getReadBackend(ctx) if err != nil { return nil, err @@ -52,7 +52,7 @@ func (i indexKeyIndex) List(ctx context.Context, prefixKey []interface{}, option return prefixIterator(backend.IndexStoreReader(), backend, i, i.KeyCodec, prefixKey, options) } -func (i indexKeyIndex) ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) { +func (i indexKeyIndex) ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) { backend, err := i.getReadBackend(ctx) if err != nil { return nil, err @@ -66,7 +66,7 @@ var ( _ Index = &indexKeyIndex{} ) -func (i indexKeyIndex) doNotImplement() {} +func (indexKeyIndex) doNotImplement() {} func (i indexKeyIndex) onInsert(store kv.Store, message protoreflect.Message) error { k, v, err := i.EncodeKVFromMessage(message) @@ -76,9 +76,9 @@ func (i indexKeyIndex) onInsert(store kv.Store, message protoreflect.Message) er return store.Set(k, v) } -func (i indexKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Message) error { - newValues := i.GetKeyValues(new) - existingValues := i.GetKeyValues(existing) +func (i indexKeyIndex) onUpdate(store kv.Store, newMsg, existingMsg protoreflect.Message) error { + newValues := i.GetKeyValues(newMsg) + existingValues := i.GetKeyValues(existingMsg) if i.CompareKeys(newValues, existingValues) == 0 { return nil } @@ -108,18 +108,18 @@ func (i indexKeyIndex) onDelete(store kv.Store, message protoreflect.Message) er } func (i indexKeyIndex) readValueFromIndexKey(backend ReadBackend, primaryKey []protoreflect.Value, _ []byte, message proto.Message) error { - found, err := i.primaryKey.get(backend, message, primaryKey) + found, err := i.primaryKey.doGet(backend, message, primaryKey) if err != nil { return err } if !found { - return ormerrors.UnexpectedError.Wrapf("can't find primary key") + return ormerrors.ErrUnexpectedError.Wrapf("can't find primary key") } return nil } -func (p indexKeyIndex) Fields() string { - return p.fields.String() +func (i indexKeyIndex) Fields() string { + return i.fields.String() } diff --git a/orm/model/ormtable/iterator.go b/orm/model/ormtable/iterator.go index 848396cb96c6..2f47ac10a876 100644 --- a/orm/model/ormtable/iterator.go +++ b/orm/model/ormtable/iterator.go @@ -49,7 +49,7 @@ type Iterator interface { doNotImplement() } -func prefixIterator(iteratorStore kv.ReadonlyStore, backend ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, prefix []interface{}, opts []listinternal.Option) (Iterator, error) { +func prefixIterator(iteratorStore kv.ReadonlyStore, backend ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, prefix []any, opts []listinternal.Option) (Iterator, error) { options := &listinternal.Options{} listinternal.ApplyOptions(options, opts) if err := options.Validate(); err != nil { @@ -106,7 +106,7 @@ func prefixIterator(iteratorStore kv.ReadonlyStore, backend ReadBackend, index c return applyCommonIteratorOptions(res, options) } -func rangeIterator(iteratorStore kv.ReadonlyStore, reader ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, start, end []interface{}, opts []listinternal.Option) (Iterator, error) { +func rangeIterator(iteratorStore kv.ReadonlyStore, reader ReadBackend, index concreteIndex, codec *ormkv.KeyCodec, start, end []any, opts []listinternal.Option) (Iterator, error) { options := &listinternal.Options{} listinternal.ApplyOptions(options, opts) if err := options.Validate(); err != nil { @@ -205,7 +205,7 @@ type indexIterator struct { started bool } -func (i *indexIterator) PageResponse() *queryv1beta1.PageResponse { +func (*indexIterator) PageResponse() *queryv1beta1.PageResponse { return nil } diff --git a/orm/model/ormtable/paginate.go b/orm/model/ormtable/paginate.go index f30d9c02583d..0bf27ba2d433 100644 --- a/orm/model/ormtable/paginate.go +++ b/orm/model/ormtable/paginate.go @@ -84,12 +84,11 @@ func (it *paginationIterator) Next() bool { if ok { it.i++ return true - } else { - it.pageRes = &queryv1beta1.PageResponse{ - Total: uint64(it.i), - } - return false } + it.pageRes = &queryv1beta1.PageResponse{ + Total: uint64(it.i), + } + return false } func (it paginationIterator) PageResponse() *queryv1beta1.PageResponse { diff --git a/orm/model/ormtable/primary_key.go b/orm/model/ormtable/primary_key.go index 0ce62852895b..9bff13afd7a7 100644 --- a/orm/model/ormtable/primary_key.go +++ b/orm/model/ormtable/primary_key.go @@ -25,7 +25,7 @@ type primaryKeyIndex struct { getBackend func(context.Context) (ReadBackend, error) } -func (p primaryKeyIndex) List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) { +func (p primaryKeyIndex) List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) { backend, err := p.getBackend(ctx) if err != nil { return nil, err @@ -34,7 +34,7 @@ func (p primaryKeyIndex) List(ctx context.Context, prefixKey []interface{}, opti return prefixIterator(backend.CommitmentStoreReader(), backend, p, p.KeyCodec, prefixKey, options) } -func (p primaryKeyIndex) ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) { +func (p primaryKeyIndex) ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) { backend, err := p.getBackend(ctx) if err != nil { return nil, err @@ -43,18 +43,18 @@ func (p primaryKeyIndex) ListRange(ctx context.Context, from, to []interface{}, return rangeIterator(backend.CommitmentStoreReader(), backend, p, p.KeyCodec, from, to, options) } -func (p primaryKeyIndex) doNotImplement() {} +func (primaryKeyIndex) doNotImplement() {} -func (p primaryKeyIndex) Has(ctx context.Context, key ...interface{}) (found bool, err error) { +func (p primaryKeyIndex) Has(ctx context.Context, key ...any) (found bool, err error) { backend, err := p.getBackend(ctx) if err != nil { return false, err } - return p.has(backend, encodeutil.ValuesOf(key...)) + return p.checkHas(backend, encodeutil.ValuesOf(key...)) } -func (p primaryKeyIndex) has(backend ReadBackend, values []protoreflect.Value) (found bool, err error) { +func (p primaryKeyIndex) checkHas(backend ReadBackend, values []protoreflect.Value) (found bool, err error) { keyBz, err := p.EncodeKey(values) if err != nil { return false, err @@ -63,16 +63,16 @@ func (p primaryKeyIndex) has(backend ReadBackend, values []protoreflect.Value) ( return backend.CommitmentStoreReader().Has(keyBz) } -func (p primaryKeyIndex) Get(ctx context.Context, message proto.Message, values ...interface{}) (found bool, err error) { +func (p primaryKeyIndex) Get(ctx context.Context, message proto.Message, values ...any) (found bool, err error) { backend, err := p.getBackend(ctx) if err != nil { return false, err } - return p.get(backend, message, encodeutil.ValuesOf(values...)) + return p.doGet(backend, message, encodeutil.ValuesOf(values...)) } -func (p primaryKeyIndex) get(backend ReadBackend, message proto.Message, values []protoreflect.Value) (found bool, err error) { +func (p primaryKeyIndex) doGet(backend ReadBackend, message proto.Message, values []protoreflect.Value) (found bool, err error) { key, err := p.EncodeKey(values) if err != nil { return false, err @@ -81,7 +81,7 @@ func (p primaryKeyIndex) get(backend ReadBackend, message proto.Message, values return p.getByKeyBytes(backend, key, values, message) } -func (p primaryKeyIndex) DeleteBy(ctx context.Context, primaryKeyValues ...interface{}) error { +func (p primaryKeyIndex) DeleteBy(ctx context.Context, primaryKeyValues ...any) error { if len(primaryKeyValues) == len(p.GetFieldNames()) { return p.doDelete(ctx, encodeutil.ValuesOf(primaryKeyValues...)) } @@ -94,7 +94,7 @@ func (p primaryKeyIndex) DeleteBy(ctx context.Context, primaryKeyValues ...inter return p.deleteByIterator(ctx, it) } -func (p primaryKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) error { +func (p primaryKeyIndex) DeleteRange(ctx context.Context, from, to []any) error { it, err := p.ListRange(ctx, from, to) if err != nil { return err @@ -113,7 +113,7 @@ func (p primaryKeyIndex) getWriteBackend(ctx context.Context) (Backend, error) { return writeBackend, nil } - return nil, ormerrors.ReadOnly + return nil, ormerrors.ErrReadOnly } func (p primaryKeyIndex) doDelete(ctx context.Context, primaryKeyValues []protoreflect.Value) error { diff --git a/orm/model/ormtable/singleton.go b/orm/model/ormtable/singleton.go index 1a7017662579..db494d26f0ba 100644 --- a/orm/model/ormtable/singleton.go +++ b/orm/model/ormtable/singleton.go @@ -37,9 +37,8 @@ func (t singleton) ValidateJSON(reader io.Reader) error { if t.customJSONValidator != nil { return t.customJSONValidator(msg) - } else { - return DefaultJSONValidator(msg) } + return DefaultJSONValidator(msg) } func (t singleton) ImportJSON(ctx context.Context, reader io.Reader) error { @@ -59,7 +58,7 @@ func (t singleton) ImportJSON(ctx context.Context, reader io.Reader) error { return err } - return t.save(ctx, backend, msg, saveModeDefault) + return t.write(ctx, backend, msg, saveModeDefault) } func (t singleton) ExportJSON(ctx context.Context, writer io.Writer) error { diff --git a/orm/model/ormtable/table_impl.go b/orm/model/ormtable/table_impl.go index bbcebb3a96ad..e99ba2b6dcff 100644 --- a/orm/model/ormtable/table_impl.go +++ b/orm/model/ormtable/table_impl.go @@ -24,10 +24,10 @@ type tableImpl struct { indexes []Index indexesByFields map[fieldnames.FieldNames]concreteIndex uniqueIndexesByFields map[fieldnames.FieldNames]UniqueIndex - indexesById map[uint32]Index - entryCodecsById map[uint32]ormkv.EntryCodec + indexesByID map[uint32]Index + entryCodecsByID map[uint32]ormkv.EntryCodec tablePrefix []byte - tableId uint32 + tableID uint32 typeResolver TypeResolver customJSONValidator func(message proto.Message) error } @@ -44,7 +44,7 @@ func (t tableImpl) PrimaryKey() UniqueIndex { } func (t tableImpl) GetIndexByID(id uint32) Index { - return t.indexesById[id] + return t.indexesByID[id] } func (t tableImpl) Save(ctx context.Context, message proto.Message) error { @@ -53,7 +53,7 @@ func (t tableImpl) Save(ctx context.Context, message proto.Message) error { return err } - return t.save(ctx, backend, message, saveModeDefault) + return t.write(ctx, backend, message, saveModeDefault) } func (t tableImpl) Insert(ctx context.Context, message proto.Message) error { @@ -62,7 +62,7 @@ func (t tableImpl) Insert(ctx context.Context, message proto.Message) error { return err } - return t.save(ctx, backend, message, saveModeInsert) + return t.write(ctx, backend, message, saveModeInsert) } func (t tableImpl) Update(ctx context.Context, message proto.Message) error { @@ -71,10 +71,10 @@ func (t tableImpl) Update(ctx context.Context, message proto.Message) error { return err } - return t.save(ctx, backend, message, saveModeUpdate) + return t.write(ctx, backend, message, saveModeUpdate) } -func (t tableImpl) save(ctx context.Context, backend Backend, message proto.Message, mode saveMode) error { +func (t tableImpl) write(ctx context.Context, backend Backend, message proto.Message, mode saveMode) error { writer := newBatchIndexCommitmentWriter(backend) defer writer.Close() return t.doSave(ctx, writer, message, mode) @@ -95,7 +95,7 @@ func (t tableImpl) doSave(ctx context.Context, writer *batchIndexCommitmentWrite if haveExisting { if mode == saveModeInsert { - return ormerrors.AlreadyExists.Wrapf("%q:%+v", mref.Descriptor().FullName(), pkValues) + return ormerrors.ErrOrmAlreadyExists.Wrapf("%q:%+v", mref.Descriptor().FullName(), pkValues) } if validateHooks := writer.ValidateHooks(); validateHooks != nil { @@ -106,7 +106,7 @@ func (t tableImpl) doSave(ctx context.Context, writer *batchIndexCommitmentWrite } } else { if mode == saveModeUpdate { - return ormerrors.NotFound.Wrapf("%q", mref.Descriptor().FullName()) + return ormerrors.ErrNotFound.Wrapf("%q", mref.Descriptor().FullName()) } if validateHooks := writer.ValidateHooks(); validateHooks != nil { @@ -141,7 +141,6 @@ func (t tableImpl) doSave(ctx context.Context, writer *batchIndexCommitmentWrite if err != nil { return err } - } if writeHooks := writer.WriteHooks(); writeHooks != nil { writer.enqueueHook(func() { @@ -183,20 +182,20 @@ func (t tableImpl) Indexes() []Index { return t.indexes } -func (t tableImpl) DefaultJSON() json.RawMessage { +func (tableImpl) DefaultJSON() json.RawMessage { return json.RawMessage("[]") } -func (t tableImpl) decodeJson(reader io.Reader, onMsg func(message proto.Message) error) error { - decoder, err := t.startDecodeJson(reader) +func (t tableImpl) decodeJSON(reader io.Reader, onMsg func(message proto.Message) error) error { + decoder, err := t.startDecodeJSON(reader) if err != nil { return err } - return t.doDecodeJson(decoder, nil, onMsg) + return t.doDecodeJSON(decoder, nil, onMsg) } -func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { +func (tableImpl) startDecodeJSON(reader io.Reader) (*json.Decoder, error) { decoder := json.NewDecoder(reader) token, err := decoder.Token() if err != nil { @@ -204,7 +203,7 @@ func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { } if token != json.Delim('[') { - return nil, ormerrors.JSONImportError.Wrapf("expected [ got %s", token) + return nil, ormerrors.ErrJSONImportError.Wrapf("expected [ got %s", token) } return decoder, nil @@ -213,21 +212,21 @@ func (t tableImpl) startDecodeJson(reader io.Reader) (*json.Decoder, error) { // onFirst is called on the first RawMessage and used for auto-increment tables // to decode the sequence in which case it should return true. // onMsg is called on every decoded message -func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json.RawMessage) bool, onMsg func(message proto.Message) error) error { +func (t tableImpl) doDecodeJSON(decoder *json.Decoder, onFirst func(message json.RawMessage) bool, onMsg func(message proto.Message) error) error { unmarshalOptions := protojson.UnmarshalOptions{Resolver: t.typeResolver} first := true for decoder.More() { - var rawJson json.RawMessage - err := decoder.Decode(&rawJson) + var rawJSON json.RawMessage + err := decoder.Decode(&rawJSON) if err != nil { - return ormerrors.JSONImportError.Wrapf("%s", err) + return ormerrors.ErrJSONImportError.Wrapf("%s", err) } if first { first = false if onFirst != nil { - if onFirst(rawJson) { + if onFirst(rawJSON) { // if onFirst handled this, skip decoding into a proto message continue } @@ -235,7 +234,7 @@ func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json } msg := t.MessageType().New().Interface() - err = unmarshalOptions.Unmarshal(rawJson, msg) + err = unmarshalOptions.Unmarshal(rawJSON, msg) if err != nil { return err } @@ -252,7 +251,7 @@ func (t tableImpl) doDecodeJson(decoder *json.Decoder, onFirst func(message json } if token != json.Delim(']') { - return ormerrors.JSONImportError.Wrapf("expected ] got %s", token) + return ormerrors.ErrJSONImportError.Wrapf("expected ] got %s", token) } return nil @@ -280,12 +279,11 @@ func DefaultJSONValidator(message proto.Message) error { } func (t tableImpl) ValidateJSON(reader io.Reader) error { - return t.decodeJson(reader, func(message proto.Message) error { + return t.decodeJSON(reader, func(message proto.Message) error { if t.customJSONValidator != nil { return t.customJSONValidator(message) - } else { - return DefaultJSONValidator(message) } + return DefaultJSONValidator(message) }) } @@ -295,18 +293,18 @@ func (t tableImpl) ImportJSON(ctx context.Context, reader io.Reader) error { return err } - return t.decodeJson(reader, func(message proto.Message) error { - return t.save(ctx, backend, message, saveModeDefault) + return t.decodeJSON(reader, func(message proto.Message) error { + return t.write(ctx, backend, message, saveModeDefault) }) } -func (t tableImpl) ExportJSON(context context.Context, writer io.Writer) error { +func (t tableImpl) ExportJSON(ctx context.Context, writer io.Writer) error { _, err := writer.Write([]byte("[")) if err != nil { return err } - return t.doExportJSON(context, writer, true) + return t.doExportJSON(ctx, writer, true) } func (t tableImpl) doExportJSON(ctx context.Context, writer io.Writer, start bool) error { @@ -346,7 +344,6 @@ func (t tableImpl) doExportJSON(ctx context.Context, writer io.Writer, start boo if err != nil { return err } - } } @@ -363,12 +360,12 @@ func (t tableImpl) DecodeEntry(k, v []byte) (ormkv.Entry, error) { } if id > math.MaxUint32 { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("uint32 varint id out of range %d", id) } - idx, ok := t.entryCodecsById[uint32(id)] + idx, ok := t.entryCodecsByID[uint32(id)] if !ok { - return nil, ormerrors.UnexpectedDecodePrefix.Wrapf("can't find field with id %d", id) + return nil, ormerrors.ErrUnexpectedDecodePrefix.Wrapf("can't find field with id %d", id) } return idx.DecodeEntry(k, v) @@ -381,17 +378,17 @@ func (t tableImpl) EncodeEntry(entry ormkv.Entry) (k, v []byte, err error) { case *ormkv.IndexKeyEntry: idx, ok := t.indexesByFields[fieldnames.FieldsFromNames(entry.Fields)] if !ok { - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("can't find index with fields %s", entry.Fields) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("can't find index with fields %s", entry.Fields) } return idx.EncodeEntry(entry) default: - return nil, nil, ormerrors.BadDecodeEntry.Wrapf("%s", entry) + return nil, nil, ormerrors.ErrBadDecodeEntry.Wrapf("%s", entry) } } func (t tableImpl) ID() uint32 { - return t.tableId + return t.tableID } func (t tableImpl) Has(ctx context.Context, message proto.Message) (found bool, err error) { @@ -401,7 +398,7 @@ func (t tableImpl) Has(ctx context.Context, message proto.Message) (found bool, } keyValues := t.primaryKeyIndex.PrimaryKeyCodec.GetKeyValues(message.ProtoReflect()) - return t.primaryKeyIndex.has(backend, keyValues) + return t.primaryKeyIndex.checkHas(backend, keyValues) } // Get retrieves the message if one exists for the primary key fields @@ -414,7 +411,7 @@ func (t tableImpl) Get(ctx context.Context, message proto.Message) (found bool, } keyValues := t.primaryKeyIndex.PrimaryKeyCodec.GetKeyValues(message.ProtoReflect()) - return t.primaryKeyIndex.get(backend, message, keyValues) + return t.primaryKeyIndex.doGet(backend, message, keyValues) } var ( diff --git a/orm/model/ormtable/table_test.go b/orm/model/ormtable/table_test.go index 8e62cf814359..aa1575179f32 100644 --- a/orm/model/ormtable/table_test.go +++ b/orm/model/ormtable/table_test.go @@ -9,29 +9,24 @@ import ( "testing" "time" - "google.golang.org/protobuf/types/known/timestamppb" - - dbm "github.com/cosmos/cosmos-db" - - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/testing/protocmp" - "gotest.tools/v3/assert" - "gotest.tools/v3/golden" - "pgregory.net/rapid" - - "github.com/cosmos/cosmos-sdk/orm/types/kv" - queryv1beta1 "cosmossdk.io/api/cosmos/base/query/v1beta1" sdkerrors "cosmossdk.io/errors" - + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/testkv" "github.com/cosmos/cosmos-sdk/orm/internal/testpb" "github.com/cosmos/cosmos-sdk/orm/internal/testutil" "github.com/cosmos/cosmos-sdk/orm/model/ormlist" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "github.com/cosmos/cosmos-sdk/orm/types/kv" "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/timestamppb" + "gotest.tools/v3/assert" + "gotest.tools/v3/golden" + "pgregory.net/rapid" ) func TestScenario(t *testing.T) { @@ -40,30 +35,32 @@ func TestScenario(t *testing.T) { }) assert.NilError(t, err) - // first run tests with a split index-commitment store + // First run tests with a split index-commitment store. runTestScenario(t, table, testkv.NewSplitMemBackend()) - // now run tests with a shared index-commitment store + // Now run tests with a shared index-commitment store. - // we're going to wrap this test in a debug store and save the decoded debug + // We're going to wrap this test in a debug store and save the decoded debug // messages, these will be checked against a golden file at the end of the - // test. the golden file can be used for fine-grained debugging of kv-store - // layout + // test. The golden file can be used for fine-grained debugging of kv-store + // layout. debugBuf := &strings.Builder{} store := testkv.NewDebugBackend( testkv.NewSharedMemBackend(), &testkv.EntryCodecDebugger{ EntryCodec: table, - Print: func(s string) { debugBuf.WriteString(s + "\n") }, + Print: func(s string) { + debugBuf.WriteString(s + "\n") //nolint:errcheck,revive // we're going to pass the whole function + }, }, ) runTestScenario(t, table, store) - // we're going to store debug data in a golden file to make sure that + // We're going to store debug data in a golden file to make sure that // logical decoding works successfully // run `go test pkgname -test.update-golden` to update the golden file - // see https://pkg.go.dev/gotest.tools/v3/golden for docs + // see https://pkg.go.dev/gotest.tools/v3/golden for docs. golden.Assert(t, debugBuf.String(), "test_scenario.golden") checkEncodeDecodeEntries(t, table, store.IndexStoreReader()) @@ -94,7 +91,7 @@ func TestPaginationLimitCountTotal(t *testing.T) { it, err = store.List(ctx, &testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{Limit: 1, CountTotal: true})) assert.NilError(t, err) - for it.Next() { + for it.Next() { //nolint:revive // we need this empty block here } pr := it.PageResponse() assert.Check(t, pr != nil) @@ -151,7 +148,7 @@ func TestTimestampIndex(t *testing.T) { i++ } - // insert a nil entry + // Insert a nil entry. id, err := store.InsertReturningId(ctx, &testpb.ExampleTimestamp{ Name: "nil", Ts: nil, @@ -165,7 +162,7 @@ func TestTimestampIndex(t *testing.T) { it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}) assert.NilError(t, err) - // make sure nils are ordered last + // Make sure nils are ordered last. timeOrder = append(timeOrder, nil) i = 0 for it.Next() { @@ -182,7 +179,7 @@ func TestTimestampIndex(t *testing.T) { } it.Close() - // try iterating over just nil timestamps + // Try iterating over just nil timestamps. it, err = store.List(ctx, testpb.ExampleTimestampTsIndexKey{}.WithTs(nil)) assert.NilError(t, err) assert.Assert(t, it.Next()) @@ -193,8 +190,9 @@ func TestTimestampIndex(t *testing.T) { it.Close() } -// check that the ormkv.Entry's decode and encode to the same bytes +// check that the ormkv.Entry's decode and encode to the same bytes. func checkEncodeDecodeEntries(t *testing.T, table ormtable.Table, store kv.ReadonlyStore) { + t.Helper() it, err := store.Iterator(nil, nil) assert.NilError(t, err) for it.Valid() { @@ -211,73 +209,74 @@ func checkEncodeDecodeEntries(t *testing.T, table ormtable.Table, store kv.Reado } func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backend) { + t.Helper() ctx := ormtable.WrapContextDefault(backend) store, err := testpb.NewExampleTableTable(table) assert.NilError(t, err) - // let's create 10 data items we'll use later and give them indexes + // Let's create 10 data items we'll use later and give them indexes. data := []*testpb.ExampleTable{ - {U32: 4, I64: -2, Str: "abc", U64: 7}, // 0 - {U32: 4, I64: -2, Str: "abd", U64: 7}, // 1 - {U32: 4, I64: -1, Str: "abc", U64: 8}, // 2 - {U32: 5, I64: -2, Str: "abd", U64: 8}, // 3 - {U32: 5, I64: -2, Str: "abe", U64: 9}, // 4 - {U32: 7, I64: -2, Str: "abe", U64: 10}, // 5 - {U32: 7, I64: -1, Str: "abe", U64: 11}, // 6 - {U32: 8, I64: -4, Str: "abc", U64: 11}, // 7 - {U32: 8, I64: 1, Str: "abc", U64: 12}, // 8 - {U32: 8, I64: 1, Str: "abd", U64: 10}, // 9 + {U32: 4, I64: -2, Str: "abc", U64: 7}, // 0. + {U32: 4, I64: -2, Str: "abd", U64: 7}, // 1. + {U32: 4, I64: -1, Str: "abc", U64: 8}, // 2. + {U32: 5, I64: -2, Str: "abd", U64: 8}, // 3. + {U32: 5, I64: -2, Str: "abe", U64: 9}, // 4. + {U32: 7, I64: -2, Str: "abe", U64: 10}, // 5. + {U32: 7, I64: -1, Str: "abe", U64: 11}, // 6. + {U32: 8, I64: -4, Str: "abc", U64: 11}, // 7. + {U32: 8., I64: 1, Str: "abc", U64: 12}, // 8 + {U32: 8, I64: 1, Str: "abd", U64: 10}, // 9. } - // let's make a function to match what's in our iterator with what we - // expect using indexes in the data array above + // Let's make a function to match what's in our iterator with what we + // expect using indexes in the data array above. assertIteratorItems := func(it ormtable.Iterator, xs ...int) { for _, i := range xs { assert.Assert(t, it.Next()) msg, err := it.GetMessage() assert.NilError(t, err) - // t.Logf("data[%d] %v == %v", i, data[i], msg) + // T.Logf("data[%d] %v == %v", i, data[i], msg). assert.DeepEqual(t, data[i], msg, protocmp.Transform()) } - // make sure the iterator is done + // Make sure the iterator is done. assert.Assert(t, !it.Next()) } - // insert one record + // Insert one record. err = store.Insert(ctx, data[0]) assert.NilError(t, err) - // trivial prefix query has one record + // Trivial prefix query has one record. it, err := store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0) - // insert one record + // Insert one record. err = store.Insert(ctx, data[1]) assert.NilError(t, err) - // trivial prefix query has two records + // Trivial prefix query has two records. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 1) - // insert the other records + // Insert the other records. assert.NilError(t, err) for i := 2; i < len(data); i++ { err = store.Insert(ctx, data[i]) assert.NilError(t, err) } - // let's do a prefix query on the primary key + // Let's do a prefix query on the primary key. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}.WithU32(8)) assert.NilError(t, err) assertIteratorItems(it, 7, 8, 9) - // let's try a reverse prefix query + // Let's try a reverse prefix query. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}.WithU32(4), ormlist.Reverse()) assert.NilError(t, err) defer it.Close() assertIteratorItems(it, 2, 1, 0) - // let's try a range query + // Let's try a range query. it, err = store.ListRange(ctx, testpb.ExampleTablePrimaryKey{}.WithU32I64(4, -1), testpb.ExampleTablePrimaryKey{}.WithU32(7), @@ -286,7 +285,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen defer it.Close() assertIteratorItems(it, 2, 3, 4, 5, 6) - // and another range query + // And another range query. it, err = store.ListRange(ctx, testpb.ExampleTablePrimaryKey{}.WithU32I64(5, -3), testpb.ExampleTablePrimaryKey{}.WithU32I64Str(8, 1, "abc"), @@ -295,7 +294,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen defer it.Close() assertIteratorItems(it, 3, 4, 5, 6, 7, 8) - // now a reverse range query on a different index + // Now a reverse range query on a different index. strU32Index := table.GetIndex("str,u32") assert.Assert(t, strU32Index != nil) it, err = store.ListRange(ctx, @@ -306,14 +305,14 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 9, 3, 1, 8, 7, 2, 0) - // another prefix query forwards + // Another prefix query forwards. it, err = store.List(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abe", 7), ) assert.NilError(t, err) assertIteratorItems(it, 5, 6) - // and backwards + // And backwards. it, err = store.List(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abc", 4), ormlist.Reverse(), @@ -321,7 +320,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 2, 0) - // try filtering + // Try filtering. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Filter(func(message proto.Message) bool { ex := message.(*testpb.ExampleTable) return ex.U64 != 10 @@ -329,7 +328,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 0, 1, 2, 3, 4, 6, 7, 8) - // try a cursor + // Try a cursor. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assert.Assert(t, it.Next()) @@ -338,7 +337,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 2, 3, 4, 5, 6, 7, 8, 9) - // try an unique index + // Try an unique index. found, err := store.HasByU64Str(ctx, 12, "abc") assert.NilError(t, err) assert.Assert(t, found) @@ -346,7 +345,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assert.DeepEqual(t, data[8], a, protocmp.Transform()) - // let's try paginating some stuff + // Let's try paginating some stuff. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 4, CountTotal: true, @@ -358,7 +357,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Equal(t, uint64(10), res.Total) assert.Assert(t, res.NextKey != nil) - // let's use a default limit + // Let's use a default limit. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.DefaultLimit(4), ormlist.Paginate(&queryv1beta1.PageRequest{ @@ -371,7 +370,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Equal(t, uint64(10), res.Total) assert.Assert(t, res.NextKey != nil) - // read another page + // Read another page. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Key: res.NextKey, Limit: 4, @@ -382,7 +381,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey != nil) - // and the last page + // And the last page. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Key: res.NextKey, Limit: 4, @@ -393,7 +392,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey == nil) - // let's go backwards + // Let's go backwards. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 2, CountTotal: true, @@ -406,7 +405,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey != nil) assert.Equal(t, uint64(10), res.Total) - // a bit more + // A bit more. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Key: res.NextKey, Limit: 2, @@ -418,7 +417,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey != nil) - // range query + // Range query. it, err = store.ListRange(ctx, testpb.ExampleTablePrimaryKey{}.WithU32I64Str(4, -1, "abc"), testpb.ExampleTablePrimaryKey{}.WithU32I64Str(7, -2, "abe"), @@ -431,7 +430,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res != nil) assert.Assert(t, res.NextKey == nil) - // let's try an offset + // Let's try an offset. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 2, CountTotal: true, @@ -444,7 +443,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey != nil) assert.Equal(t, uint64(10), res.Total) - // and reverse + // And reverse. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 3, CountTotal: true, @@ -458,7 +457,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey != nil) assert.Equal(t, uint64(10), res.Total) - // now an offset that's slightly too big + // Now an offset that's slightly too big. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}, ormlist.Paginate(&queryv1beta1.PageRequest{ Limit: 1, CountTotal: true, @@ -471,19 +470,19 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, res.NextKey == nil) assert.Equal(t, uint64(10), res.Total) - // now let's update some things + // Now let's update some things. for i := 0; i < 5; i++ { - data[i].U64 = data[i].U64 * 2 + data[i].U64 *= 2 data[i].Bz = []byte(data[i].Str) err = store.Update(ctx, data[i]) assert.NilError(t, err) } it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) - // we should still get everything in the same order + // We should still get everything in the same order. assertIteratorItems(it, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - // let's use SAVE_MODE_DEFAULT and add something + // Let's use SAVE_MODE_DEFAULT and add something. data = append(data, &testpb.ExampleTable{U32: 9}) err = store.Save(ctx, data[10]) assert.NilError(t, err) @@ -491,19 +490,19 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assert.Assert(t, a != nil) assert.DeepEqual(t, data[10], a, protocmp.Transform()) - // and update it + // And update it. data[10].B = true assert.NilError(t, table.Save(ctx, data[10])) a, err = store.Get(ctx, 9, 0, "") assert.NilError(t, err) assert.Assert(t, a != nil) assert.DeepEqual(t, data[10], a, protocmp.Transform()) - // and iterate + // And iterate. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - // let's export and import JSON and use a read-only backend + // Let's export and import JSON and use a read-only backend. buf := &bytes.Buffer{} readBackend := ormtable.NewReadBackend(ormtable.ReadBackendOptions{ CommitmentStoreReader: backend.CommitmentStoreReader(), @@ -513,32 +512,32 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, table.ValidateJSON(bytes.NewReader(buf.Bytes()))) store2 := ormtable.WrapContextDefault(testkv.NewSplitMemBackend()) assert.NilError(t, table.ImportJSON(store2, bytes.NewReader(buf.Bytes()))) - assertTablesEqual(t, table, ctx, store2) + assertTablesEqual(ctx, store2, t, table) - // let's delete item 5 + // Let's delete item 5. err = store.DeleteBy(ctx, testpb.ExampleTableU32I64StrIndexKey{}.WithU32I64Str(7, -2, "abe")) assert.NilError(t, err) - // it should be gone + // It should be gone. found, err = store.Has(ctx, 7, -2, "abe") assert.NilError(t, err) assert.Assert(t, !found) - // and missing from the iterator + // And missing from the iterator. it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 1, 2, 3, 4, 6, 7, 8, 9, 10) - // let's do a batch delete - // first iterate over the items we'll delete to check that iterator + // Let's do a batch delete + // first iterate over the items we'll delete to check that iterator. it, err = store.List(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStr("abd")) assert.NilError(t, err) assertIteratorItems(it, 1, 3, 9) - // now delete them + // Now delete them. assert.NilError(t, store.DeleteBy(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStr("abd"))) it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 0, 2, 4, 6, 7, 8, 10) - // Let's do a range delete + // Let's do a range delete. assert.NilError(t, store.DeleteRange(ctx, testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abc", 8), testpb.ExampleTableStrU32IndexKey{}.WithStrU32("abe", 5), @@ -547,7 +546,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.NilError(t, err) assertIteratorItems(it, 0, 2, 6, 10) - // Let's delete something directly + // Let's delete something directly. assert.NilError(t, store.Delete(ctx, data[0])) it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) @@ -559,6 +558,7 @@ func TestRandomTableData(t *testing.T) { } func testTable(t *testing.T, tableData *TableData) { + t.Helper() for _, index := range tableData.table.Indexes() { indexModel := &IndexModel{ TableData: tableData, @@ -573,6 +573,7 @@ func testTable(t *testing.T, tableData *TableData) { } func testUniqueIndex(t *testing.T, model *IndexModel) { + t.Helper() index := model.index.(ormtable.UniqueIndex) t.Logf("testing unique index %T %s", index, index.Fields()) for i := 0; i < len(model.data); i++ { @@ -595,6 +596,7 @@ func testUniqueIndex(t *testing.T, model *IndexModel) { } func testIndex(t *testing.T, model *IndexModel) { + t.Helper() index := model.index if index.IsFullyOrdered() { t.Logf("testing index %T %s", index, index.Fields()) @@ -630,7 +632,7 @@ func testIndex(t *testing.T, model *IndexModel) { } else { t.Logf("testing unordered index %T %s", index, index.Fields()) - // get all the data + // Get all the data. it, err := model.index.List(model.context, nil) assert.NilError(t, err) var data2 []proto.Message @@ -641,7 +643,7 @@ func testIndex(t *testing.T, model *IndexModel) { } assert.Equal(t, len(model.data), len(data2)) - // sort it + // Sort it. model2 := &IndexModel{ TableData: &TableData{ table: model.table, @@ -652,7 +654,7 @@ func testIndex(t *testing.T, model *IndexModel) { } sort.Sort(model2) - // compare + // Compare. for i := 0; i < len(data2); i++ { assert.DeepEqual(t, model.data[i], data2[i], protocmp.Transform()) } @@ -703,7 +705,7 @@ func TableDataGen[T proto.Message](elemGen *rapid.Generator[T], n int) *rapid.Ge for i := 0; i < n; { message = elemGen.Draw(t, fmt.Sprintf("message[%d]", i)) err := table.Insert(store, message) - if sdkerrors.IsOf(err, ormerrors.PrimaryKeyConstraintViolation, ormerrors.UniqueKeyViolation) { + if sdkerrors.IsOf(err, ormerrors.ErrPrimaryKeyConstraintViolation, ormerrors.ErrUniqueKeyViolation) { continue } else if err != nil { panic(err) @@ -763,9 +765,7 @@ func (m *IndexModel) Less(i, j int) bool { } func (m *IndexModel) Swap(i, j int) { - x := m.data[i] - m.data[i] = m.data[j] - m.data[j] = x + m.data[i], m.data[j] = m.data[j], m.data[i] } var _ sort.Interface = &IndexModel{} @@ -780,11 +780,11 @@ func TestJSONExportImport(t *testing.T) { for i := 0; i < 100; { x := testutil.GenA.Example() err = table.Insert(store, x) - if sdkerrors.IsOf(err, ormerrors.PrimaryKeyConstraintViolation, ormerrors.UniqueKeyViolation) { + if sdkerrors.IsOf(err, ormerrors.ErrPrimaryKeyConstraintViolation, ormerrors.ErrUniqueKeyViolation) { continue - } else { - assert.NilError(t, err) } + assert.NilError(t, err) + i++ } @@ -796,10 +796,10 @@ func TestJSONExportImport(t *testing.T) { store2 := ormtable.WrapContextDefault(testkv.NewSplitMemBackend()) assert.NilError(t, table.ImportJSON(store2, bytes.NewReader(buf.Bytes()))) - assertTablesEqual(t, table, store, store2) + assertTablesEqual(store, store2, t, table) } -func assertTablesEqual(t assert.TestingT, table ormtable.Table, ctx, ctx2 context.Context) { +func assertTablesEqual(ctx, ctx2 context.Context, t assert.TestingT, table ormtable.Table) { it, err := table.List(ctx, nil) assert.NilError(t, err) it2, err := table.List(ctx2, nil) @@ -822,8 +822,8 @@ func assertTablesEqual(t assert.TestingT, table ormtable.Table, ctx, ctx2 contex } } -func protoValuesToInterfaces(ks []protoreflect.Value) []interface{} { - values := make([]interface{}, len(ks)) +func protoValuesToInterfaces(ks []protoreflect.Value) []any { + values := make([]any, len(ks)) for i := 0; i < len(ks); i++ { values[i] = ks[i].Interface() } @@ -841,7 +841,7 @@ func TestReadonly(t *testing.T) { IndexStoreReader: dbm.NewMemDB(), }) ctx := ormtable.WrapContextDefault(readBackend) - assert.ErrorIs(t, ormerrors.ReadOnly, table.Insert(ctx, &testpb.ExampleTable{})) + assert.ErrorIs(t, ormerrors.ErrReadOnly, table.Insert(ctx, &testpb.ExampleTable{})) } func TestInsertReturningFieldName(t *testing.T) { diff --git a/orm/model/ormtable/unique.go b/orm/model/ormtable/unique.go index 13127da04c43..232cfa64eeeb 100644 --- a/orm/model/ormtable/unique.go +++ b/orm/model/ormtable/unique.go @@ -3,19 +3,14 @@ package ormtable import ( "context" - "github.com/cosmos/cosmos-sdk/orm/types/kv" - + "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" + "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" "github.com/cosmos/cosmos-sdk/orm/internal/fieldnames" - "github.com/cosmos/cosmos-sdk/orm/model/ormlist" - - "github.com/cosmos/cosmos-sdk/orm/encoding/encodeutil" - + "github.com/cosmos/cosmos-sdk/orm/types/kv" + "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" - - "github.com/cosmos/cosmos-sdk/orm/encoding/ormkv" - "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" ) type uniqueKeyIndex struct { @@ -25,7 +20,7 @@ type uniqueKeyIndex struct { getReadBackend func(context.Context) (ReadBackend, error) } -func (u uniqueKeyIndex) List(ctx context.Context, prefixKey []interface{}, options ...ormlist.Option) (Iterator, error) { +func (u uniqueKeyIndex) List(ctx context.Context, prefixKey []any, options ...ormlist.Option) (Iterator, error) { backend, err := u.getReadBackend(ctx) if err != nil { return nil, err @@ -34,7 +29,7 @@ func (u uniqueKeyIndex) List(ctx context.Context, prefixKey []interface{}, optio return prefixIterator(backend.IndexStoreReader(), backend, u, u.GetKeyCodec(), prefixKey, options) } -func (u uniqueKeyIndex) ListRange(ctx context.Context, from, to []interface{}, options ...ormlist.Option) (Iterator, error) { +func (u uniqueKeyIndex) ListRange(ctx context.Context, from, to []any, options ...ormlist.Option) (Iterator, error) { backend, err := u.getReadBackend(ctx) if err != nil { return nil, err @@ -43,9 +38,9 @@ func (u uniqueKeyIndex) ListRange(ctx context.Context, from, to []interface{}, o return rangeIterator(backend.IndexStoreReader(), backend, u, u.GetKeyCodec(), from, to, options) } -func (u uniqueKeyIndex) doNotImplement() {} +func (uniqueKeyIndex) doNotImplement() {} -func (u uniqueKeyIndex) Has(ctx context.Context, values ...interface{}) (found bool, err error) { +func (u uniqueKeyIndex) Has(ctx context.Context, values ...any) (found bool, err error) { backend, err := u.getReadBackend(ctx) if err != nil { return false, err @@ -59,7 +54,7 @@ func (u uniqueKeyIndex) Has(ctx context.Context, values ...interface{}) (found b return backend.IndexStoreReader().Has(key) } -func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValues ...interface{}) (found bool, err error) { +func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValues ...any) (found bool, err error) { backend, err := u.getReadBackend(ctx) if err != nil { return false, err @@ -75,7 +70,7 @@ func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValue return false, err } - // for unique keys, value can be empty and the entry still exists + // For unique keys, value can be empty and the entry still exists. if value == nil { return false, nil } @@ -85,10 +80,10 @@ func (u uniqueKeyIndex) Get(ctx context.Context, message proto.Message, keyValue return true, err } - return u.primaryKey.get(backend, message, pk) + return u.primaryKey.doGet(backend, message, pk) } -func (u uniqueKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) error { +func (u uniqueKeyIndex) DeleteBy(ctx context.Context, keyValues ...any) error { it, err := u.List(ctx, keyValues) if err != nil { return err @@ -97,7 +92,7 @@ func (u uniqueKeyIndex) DeleteBy(ctx context.Context, keyValues ...interface{}) return u.primaryKey.deleteByIterator(ctx, it) } -func (u uniqueKeyIndex) DeleteRange(ctx context.Context, from, to []interface{}) error { +func (u uniqueKeyIndex) DeleteRange(ctx context.Context, from, to []any) error { it, err := u.ListRange(ctx, from, to) if err != nil { return err @@ -118,16 +113,16 @@ func (u uniqueKeyIndex) onInsert(store kv.Store, message protoreflect.Message) e } if has { - return ormerrors.UniqueKeyViolation.Wrapf("%q", u.fields) + return ormerrors.ErrUniqueKeyViolation.Wrapf("%q", u.fields) } return store.Set(k, v) } -func (u uniqueKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Message) error { +func (u uniqueKeyIndex) onUpdate(store kv.Store, newMsg, existingMsg protoreflect.Message) error { keyCodec := u.GetKeyCodec() - newValues := keyCodec.GetKeyValues(new) - existingValues := keyCodec.GetKeyValues(existing) + newValues := keyCodec.GetKeyValues(newMsg) + existingValues := keyCodec.GetKeyValues(existingMsg) if keyCodec.CompareKeys(newValues, existingValues) == 0 { return nil } @@ -143,7 +138,7 @@ func (u uniqueKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Mess } if has { - return ormerrors.UniqueKeyViolation.Wrapf("%q", u.fields) + return ormerrors.ErrUniqueKeyViolation.Wrapf("%q", u.fields) } existingKey, err := keyCodec.EncodeKey(existingValues) @@ -156,7 +151,7 @@ func (u uniqueKeyIndex) onUpdate(store kv.Store, new, existing protoreflect.Mess return err } - _, value, err := u.GetValueCodec().EncodeKeyFromMessage(new) + _, value, err := u.GetValueCodec().EncodeKeyFromMessage(newMsg) if err != nil { return err } @@ -174,13 +169,13 @@ func (u uniqueKeyIndex) onDelete(store kv.Store, message protoreflect.Message) e } func (u uniqueKeyIndex) readValueFromIndexKey(store ReadBackend, primaryKey []protoreflect.Value, _ []byte, message proto.Message) error { - found, err := u.primaryKey.get(store, message, primaryKey) + found, err := u.primaryKey.doGet(store, message, primaryKey) if err != nil { return err } if !found { - return ormerrors.UnexpectedError.Wrapf("can't find primary key") + return ormerrors.ErrUnexpectedError.Wrapf("can't find primary key") } return nil diff --git a/orm/orm.go b/orm/orm.go index 558a061c7460..0467e8f35707 100644 --- a/orm/orm.go +++ b/orm/orm.go @@ -8,14 +8,12 @@ import ( ormv1alpha1 "cosmossdk.io/api/cosmos/orm/v1alpha1" "cosmossdk.io/core/appmodule" "cosmossdk.io/core/store" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protodesc" - "google.golang.org/protobuf/reflect/protoregistry" - "cosmossdk.io/depinject" - "github.com/cosmos/cosmos-sdk/orm/model/ormdb" "github.com/cosmos/cosmos-sdk/orm/model/ormtable" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoregistry" ) func init() { diff --git a/orm/testing/ormmocks/hooks.go b/orm/testing/ormmocks/hooks.go index c5ad0e6f0b17..cf4471a8548b 100644 --- a/orm/testing/ormmocks/hooks.go +++ b/orm/testing/ormmocks/hooks.go @@ -44,7 +44,7 @@ func (m *MockValidateHooks) ValidateDelete(arg0 context.Context, arg1 proto.Mess } // ValidateDelete indicates an expected call of ValidateDelete. -func (mr *MockValidateHooksMockRecorder) ValidateDelete(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockValidateHooksMockRecorder) ValidateDelete(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateDelete", reflect.TypeOf((*MockValidateHooks)(nil).ValidateDelete), arg0, arg1) } @@ -58,7 +58,7 @@ func (m *MockValidateHooks) ValidateInsert(arg0 context.Context, arg1 proto.Mess } // ValidateInsert indicates an expected call of ValidateInsert. -func (mr *MockValidateHooksMockRecorder) ValidateInsert(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockValidateHooksMockRecorder) ValidateInsert(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateInsert", reflect.TypeOf((*MockValidateHooks)(nil).ValidateInsert), arg0, arg1) } @@ -72,7 +72,7 @@ func (m *MockValidateHooks) ValidateUpdate(ctx context.Context, existing, new pr } // ValidateUpdate indicates an expected call of ValidateUpdate. -func (mr *MockValidateHooksMockRecorder) ValidateUpdate(ctx, existing, new interface{}) *gomock.Call { +func (mr *MockValidateHooksMockRecorder) ValidateUpdate(ctx, existing, new any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateUpdate", reflect.TypeOf((*MockValidateHooks)(nil).ValidateUpdate), ctx, existing, new) } @@ -107,7 +107,7 @@ func (m *MockWriteHooks) OnDelete(arg0 context.Context, arg1 proto.Message) { } // OnDelete indicates an expected call of OnDelete. -func (mr *MockWriteHooksMockRecorder) OnDelete(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockWriteHooksMockRecorder) OnDelete(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnDelete", reflect.TypeOf((*MockWriteHooks)(nil).OnDelete), arg0, arg1) } @@ -119,7 +119,7 @@ func (m *MockWriteHooks) OnInsert(arg0 context.Context, arg1 proto.Message) { } // OnInsert indicates an expected call of OnInsert. -func (mr *MockWriteHooksMockRecorder) OnInsert(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockWriteHooksMockRecorder) OnInsert(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnInsert", reflect.TypeOf((*MockWriteHooks)(nil).OnInsert), arg0, arg1) } @@ -131,7 +131,7 @@ func (m *MockWriteHooks) OnUpdate(ctx context.Context, existing, new proto.Messa } // OnUpdate indicates an expected call of OnUpdate. -func (mr *MockWriteHooksMockRecorder) OnUpdate(ctx, existing, new interface{}) *gomock.Call { +func (mr *MockWriteHooksMockRecorder) OnUpdate(ctx, existing, new any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnUpdate", reflect.TypeOf((*MockWriteHooks)(nil).OnUpdate), ctx, existing, new) } diff --git a/orm/testing/ormmocks/match.go b/orm/testing/ormmocks/match.go index 8c1da2c022f0..fa5936e20370 100644 --- a/orm/testing/ormmocks/match.go +++ b/orm/testing/ormmocks/match.go @@ -15,13 +15,13 @@ func Eq(message proto.Message) gomock.Matcher { } type protoEq struct { - message interface{} + message any diff string } -func (p protoEq) Matches(x interface{}) bool { +func (p protoEq) Matches(x any) bool { p.diff = cmp.Diff(x, p.message, protocmp.Transform()) - return len(p.diff) == 0 + return p.diff == "" } func (p protoEq) String() string { diff --git a/orm/types/kv/store.go b/orm/types/kv/store.go index f1281b356a0a..66e4c830fa6f 100644 --- a/orm/types/kv/store.go +++ b/orm/types/kv/store.go @@ -9,11 +9,11 @@ import ( // ReadonlyStore is an interface for readonly access to a kv-store. type ReadonlyStore interface { // Get fetches the value of the given key, or nil if it does not exist. - // CONTRACT: key, value readonly []byte + // CONTRACT: key, value readonly []byte. Get(key []byte) ([]byte, error) // Has checks if a key exists. - // CONTRACT: key, value readonly []byte + // CONTRACT: key, value readonly []byte. Has(key []byte) (bool, error) // Iterator returns an iterator over a domain of keys, in ascending order. The caller must call @@ -21,7 +21,7 @@ type ReadonlyStore interface { // from the first key, and a nil end iterates to the last key (inclusive). Empty keys are not // valid. // CONTRACT: No writes may happen within a domain while an iterator exists over it. - // CONTRACT: start, end readonly []byte + // CONTRACT: start, end readonly []byte. Iterator(start, end []byte) (Iterator, error) // ReverseIterator returns an iterator over a domain of keys, in descending order. The caller @@ -29,7 +29,7 @@ type ReadonlyStore interface { // iterates from the last key (inclusive), and a nil start iterates to the first key (inclusive). // Empty keys are not valid. // CONTRACT: No writes may happen within a domain while an iterator exists over it. - // CONTRACT: start, end readonly []byte + // CONTRACT: start, end readonly []byte. ReverseIterator(start, end []byte) (Iterator, error) } @@ -41,10 +41,10 @@ type Store interface { ReadonlyStore // Set sets the value for the given key, replacing it if it already exists. - // CONTRACT: key, value readonly []byte + // CONTRACT: key, value readonly []byte. Set(key, value []byte) error // Delete deletes the key, or does nothing if the key does not exist. - // CONTRACT: key readonly []byte + // CONTRACT: key readonly []byte. Delete(key []byte) error } diff --git a/orm/types/ormerrors/errors.go b/orm/types/ormerrors/errors.go index ef4dac26e035..08b4e71d055b 100644 --- a/orm/types/ormerrors/errors.go +++ b/orm/types/ormerrors/errors.go @@ -5,43 +5,43 @@ import ( "google.golang.org/grpc/codes" ) -var codespace = "orm" +var ormcodespace = "orm" // IsNotFound returns true if the error indicates that the record was not found. func IsNotFound(err error) bool { - return errors.IsOf(err, NotFound) + return errors.IsOf(err, ErrNotFound) } var ( - InvalidTableId = errors.New(codespace, 1, "invalid or missing table or single id, need a non-zero value") - MissingPrimaryKey = errors.New(codespace, 2, "table is missing primary key") - InvalidKeyFieldsDefinition = errors.New(codespace, 3, "invalid field definition for key") - DuplicateKeyField = errors.New(codespace, 4, "duplicate field in key") - FieldNotFound = errors.New(codespace, 5, "field not found") - InvalidAutoIncrementKey = errors.New(codespace, 6, "an auto-increment primary key must specify a single uint64 field") - InvalidIndexId = errors.New(codespace, 7, "invalid or missing index id, need a value >= 0 and < 32768") - DuplicateIndexId = errors.New(codespace, 8, "duplicate index id") - PrimaryKeyConstraintViolation = errors.New(codespace, 9, "object with primary key already exists") - PrimaryKeyInvalidOnUpdate = errors.New(codespace, 11, "can't update object with missing or invalid primary key") - AutoIncrementKeyAlreadySet = errors.New(codespace, 12, "can't create with auto-increment primary key already set") - CantFindIndex = errors.New(codespace, 13, "can't find index") - UnexpectedDecodePrefix = errors.New(codespace, 14, "unexpected prefix while trying to decode an entry") - UnsupportedOperation = errors.New(codespace, 16, "unsupported operation") - BadDecodeEntry = errors.New(codespace, 17, "bad decode entry") - IndexOutOfBounds = errors.New(codespace, 18, "index out of bounds") - InvalidListOptions = errors.New(codespace, 19, "invalid list options") - InvalidKeyField = errors.New(codespace, 20, "invalid key field") - UnexpectedError = errors.New(codespace, 21, "unexpected error") - InvalidRangeIterationKeys = errors.New(codespace, 22, "invalid range iteration keys") - JSONImportError = errors.New(codespace, 23, "json import error") - UniqueKeyViolation = errors.RegisterWithGRPCCode(codespace, 24, codes.FailedPrecondition, "unique key violation") - InvalidTableDefinition = errors.New(codespace, 25, "invalid table definition") - InvalidFileDescriptorID = errors.New(codespace, 26, "invalid file descriptor ID") - TableNotFound = errors.New(codespace, 27, "table not found") - JSONValidationError = errors.New(codespace, 28, "invalid JSON") - NotFound = errors.RegisterWithGRPCCode(codespace, 29, codes.NotFound, "not found") - ReadOnly = errors.New(codespace, 30, "database is read-only") - AlreadyExists = errors.RegisterWithGRPCCode(codespace, 31, codes.AlreadyExists, "already exists") - ConstraintViolation = errors.RegisterWithGRPCCode(codespace, 32, codes.FailedPrecondition, "failed precondition") - NoTableDescriptor = errors.New(codespace, 33, "no table descriptor found") + ErrInvalidTableID = errors.New(ormcodespace, 1, "invalid or missing table or single id, need a non-zero value") + ErrMissingPrimaryKey = errors.New(ormcodespace, 2, "table is missing primary key") + ErrInvalidKeyFieldsDefinition = errors.New(ormcodespace, 3, "invalid field definition for key") + ErrDuplicateKeyField = errors.New(ormcodespace, 4, "duplicate field in key") + ErrFieldNotFound = errors.New(ormcodespace, 5, "field not found") + ErrInvalidAutoIncrementKey = errors.New(ormcodespace, 6, "an auto-increment primary key must specify a single uint64 field") + ErrInvalidIndexID = errors.New(ormcodespace, 7, "invalid or missing index id, need a value >= 0 and < 32768") + ErrDuplicateIndexID = errors.New(ormcodespace, 8, "duplicate index id") + ErrPrimaryKeyConstraintViolation = errors.New(ormcodespace, 9, "object with primary key already exists") + ErrPrimaryKeyInvalidOnUpdate = errors.New(ormcodespace, 11, "can't update object with missing or invalid primary key") + ErrAutoIncrementKeyAlreadySet = errors.New(ormcodespace, 12, "can't create with auto-increment primary key already set") + ErrCantFindIndex = errors.New(ormcodespace, 13, "can't find index") + ErrUnexpectedDecodePrefix = errors.New(ormcodespace, 14, "unexpected prefix while trying to decode an entry") + ErrUnsupportedOperation = errors.New(ormcodespace, 16, "unsupported operation") + ErrBadDecodeEntry = errors.New(ormcodespace, 17, "bad decode entry") + ErrIndexOutOfBounds = errors.New(ormcodespace, 18, "index out of bounds") + ErrInvalidListOptions = errors.New(ormcodespace, 19, "invalid list options") + ErrInvalidKeyField = errors.New(ormcodespace, 20, "invalid key field") + ErrUnexpectedError = errors.New(ormcodespace, 21, "unexpected error") + ErrInvalidRangeIterationKeys = errors.New(ormcodespace, 22, "invalid range iteration keys") + ErrJSONImportError = errors.New(ormcodespace, 23, "json import error") + ErrUniqueKeyViolation = errors.RegisterWithGRPCCode(ormcodespace, 24, codes.FailedPrecondition, "unique key violation") + ErrInvalidTableDefinition = errors.New(ormcodespace, 25, "invalid table definition") + ErrInvalidFileDescriptorID = errors.New(ormcodespace, 26, "invalid file descriptor ID") + ErrTableNotFound = errors.New(ormcodespace, 27, "table not found") + ErrJSONValidationError = errors.New(ormcodespace, 28, "invalid JSON") + ErrNotFound = errors.RegisterWithGRPCCode(ormcodespace, 29, codes.NotFound, "not found") + ErrReadOnly = errors.New(ormcodespace, 30, "database is read-only") + ErrOrmAlreadyExists = errors.RegisterWithGRPCCode(ormcodespace, 31, codes.AlreadyExists, "already exists") + ErrConstraintViolation = errors.RegisterWithGRPCCode(ormcodespace, 32, codes.FailedPrecondition, "failed precondition") + ErrNoTableDescriptor = errors.New(ormcodespace, 33, "no table descriptor found") ) diff --git a/server/grpc/gogoreflection/serverreflection.go b/server/grpc/gogoreflection/serverreflection.go index a7be3e469050..52b10f4f8f0c 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -46,7 +46,6 @@ import ( "sort" "sync" - //nolint: staticcheck "github.com/golang/protobuf/proto" dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/grpc" diff --git a/server/mock/app.go b/server/mock/app.go index 5c977b53d21f..832d50bc76b5 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -147,7 +147,7 @@ type MsgServerImpl struct { capKeyMainStore *storetypes.KVStoreKey } -func _Msg_Test_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { //nolint:revive +func _Msg_Test_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(KVStoreTx) if err := dec(in); err != nil { return nil, err diff --git a/server/mock/tx.go b/server/mock/tx.go index 8201504095ec..f8daaedbc7a5 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -121,7 +121,7 @@ func decodeTx(txBytes []byte) (sdk.Tx, error) { var tx sdk.Tx split := bytes.Split(txBytes, []byte("=")) - if len(split) == 1 { //nolint:gocritic + if len(split) == 1 { k := split[0] tx = &KVStoreTx{k, k, txBytes, nil} } else if len(split) == 2 { diff --git a/testutil/rest.go b/testutil/rest.go index 93608482d195..3a3103dcbc8b 100644 --- a/testutil/rest.go +++ b/testutil/rest.go @@ -42,7 +42,7 @@ func GetRequestWithHeaders(url string, headers map[string]string) ([]byte, error // GetRequest defines a wrapper around an HTTP GET request with a provided URL. // An error is returned if the request or reading the body fails. func GetRequest(url string) ([]byte, error) { - res, err := http.Get(url) //nolint:gosec + res, err := http.Get(url) if err != nil { return nil, err } @@ -61,7 +61,7 @@ func GetRequest(url string) ([]byte, error) { // PostRequest defines a wrapper around an HTTP POST request with a provided URL and data. // An error is returned if the request or reading the body fails. func PostRequest(url, contentType string, data []byte) ([]byte, error) { - res, err := http.Post(url, contentType, bytes.NewBuffer(data)) //nolint:gosec + res, err := http.Post(url, contentType, bytes.NewBuffer(data)) if err != nil { return nil, fmt.Errorf("error while sending post request: %w", err) } diff --git a/testutil/sims/simulation_helpers.go b/testutil/sims/simulation_helpers.go index 152703bf11ae..7c017a8144e7 100644 --- a/testutil/sims/simulation_helpers.go +++ b/testutil/sims/simulation_helpers.go @@ -68,7 +68,7 @@ func SimulationOperations(app runtime.AppI, cdc codec.JSONCodec, config simtypes } } - simState.LegacyProposalContents = app.SimulationManager().GetProposalContents(simState) //nolint:staticcheck + simState.LegacyProposalContents = app.SimulationManager().GetProposalContents(simState) //nolint:staticcheck // SA1019: simState.LegacyProposalContents is deprecated: LegacyProposalContents is deprecated simState.ProposalMsgs = app.SimulationManager().GetProposalMsgs(simState) return app.SimulationManager().WeightedOperations(simState) } diff --git a/testutil/sims/simulation_helpers_test.go b/testutil/sims/simulation_helpers_test.go index 55cc77b439aa..a499c50c568a 100644 --- a/testutil/sims/simulation_helpers_test.go +++ b/testutil/sims/simulation_helpers_test.go @@ -85,7 +85,7 @@ func TestDiffKVStores(t *testing.T) { // Same keys, different value. Comparisons will be nil as prefixes are skipped. prefix := []byte("prefix:") - k1Prefixed := append(prefix, k1...) //nolint:gocritic // append is fine here + k1Prefixed := append(prefix, k1...) store1.Set(k1Prefixed, v1) store2.Set(k1Prefixed, v2) checkDiffResults(t, store1, store2) diff --git a/x/auth/simulation/proposals.go b/x/auth/simulation/proposals.go index 87746569c22f..0e7cd95797f3 100644 --- a/x/auth/simulation/proposals.go +++ b/x/auth/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/auth/types/credentials.go b/x/auth/types/credentials.go index 83cd63dd2982..4c63fc8d8c41 100644 --- a/x/auth/types/credentials.go +++ b/x/auth/types/credentials.go @@ -27,7 +27,6 @@ func NewBaseAccountWithPubKey(pubkey cryptotypes.PubKey) (*BaseAccount, error) { return baseAccount, nil } -//nolint:gosec // this isn't an hardcoded credential const ModuleCredentialType = "ModuleCredential" var _ cryptotypes.PubKey = &ModuleCredential{} diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 33fe08dea025..6cb1f39b887e 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -27,9 +27,9 @@ var ( // Simulation operation weights constants const ( - OpWeightMsgGrant = "op_weight_msg_grant" //nolint:gosec - OpWeightRevoke = "op_weight_msg_revoke" //nolint:gosec - OpWeightExec = "op_weight_msg_execute" //nolint:gosec + OpWeightMsgGrant = "op_weight_msg_grant" + OpWeightRevoke = "op_weight_msg_revoke" + OpWeightExec = "op_weight_msg_execute" ) // authz operations weights diff --git a/x/bank/migrations/v3/store_test.go b/x/bank/migrations/v3/store_test.go index 83ba288abf80..bf0aed05e978 100644 --- a/x/bank/migrations/v3/store_test.go +++ b/x/bank/migrations/v3/store_test.go @@ -108,7 +108,7 @@ func TestMigrateDenomMetaData(t *testing.T) { newKey := denomMetadataIter.Key() // make sure old entry is deleted - oldKey := append(newKey, newKey[0:]...) //nolint:gocritic // append is ok here + oldKey := append(newKey, newKey[0:]...) bz := denomMetadataStore.Get(oldKey) require.Nil(t, bz) diff --git a/x/bank/simulation/genesis_test.go b/x/bank/simulation/genesis_test.go index 76be7256f84d..301596af9eb0 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -43,7 +43,7 @@ func TestRandomizedGenState(t *testing.T) { simState.Cdc.MustUnmarshalJSON(simState.GenState[types.ModuleName], &bankGenesis) assert.Equal(t, true, bankGenesis.Params.GetDefaultSendEnabled(), "Params.GetDefaultSendEnabled") - assert.Len(t, bankGenesis.Params.GetSendEnabled(), 0, "Params.GetSendEnabled") //nolint:staticcheck + assert.Len(t, bankGenesis.Params.GetSendEnabled(), 0, "Params.GetSendEnabled") if assert.Len(t, bankGenesis.Balances, 3) { assert.Equal(t, "cosmos1ghekyjucln7y67ntx7cf27m9dpuxxemn4c8g4r", bankGenesis.Balances[2].GetAddress().String(), "Balances[2] address") assert.Equal(t, "1000stake", bankGenesis.Balances[2].GetCoins().String(), "Balances[2] coins") diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 3f7a1b024d91..5d5037a2b858 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -18,10 +18,10 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgSend = "op_weight_msg_send" //nolint:gosec - OpWeightMsgMultiSend = "op_weight_msg_multisend" //nolint:gosec - DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend - DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend + OpWeightMsgSend = "op_weight_msg_send" + OpWeightMsgMultiSend = "op_weight_msg_multisend" + DefaultWeightMsgSend = 100 // from simappparams.DefaultWeightMsgSend + DefaultWeightMsgMultiSend = 10 // from simappparams.DefaultWeightMsgMultiSend ) // WeightedOperations returns all the operations from the module with their respective weights diff --git a/x/bank/simulation/proposals.go b/x/bank/simulation/proposals.go index 5a63b8632cea..3843b5f2566a 100644 --- a/x/bank/simulation/proposals.go +++ b/x/bank/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/bank/simulation/proposals_test.go b/x/bank/simulation/proposals_test.go index cc9ca7e55c08..a747b9bb2823 100644 --- a/x/bank/simulation/proposals_test.go +++ b/x/bank/simulation/proposals_test.go @@ -39,6 +39,6 @@ func TestProposalMsgs(t *testing.T) { fmt.Println(msgUpdateParams) assert.Equal(t, sdk.AccAddress(address.Module("gov")).String(), msgUpdateParams.Authority) - assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) //nolint:staticcheck + assert.Assert(t, len(msgUpdateParams.Params.SendEnabled) == 0) assert.Equal(t, true, msgUpdateParams.Params.DefaultSendEnabled) } diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 40165a31798a..0a97faf3a189 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -19,10 +19,10 @@ import ( // Simulation operation weights constants const ( - OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" //nolint:gosec - OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" //nolint:gosec - OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" //nolint:gosec - OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" //nolint:gosec + OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" + OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" + OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" + OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" DefaultWeightMsgSetWithdrawAddress int = 50 DefaultWeightMsgWithdrawDelegationReward int = 50 diff --git a/x/distribution/simulation/proposals.go b/x/distribution/simulation/proposals.go index 6330691afc26..858fa09e5607 100644 --- a/x/distribution/simulation/proposals.go +++ b/x/distribution/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 50 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/gov/keeper/msg_server_test.go b/x/gov/keeper/msg_server_test.go index 599b559cd134..b67943e0f764 100644 --- a/x/gov/keeper/msg_server_test.go +++ b/x/gov/keeper/msg_server_test.go @@ -962,7 +962,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { name: "invalid quorum", input: func() *v1.MsgUpdateParams { params1 := params - params1.Quorum = "abc" //nolint:goconst + params1.Quorum = "abc" return &v1.MsgUpdateParams{ Authority: authority, diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 4ea36900e787..caf21dbc346b 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -30,7 +30,7 @@ var ( // Simulation operation weights constants // -//nolint:gosec // these are not hard-coded credentials. + const ( OpWeightMsgDeposit = "op_weight_msg_deposit" OpWeightMsgVote = "op_weight_msg_vote" diff --git a/x/group/internal/orm/index_property_test.go b/x/group/internal/orm/index_property_test.go index 4c42bceb2f82..c6d90efd088b 100644 --- a/x/group/internal/orm/index_property_test.go +++ b/x/group/internal/orm/index_property_test.go @@ -46,7 +46,7 @@ func TestPrefixRangeProperty(t *testing.T) { // index, one greater at overflow and 0 from // then on for i, b := range start { - if i < overflowIndex { //nolint:gocritic // ifElseChain: rewrite if-else to switch statement + if i < overflowIndex { require.Equal(t, b, end[i]) } else if i == overflowIndex { require.Equal(t, b+1, end[i]) diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index 9b19fd692f46..34592cec8c64 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -42,7 +42,7 @@ var ( // Simulation operation weights constants // -//nolint:gosec // these are not hardcoded credentials. + const ( OpMsgCreateGroup = "op_weight_msg_create_group" OpMsgUpdateGroupAdmin = "op_weight_msg_update_group_admin" diff --git a/x/mint/simulation/proposals.go b/x/mint/simulation/proposals.go index 129658adcf22..0ecf4a5591d1 100644 --- a/x/mint/simulation/proposals.go +++ b/x/mint/simulation/proposals.go @@ -14,7 +14,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/params/simulation/proposals.go b/x/params/simulation/proposals.go index 30b8f8434794..9f49b9102421 100644 --- a/x/params/simulation/proposals.go +++ b/x/params/simulation/proposals.go @@ -12,8 +12,6 @@ const ( ) // ProposalContents defines the module weighted proposals' contents -// -//nolint:staticcheck func ProposalContents(paramChanges []simtypes.LegacyParamChange) []simtypes.WeightedProposalContent { return []simtypes.WeightedProposalContent{ simulation.NewWeightedProposalContent( diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index ac2b4951f456..bb8c84477cb4 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -154,7 +154,7 @@ func (suite *SubspaceTestSuite) TestModified() { func (suite *SubspaceTestSuite) TestUpdate() { suite.Require().Panics(func() { - suite.ss.Update(suite.ctx, []byte("invalid_key"), nil) //nolint:errcheck + suite.ss.Update(suite.ctx, []byte("invalid_key"), nil) }) t := time.Hour * 48 diff --git a/x/simulation/mock_cometbft.go b/x/simulation/mock_cometbft.go index 166cf40a87d7..7e72a1ae8d91 100644 --- a/x/simulation/mock_cometbft.go +++ b/x/simulation/mock_cometbft.go @@ -69,7 +69,7 @@ func (vals mockValidators) randomProposer(r *rand.Rand) []byte { proposer := vals[key].val pk, err := cryptoenc.PubKeyFromProto(proposer.PubKey) - if err != nil { //nolint:wsl + if err != nil { panic(err) } diff --git a/x/simulation/params.go b/x/simulation/params.go index 4ac7fac95099..7837fc294f3e 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -149,8 +149,6 @@ func (w WeightedProposalMsg) MsgSimulatorFn() simulation.MsgSimulatorFn { // Legacy Proposal Content // WeightedProposalContent defines a common struct for proposal content defined by external modules (i.e outside gov) -// -//nolint:staticcheck type WeightedProposalContent struct { appParamsKey string // key used to retrieve the value of the weight from the simulation application params defaultWeight int // default weight @@ -169,7 +167,7 @@ func (w WeightedProposalContent) DefaultWeight() int { return w.defaultWeight } -func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { //nolint:staticcheck +func (w WeightedProposalContent) ContentSimulatorFn() simulation.ContentSimulatorFn { return w.contentSimulatorFn } diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go index 496454142c45..9660d8ce2779 100644 --- a/x/simulation/params_test.go +++ b/x/simulation/params_test.go @@ -30,7 +30,7 @@ func TestNewWeightedProposalContent(t *testing.T) { key := "theKey" weight := 1 content := &testContent{} - f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { //nolint:staticcheck + f := func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { return content } diff --git a/x/slashing/module.go b/x/slashing/module.go index 7374e27ab075..1ce67f1825e1 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -212,8 +212,7 @@ func init() { ) } -//nolint:revive -type SlashingInputs struct { +type SlashingInputs struct { //nolint:revive // ignore struct name linting depinject.In Config *modulev1.Module @@ -229,8 +228,7 @@ type SlashingInputs struct { LegacySubspace exported.Subspace } -//nolint:revive -type SlashingOutputs struct { +type SlashingOutputs struct { //nolint:revive // ignore struct name linting depinject.Out Keeper keeper.Keeper diff --git a/x/slashing/simulation/proposals.go b/x/slashing/simulation/proposals.go index 6c17b9c44a0a..86b5d5a532d8 100644 --- a/x/slashing/simulation/proposals.go +++ b/x/slashing/simulation/proposals.go @@ -15,7 +15,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index 416e9b3077f9..db8dc4c489d0 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -18,8 +18,6 @@ var ( ) // NewMsgUnjail creates a new MsgUnjail instance -// -//nolint:interfacer func NewMsgUnjail(validatorAddr sdk.ValAddress) *MsgUnjail { return &MsgUnjail{ ValidatorAddr: validatorAddr.String(), diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go index 27ed54e0b819..8e9519d51dec 100644 --- a/x/slashing/types/signing_info.go +++ b/x/slashing/types/signing_info.go @@ -8,8 +8,6 @@ import ( ) // NewValidatorSigningInfo creates a new ValidatorSigningInfo instance -// -//nolint:interfacer func NewValidatorSigningInfo( consAddr sdk.ConsAddress, startHeight, indexOffset int64, jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 5093688b5bb9..acea5c37871b 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -57,7 +57,7 @@ func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegati // GetValidatorDelegations returns all delegations to a specific validator. // Useful for querier. -func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { //nolint:interfacer +func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { store := ctx.KVStore(k.storeKey) iterator := storetypes.KVStorePrefixIterator(store, types.DelegationKey) diff --git a/x/staking/module.go b/x/staking/module.go index 9674998406dd..36d102b7df20 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -205,8 +205,7 @@ func init() { ) } -//nolint:revive -type StakingInputs struct { +type StakingInputs struct { //nolint:revive // ignore struct name linting depinject.In Config *modulev1.Module @@ -220,9 +219,7 @@ type StakingInputs struct { } // Dependency Injection Outputs -// -//nolint:revive -type StakingOutputs struct { +type StakingOutputs struct { //nolint:revive // ignore struct name linting depinject.Out StakingKeeper *keeper.Keeper diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 18794553b037..ecfb01f2feb0 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -18,7 +18,7 @@ import ( // Simulation operation weights constants // -//nolint:gosec // these are not hardcoded credentials + const ( DefaultWeightMsgCreateValidator int = 100 DefaultWeightMsgEditValidator int = 5 diff --git a/x/staking/simulation/proposals.go b/x/staking/simulation/proposals.go index 6b1f43128247..5ef5fc7a13bc 100644 --- a/x/staking/simulation/proposals.go +++ b/x/staking/simulation/proposals.go @@ -15,7 +15,7 @@ import ( const ( DefaultWeightMsgUpdateParams int = 100 - OpWeightMsgUpdateParams = "op_weight_msg_update_params" //nolint:gosec + OpWeightMsgUpdateParams = "op_weight_msg_update_params" ) // ProposalMsgs defines the module weighted proposals' contents diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index f993d9dc28e8..3fd63b261648 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -14,8 +14,6 @@ import ( var _ DelegationI = Delegation{} // NewDelegation creates a new delegation object -// -//nolint:interfacer func NewDelegation(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, shares sdk.Dec) Delegation { return Delegation{ DelegatorAddress: delegatorAddr.String(), @@ -115,8 +113,6 @@ func UnmarshalUBDE(cdc codec.BinaryCodec, value []byte) (ubd UnbondingDelegation } // NewUnbondingDelegation - create a new unbonding delegation object -// -//nolint:interfacer func NewUnbondingDelegation( delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance math.Int, id uint64, @@ -213,7 +209,6 @@ func (e RedelegationEntry) OnHold() bool { return e.UnbondingOnHoldRefCount > 0 } -//nolint:interfacer func NewRedelegation( delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance math.Int, sharesDst sdk.Dec, id uint64, @@ -311,8 +306,6 @@ func (d DelegationResponses) String() (out string) { } // NewRedelegationResponse crates a new RedelegationEntryResponse instance. -// -//nolint:interfacer func NewRedelegationResponse( delegatorAddr sdk.AccAddress, validatorSrc, validatorDst sdk.ValAddress, entries []RedelegationEntryResponse, ) RedelegationResponse { diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 1cd7767266aa..5a8a765020e3 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -33,7 +33,7 @@ var ( // NewMsgCreateValidator creates a new MsgCreateValidator instance. // Delegator address and validator address are the same. func NewMsgCreateValidator( - valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, //nolint:interfacer + valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation math.Int, ) (*MsgCreateValidator, error) { var pkAny *codectypes.Any @@ -120,8 +120,6 @@ func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) } // NewMsgEditValidator creates a new MsgEditValidator instance -// -//nolint:interfacer func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *math.Int) *MsgEditValidator { return &MsgEditValidator{ Description: description, @@ -170,8 +168,6 @@ func (msg MsgEditValidator) ValidateBasic() error { } // NewMsgDelegate creates a new MsgDelegate instance. -// -//nolint:interfacer func NewMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgDelegate { return &MsgDelegate{ DelegatorAddress: delAddr.String(), @@ -212,8 +208,6 @@ func (msg MsgDelegate) ValidateBasic() error { } // NewMsgBeginRedelegate creates a new MsgBeginRedelegate instance. -// -//nolint:interfacer func NewMsgBeginRedelegate( delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, amount sdk.Coin, ) *MsgBeginRedelegate { @@ -260,8 +254,6 @@ func (msg MsgBeginRedelegate) ValidateBasic() error { } // NewMsgUndelegate creates a new MsgUndelegate instance. -// -//nolint:interfacer func NewMsgUndelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgUndelegate { return &MsgUndelegate{ DelegatorAddress: delAddr.String(), @@ -302,8 +294,6 @@ func (msg MsgUndelegate) ValidateBasic() error { } // NewMsgCancelUnbondingDelegation creates a new MsgCancelUnbondingDelegation instance. -// -//nolint:interfacer func NewMsgCancelUnbondingDelegation(delAddr sdk.AccAddress, valAddr sdk.ValAddress, creationHeight int64, amount sdk.Coin) *MsgCancelUnbondingDelegation { return &MsgCancelUnbondingDelegation{ DelegatorAddress: delAddr.String(), diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index c763998dc7d1..1b55f7120cf2 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -39,8 +39,6 @@ var ( var _ ValidatorI = Validator{} // NewValidator constructs a new Validator -// -//nolint:interfacer func NewValidator(operator sdk.ValAddress, pubKey cryptotypes.PubKey, description Description) (Validator, error) { pkAny, err := codectypes.NewAnyWithValue(pubKey) if err != nil {