From e2d630c620b531b080eed43c055dfebe0945952e Mon Sep 17 00:00:00 2001 From: Fs02 Date: Sun, 9 Oct 2022 17:36:06 +0900 Subject: [PATCH 1/9] replace empty interface with any --- adapter.go | 6 +-- adapter_test.go | 12 +++--- any_nogo1.18.go | 6 +++ association.go | 4 +- association_test.go | 12 +++--- changeset.go | 38 +++++++++---------- changeset_test.go | 44 +++++++++++----------- collection.go | 16 ++++---- collection_test.go | 26 ++++++------- column.go | 2 +- convert.go | 12 +++--- convert_test.go | 36 +++++++++--------- cursor.go | 8 ++-- cursor_test.go | 24 ++++++------ document.go | 22 +++++------ document_meta.go | 2 +- document_test.go | 18 ++++----- filter_query.go | 80 ++++++++++++++++++++-------------------- filter_query_test.go | 30 +++++++-------- go.mod | 13 +++++-- go.sum | 5 --- iterator.go | 20 +++++----- join_query.go | 6 +-- join_query_test.go | 4 +- map.go | 12 +++--- map_test.go | 6 +-- mutation.go | 12 +++--- nullable.go | 6 +-- nullable_test.go | 2 +- on_conflict.go | 4 +- on_conflict_test.go | 2 +- query.go | 12 +++--- query_test.go | 4 +- rel_test.go | 2 +- repository.go | 88 ++++++++++++++++++++++---------------------- repository_test.go | 50 ++++++++++++------------- schema_options.go | 4 +- sql_query.go | 4 +- sql_query_test.go | 2 +- structset.go | 4 +- util.go | 11 +++--- util_test.go | 2 +- 42 files changed, 341 insertions(+), 332 deletions(-) create mode 100644 any_nogo1.18.go diff --git a/adapter.go b/adapter.go index 8ec8d389..998dff9e 100644 --- a/adapter.go +++ b/adapter.go @@ -12,11 +12,11 @@ type Adapter interface { Ping(ctx context.Context) error Aggregate(ctx context.Context, query Query, mode string, field string) (int, error) Query(ctx context.Context, query Query) (Cursor, error) - Insert(ctx context.Context, query Query, primaryField string, mutates map[string]Mutate, onConflict OnConflict) (interface{}, error) - InsertAll(ctx context.Context, query Query, primaryField string, fields []string, bulkMutates []map[string]Mutate, onConflict OnConflict) ([]interface{}, error) + Insert(ctx context.Context, query Query, primaryField string, mutates map[string]Mutate, onConflict OnConflict) (any, error) + InsertAll(ctx context.Context, query Query, primaryField string, fields []string, bulkMutates []map[string]Mutate, onConflict OnConflict) ([]any, error) Update(ctx context.Context, query Query, primaryField string, mutates map[string]Mutate) (int, error) Delete(ctx context.Context, query Query) (int, error) - Exec(ctx context.Context, stmt string, args []interface{}) (int64, int64, error) + Exec(ctx context.Context, stmt string, args []any) (int64, int64, error) Begin(ctx context.Context) (Adapter, error) Commit(ctx context.Context) error diff --git a/adapter_test.go b/adapter_test.go index 41de9e1d..2bc2ef92 100644 --- a/adapter_test.go +++ b/adapter_test.go @@ -8,7 +8,7 @@ import ( type testAdapter struct { mock.Mock - result interface{} + result any } var _ Adapter = (*testAdapter)(nil) @@ -41,14 +41,14 @@ func (ta *testAdapter) Query(ctx context.Context, query Query) (Cursor, error) { return args.Get(0).(Cursor), args.Error(1) } -func (ta *testAdapter) Insert(ctx context.Context, query Query, primaryField string, mutates map[string]Mutate, onConflict OnConflict) (interface{}, error) { +func (ta *testAdapter) Insert(ctx context.Context, query Query, primaryField string, mutates map[string]Mutate, onConflict OnConflict) (any, error) { args := ta.Called(query, mutates, onConflict) return args.Get(0), args.Error(1) } -func (ta *testAdapter) InsertAll(ctx context.Context, query Query, primaryField string, fields []string, mutates []map[string]Mutate, onConflict OnConflict) ([]interface{}, error) { +func (ta *testAdapter) InsertAll(ctx context.Context, query Query, primaryField string, fields []string, mutates []map[string]Mutate, onConflict OnConflict) ([]any, error) { args := ta.Called(query, fields, mutates, onConflict) - return args.Get(0).([]interface{}), args.Error(1) + return args.Get(0).([]any), args.Error(1) } func (ta *testAdapter) Update(ctx context.Context, query Query, primaryField string, mutates map[string]Mutate) (int, error) { @@ -81,12 +81,12 @@ func (ta *testAdapter) Apply(ctx context.Context, migration Migration) error { return args.Error(0) } -func (ta *testAdapter) Result(result interface{}) *testAdapter { +func (ta *testAdapter) Result(result any) *testAdapter { ta.result = result return ta } -func (ta *testAdapter) Exec(ctx context.Context, stmt string, args []interface{}) (int64, int64, error) { +func (ta *testAdapter) Exec(ctx context.Context, stmt string, args []any) (int64, int64, error) { mockArgs := ta.Called(ctx, stmt, args) return int64(mockArgs.Int(0)), int64(mockArgs.Int(1)), mockArgs.Error(2) } diff --git a/any_nogo1.18.go b/any_nogo1.18.go new file mode 100644 index 00000000..ad0496a8 --- /dev/null +++ b/any_nogo1.18.go @@ -0,0 +1,6 @@ +//go:build !go1.18 +// +build !go1.18 + +package rel + +type any = interface{} diff --git a/association.go b/association.go index 13ff9f8a..17450d5e 100644 --- a/association.go +++ b/association.go @@ -96,7 +96,7 @@ func (a Association) ReferenceField() string { } // ReferenceValue of the association. -func (a Association) ReferenceValue() interface{} { +func (a Association) ReferenceValue() any { return indirectInterface(reflectValueFieldByIndex(a.rv, a.meta.referenceIndex, false)) } @@ -107,7 +107,7 @@ func (a Association) ForeignField() string { // ForeignValue of the association. // It'll panic if association type is has many. -func (a Association) ForeignValue() interface{} { +func (a Association) ForeignValue() any { if a.Type() == HasMany { panic("rel: cannot infer foreign value for has many or many to many association") } diff --git a/association_test.go b/association_test.go index 708af4c6..8f4bc15c 100644 --- a/association_test.go +++ b/association_test.go @@ -20,15 +20,15 @@ func TestAssociation_Document(t *testing.T) { tests := []struct { record string field string - data interface{} + data any typ AssociationType doc *Document loaded bool isZero bool referenceField string - referenceValue interface{} + referenceValue any foreignField string - foreignValue interface{} + foreignValue any autosave bool autoload bool }{ @@ -199,16 +199,16 @@ func TestAssociation_Collection(t *testing.T) { tests := []struct { record string field string - data interface{} + data any typ AssociationType col *Collection loaded bool isZero bool referenceField string - referenceValue interface{} + referenceValue any referenceThrough string foreignField string - foreignValue interface{} + foreignValue any foreignThrough string through string autoload bool diff --git a/changeset.go b/changeset.go index 5505cf26..2a474a40 100644 --- a/changeset.go +++ b/changeset.go @@ -6,20 +6,20 @@ import ( "time" ) -type pair = [2]interface{} +type pair = [2]any // Changeset mutator for structs. // This allows REL to efficiently to perform update operation only on updated fields and association. // The catch is, enabling changeset will duplicates the original struct values which consumes more memory. type Changeset struct { doc *Document - snapshot []interface{} + snapshot []any assoc map[string]Changeset - assocMany map[string]map[interface{}]Changeset + assocMany map[string]map[any]Changeset } -func (c Changeset) valueChanged(typ reflect.Type, old interface{}, new interface{}) bool { - if oeq, ok := old.(interface{ Equal(interface{}) bool }); ok { +func (c Changeset) valueChanged(typ reflect.Type, old any, new any) bool { + if oeq, ok := old.(interface{ Equal(any) bool }); ok { return !oeq.Equal(new) } @@ -53,7 +53,7 @@ func (c Changeset) FieldChanged(field string) bool { } // Changes returns map of changes. -func (c Changeset) Changes() map[string]interface{} { +func (c Changeset) Changes() map[string]any { return buildChanges(c.doc, c) } @@ -118,8 +118,8 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) { assoc = c.doc.Association(field) col, _ = assoc.Collection() muts = make([]Mutation, 0, col.Len()) - updatedIDs = make(map[interface{}]struct{}) - deletedIDs []interface{} + updatedIDs = make(map[any]struct{}) + deletedIDs []any ) for i := 0; i < col.Len(); i++ { @@ -158,16 +158,16 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) { } // NewChangeset returns new changeset mutator for given record. -func NewChangeset(record interface{}) Changeset { +func NewChangeset(record any) Changeset { return newChangeset(NewDocument(record)) } func newChangeset(doc *Document) Changeset { c := Changeset{ doc: doc, - snapshot: make([]interface{}, len(doc.Fields())), + snapshot: make([]any, len(doc.Fields())), assoc: make(map[string]Changeset), - assocMany: make(map[string]map[interface{}]Changeset), + assocMany: make(map[string]map[any]Changeset), } for i, field := range doc.Fields() { @@ -198,13 +198,13 @@ func initChangesetAssoc(doc *Document, assoc map[string]Changeset, field string) assoc[field] = newChangeset(doc) } -func initChangesetAssocMany(doc *Document, assoc map[string]map[interface{}]Changeset, field string) { +func initChangesetAssocMany(doc *Document, assoc map[string]map[any]Changeset, field string) { col, loaded := doc.Association(field).Collection() if !loaded { return } - assoc[field] = make(map[interface{}]Changeset) + assoc[field] = make(map[any]Changeset) for i := 0; i < col.Len(); i++ { var ( @@ -218,9 +218,9 @@ func initChangesetAssocMany(doc *Document, assoc map[string]map[interface{}]Chan } } -func buildChanges(doc *Document, c Changeset) map[string]interface{} { +func buildChanges(doc *Document, c Changeset) map[string]any { var ( - changes = make(map[string]interface{}) + changes = make(map[string]any) fields []string ) @@ -268,7 +268,7 @@ func buildChanges(doc *Document, c Changeset) map[string]interface{} { return changes } -func buildChangesAssoc(out map[string]interface{}, c Changeset, field string) { +func buildChangesAssoc(out map[string]any, c Changeset, field string) { assoc := c.doc.Association(field) if assoc.IsZero() { return @@ -280,13 +280,13 @@ func buildChangesAssoc(out map[string]interface{}, c Changeset, field string) { } } -func buildChangesAssocMany(out map[string]interface{}, c Changeset, field string) { +func buildChangesAssocMany(out map[string]any, c Changeset, field string) { var ( - changes []map[string]interface{} + changes []map[string]any chs = c.assocMany[field] assoc = c.doc.Association(field) col, _ = assoc.Collection() - updatedIDs = make(map[interface{}]struct{}) + updatedIDs = make(map[any]struct{}) ) for i := 0; i < col.Len(); i++ { diff --git a/changeset_test.go b/changeset_test.go index 34dda865..a4fd565b 100644 --- a/changeset_test.go +++ b/changeset_test.go @@ -12,7 +12,7 @@ func BenchmarkSmallSliceLookup(b *testing.B) { for n := 0; n < b.N; n++ { var ( index = 0 - values = []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + values = []any{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} fields = []string{"field1", "field2", "field3", "field4", "field6", "field7", "field8", "field9", "field10"} ) @@ -31,7 +31,7 @@ func BenchmarkSmallSliceLookup(b *testing.B) { func BenchmarkSmallMapLookup(b *testing.B) { for n := 0; n < b.N; n++ { var ( - values = map[string]interface{}{ + values = map[string]any{ "field1": 1, "field2": 2, "field3": 3, @@ -115,7 +115,7 @@ func TestChangeset(t *testing.T) { UpdatedAt: ts, CreatedAt: ts, } - snapshot = []interface{}{1, "User 1", 20, ts, ts} + snapshot = []any{1, "User 1", 20, ts, ts} doc = NewDocument(&user) changeset = NewChangeset(&user) ) @@ -136,7 +136,7 @@ func TestChangeset(t *testing.T) { user.Age = 21 assert.Equal(t, snapshot, changeset.snapshot) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "name": pair{"User 1", "User 2"}, "age": pair{20, 21}, }, changeset.Changes()) @@ -171,7 +171,7 @@ func TestChangeset_byte_slice(t *testing.T) { CreatedAt: ts, UpdatedAt: ts, } - snapshot = []interface{}{1, []byte("foo"), json.RawMessage(`{"baz":"foo"}`), ts, ts} + snapshot = []any{1, []byte("foo"), json.RawMessage(`{"baz":"foo"}`), ts, ts} doc = NewDocument(&user) changeset = NewChangeset(&user) ) @@ -192,7 +192,7 @@ func TestChangeset_byte_slice(t *testing.T) { user.Metadata = []byte("{}") assert.Equal(t, snapshot, changeset.snapshot) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "password": pair{[]byte("foo"), []byte("bar")}, "metadata": pair{json.RawMessage(`{"baz":"foo"}`), json.RawMessage("{}")}, }, changeset.Changes()) @@ -223,7 +223,7 @@ func TestChangeset_ptr(t *testing.T) { ID: 1, UserID: &userID, } - snapshot = []interface{}{1, 2, "", Notes(""), nil} + snapshot = []any{1, 2, "", Notes(""), nil} doc = NewDocument(&address) changeset = NewChangeset(&address) ) @@ -244,7 +244,7 @@ func TestChangeset_ptr(t *testing.T) { address.UserID = &userID assert.Equal(t, snapshot, changeset.snapshot) - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "user_id": pair{2, 3}, }, changeset.Changes()) }) @@ -267,7 +267,7 @@ func TestChangeset_belongsTo(t *testing.T) { Name: "User 1", }, } - snapshot = []interface{}{1, "User 1", 0, time.Time{}, time.Time{}} + snapshot = []any{1, "User 1", 0, time.Time{}, time.Time{}} doc = NewDocument(&address) changeset = NewChangeset(&address) ) @@ -287,8 +287,8 @@ func TestChangeset_belongsTo(t *testing.T) { address.User.Name = "User Satu" assert.Equal(t, snapshot, changeset.assoc["user"].snapshot) - assert.Equal(t, map[string]interface{}{ - "user": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "user": map[string]any{ "name": pair{"User 1", "User Satu"}, }, }, changeset.Changes()) @@ -341,8 +341,8 @@ func TestChangeset_belongsTo_new(t *testing.T) { } assert.Nil(t, changeset.assoc["user"].snapshot) - assert.Equal(t, map[string]interface{}{ - "user": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "user": map[string]any{ "id": pair{nil, 0}, "name": pair{nil, "User Satu"}, "age": pair{nil, 20}, @@ -384,7 +384,7 @@ func TestChangeset_hasOne(t *testing.T) { Notes: "HQ", }, } - snapshot = []interface{}{1, nil, "Grove Street", Notes("HQ"), nil} + snapshot = []any{1, nil, "Grove Street", Notes("HQ"), nil} doc = NewDocument(&user) changeset = NewChangeset(&user) ) @@ -406,8 +406,8 @@ func TestChangeset_hasOne(t *testing.T) { user.Address.Notes = Notes("Home") assert.Equal(t, snapshot, changeset.assoc["address"].snapshot) - assert.Equal(t, map[string]interface{}{ - "address": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "address": map[string]any{ "user_id": pair{nil, user.ID}, "street": pair{"Grove Street", "Grove Street Blvd"}, "notes": pair{Notes("HQ"), Notes("Home")}, @@ -464,8 +464,8 @@ func TestChangeset_hasOne_new(t *testing.T) { } assert.Nil(t, changeset.assoc["address"].snapshot) - assert.Equal(t, map[string]interface{}{ - "address": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "address": map[string]any{ "id": pair{nil, 0}, "user_id": pair{nil, user.ID}, "street": pair{nil, "Grove Street Blvd"}, @@ -505,7 +505,7 @@ func TestChangeset_hasMany(t *testing.T) { {ID: 12, Item: "Eraser", Status: "pending"}, }, } - snapshots = [][]interface{}{ + snapshots = [][]any{ {11, "Book", Status("pending"), 0, 0}, {12, "Eraser", Status("pending"), 0, 0}, } @@ -532,8 +532,8 @@ func TestChangeset_hasMany(t *testing.T) { user.Transactions[0].Status = "paid" user.Transactions[1] = Transaction{Item: "Paper", Status: "pending"} - assert.Equal(t, map[string]interface{}{ - "transactions": []map[string]interface{}{ + assert.Equal(t, map[string]any{ + "transactions": []map[string]any{ { "status": pair{Status("pending"), Status("paid")}, }, @@ -577,7 +577,7 @@ func TestChangeset_hasMany(t *testing.T) { }, }, }, - DeletedIDs: []interface{}{12}, + DeletedIDs: []any{12}, }, }, }, Apply(doc, changeset)) diff --git a/collection.go b/collection.go index 64ff5985..8f545bde 100644 --- a/collection.go +++ b/collection.go @@ -15,7 +15,7 @@ type slice interface { // Collection provides an abstraction over reflect to easily works with slice for database purpose. type Collection struct { - v interface{} + v any rv reflect.Value rt reflect.Type meta DocumentMeta @@ -57,21 +57,21 @@ func (c Collection) PrimaryField() string { // PrimaryValues of collection. // Returned value will be interface of slice interface. -func (c Collection) PrimaryValues() []interface{} { +func (c Collection) PrimaryValues() []any { if p, ok := c.v.(primary); ok { return p.PrimaryValues() } var ( index = c.meta.primaryIndex - pValues = make([]interface{}, len(c.PrimaryFields())) + pValues = make([]any, len(c.PrimaryFields())) ) if index != nil { for i := range index { var ( idxLen = c.rv.Len() - values = make([]interface{}, 0, idxLen) + values = make([]any, 0, idxLen) ) for j := 0; j < idxLen; j++ { @@ -85,7 +85,7 @@ func (c Collection) PrimaryValues() []interface{} { } else { // using interface. var ( - tmp = make([][]interface{}, len(pValues)) + tmp = make([][]any, len(pValues)) ) for i := 0; i < c.rv.Len(); i++ { @@ -108,7 +108,7 @@ func (c Collection) PrimaryValues() []interface{} { // PrimaryValue of this document. // panic if document uses composite key. -func (c Collection) PrimaryValue() interface{} { +func (c Collection) PrimaryValue() any { if values := c.PrimaryValues(); len(values) == 1 { return values[0] } @@ -178,7 +178,7 @@ func (c Collection) Swap(i, j int) { // NewCollection used to create abstraction to work with slice. // COllection can be created using interface or reflect.Value. -func NewCollection(records interface{}, readonly ...bool) *Collection { +func NewCollection(records any, readonly ...bool) *Collection { switch v := records.(type) { case *Collection: return v @@ -193,7 +193,7 @@ func NewCollection(records interface{}, readonly ...bool) *Collection { } } -func newCollection(v interface{}, rv reflect.Value, readonly bool) *Collection { +func newCollection(v any, rv reflect.Value, readonly bool) *Collection { var ( rt = rv.Type() ) diff --git a/collection_test.go b/collection_test.go index 79054fd9..f64aab02 100644 --- a/collection_test.go +++ b/collection_test.go @@ -18,16 +18,16 @@ func (it *Items) PrimaryFields() []string { return []string{"_uuid"} } -func (it *Items) PrimaryValues() []interface{} { +func (it *Items) PrimaryValues() []any { var ( - ids = make([]interface{}, len(*it)) + ids = make([]any, len(*it)) ) for i := range *it { ids[i] = (*it)[i].UUID } - return []interface{}{ids} + return []any{ids} } func TestCollection_ReflectValue(t *testing.T) { @@ -81,7 +81,7 @@ func TestCollection_Primary(t *testing.T) { // infer primary key assert.Equal(t, "id", col.PrimaryField()) - assert.Equal(t, []interface{}{1, 2}, col.PrimaryValue()) + assert.Equal(t, []any{1, 2}, col.PrimaryValue()) // cached _, cached := primariesCache.Load(rt) @@ -91,7 +91,7 @@ func TestCollection_Primary(t *testing.T) { // infer primary key using cache assert.Equal(t, "id", col.PrimaryField()) - assert.Equal(t, []interface{}{1, 4}, col.PrimaryValue()) + assert.Equal(t, []any{1, 4}, col.PrimaryValue()) primariesCache.Delete(rt) } @@ -107,7 +107,7 @@ func TestCollection_Primary_usingInterface(t *testing.T) { // infer primary key assert.Equal(t, "_uuid", col.PrimaryField()) - assert.Equal(t, []interface{}{"abc123", "def456"}, col.PrimaryValue()) + assert.Equal(t, []any{"abc123", "def456"}, col.PrimaryValue()) } func TestCollection_Primary_usingElemInterface(t *testing.T) { @@ -122,7 +122,7 @@ func TestCollection_Primary_usingElemInterface(t *testing.T) { // infer primary key assert.Equal(t, "_uuid", col.PrimaryField()) - assert.Equal(t, []interface{}{"abc123", "def456"}, col.PrimaryValue()) + assert.Equal(t, []any{"abc123", "def456"}, col.PrimaryValue()) primariesCache.Delete(rt) } @@ -140,7 +140,7 @@ func TestCollection_Primary_usingElemInterface_ptrElem(t *testing.T) { // infer primary key assert.Equal(t, "_uuid", col.PrimaryField()) - assert.Equal(t, []interface{}{"abc123", "def456"}, col.PrimaryValue()) + assert.Equal(t, []any{"abc123", "def456"}, col.PrimaryValue()) primariesCache.Delete(rt) } @@ -160,7 +160,7 @@ func TestCollection_Primary_usingTag(t *testing.T) { // infer primary key assert.Equal(t, "external_id", col.PrimaryField()) - assert.Equal(t, []interface{}{1, 2}, col.PrimaryValue()) + assert.Equal(t, []any{1, 2}, col.PrimaryValue()) } func TestCollection_Primary_composite(t *testing.T) { @@ -182,9 +182,9 @@ func TestCollection_Primary_composite(t *testing.T) { }) assert.Equal(t, []string{"user_id", "role_id"}, col.PrimaryFields()) - assert.Equal(t, []interface{}{ - []interface{}{1, 3, 5}, - []interface{}{2, 4, 6}, + assert.Equal(t, []any{ + []any{1, 3, 5}, + []any{2, 4, 6}, }, col.PrimaryValues()) } @@ -258,7 +258,7 @@ func TestCollection_Slice(t *testing.T) { func TestCollection(t *testing.T) { tests := []struct { - record interface{} + record any panics bool }{ { diff --git a/column.go b/column.go index 5a1dc021..b21d0fec 100644 --- a/column.go +++ b/column.go @@ -47,7 +47,7 @@ type Column struct { Limit int Precision int Scale int - Default interface{} + Default any Options string } diff --git a/convert.go b/convert.go index 5882f0ab..45038277 100644 --- a/convert.go +++ b/convert.go @@ -20,7 +20,7 @@ var _, localTimeOffset = time.Now().Local().Zone() // dest should be a pointer type. // dest will be set to zero value if src is nil. // this function assumes dest will never be nil. -func convertAssign(dest, src interface{}) error { +func convertAssign(dest, src any) error { // Common cases, without reflect. switch s := src.(type) { case string: @@ -40,7 +40,7 @@ func convertAssign(dest, src interface{}) error { case *string: *d = string(s) return nil - case *interface{}: + case *any: *d = cloneBytes(s) return nil case *[]byte: @@ -108,7 +108,7 @@ func convertAssign(dest, src interface{}) error { *d = bv.(bool) } return err - case *interface{}: + case *any: *d = src return nil } @@ -190,7 +190,7 @@ func cloneBytes(b []byte) []byte { return c } -func asString(src interface{}) (string, bool) { +func asString(src any) (string, bool) { switch v := src.(type) { case string: return v, true @@ -232,7 +232,7 @@ func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) { return } -func assignZero(dest interface{}) { +func assignZero(dest any) { switch d := dest.(type) { case *bool: *d = false @@ -264,7 +264,7 @@ func assignZero(dest interface{}) { *d = 0 case *float64: *d = 0 - case *interface{}: + case *any: *d = nil case *[]byte: *d = nil diff --git a/convert_test.go b/convert_test.go index e8564115..19190a37 100644 --- a/convert_test.go +++ b/convert_test.go @@ -23,7 +23,7 @@ type ( ) type conversionTest struct { - s, d interface{} // source and destination + s, d any // source and destination // following are used if they're non-zero wantint int64 @@ -36,7 +36,7 @@ type conversionTest struct { wanttime time.Time wantbool bool // used if d is of type *bool wanterr string - wantiface interface{} + wantiface any wantptr *int64 // if non-nil, *d's pointed value must be equal to *wantptr wantnil bool // if true, *d must be *int64(nil) wantusrdef userDefined @@ -59,7 +59,7 @@ var ( scanf64 float64 scantime time.Time scanptr *int64 - scaniface interface{} + scaniface any ) func conversionTests() []conversionTest { @@ -170,10 +170,10 @@ func conversionTests() []conversionTest { {s: "foo", d: &scanf64, wanterr: "converting driver.Value type string (\"foo\") to a float64: invalid syntax"}, // Pointers - {s: interface{}(nil), d: &scanptr, wantnil: true}, + {s: any(nil), d: &scanptr, wantnil: true}, {s: int64(42), d: &scanptr, wantptr: &answer}, - // To interface{} + // To any {s: float64(1.5), d: &scaniface, wantiface: float64(1.5)}, {s: int64(1), d: &scaniface, wantiface: int64(1)}, {s: "str", d: &scaniface, wantiface: "str"}, @@ -196,27 +196,27 @@ func conversionTests() []conversionTest { } } -func intPtrValue(intptr interface{}) interface{} { +func intPtrValue(intptr any) any { return reflect.Indirect(reflect.Indirect(reflect.ValueOf(intptr))).Int() } -func intValue(intptr interface{}) int64 { +func intValue(intptr any) int64 { return reflect.Indirect(reflect.ValueOf(intptr)).Int() } -func uintValue(intptr interface{}) uint64 { +func uintValue(intptr any) uint64 { return reflect.Indirect(reflect.ValueOf(intptr)).Uint() } -func float64Value(ptr interface{}) float64 { +func float64Value(ptr any) float64 { return *(ptr.(*float64)) } -func float32Value(ptr interface{}) float32 { +func float32Value(ptr any) float32 { return *(ptr.(*float32)) } -func timeValue(ptr interface{}) time.Time { +func timeValue(ptr any) time.Time { return *(ptr.(*time.Time)) } @@ -227,7 +227,7 @@ func TestConversions(t *testing.T) { if err != nil { errstr = err.Error() } - errf := func(format string, args ...interface{}) { + errf := func(format string, args ...any) { base := fmt.Sprintf("convertAssign #%d: for %v (%T) -> %T, ", n, ct.s, ct.s, ct.d) t.Errorf(base+format, args...) } @@ -271,7 +271,7 @@ func TestConversions(t *testing.T) { errf("want pointer to %v, got %v", *ct.wantptr, intPtrValue(ct.d)) } } - if ifptr, ok := ct.d.(*interface{}); ok { + if ifptr, ok := ct.d.(*any); ok { if !reflect.DeepEqual(ct.wantiface, scaniface) { errf("want interface %#v, got %#v", ct.wantiface, scaniface) continue @@ -279,7 +279,7 @@ func TestConversions(t *testing.T) { if srcBytes, ok := ct.s.([]byte); ok { dstBytes := (*ifptr).([]byte) if len(srcBytes) > 0 && &dstBytes[0] == &srcBytes[0] { - errf("copy into interface{} didn't copy []byte data") + errf("copy into any didn't copy []byte data") } } } @@ -296,7 +296,7 @@ func TestConversions(t *testing.T) { func TestRawBytesAllocs(t *testing.T) { var tests = []struct { name string - in interface{} + in any want string }{ {"uint64", uint64(12345678), "12345678"}, @@ -316,7 +316,7 @@ func TestRawBytesAllocs(t *testing.T) { } buf := make(sql.RawBytes, 10) - test := func(name string, in interface{}, want string) { + test := func(name string, in any, want string) { if err := convertAssign(&buf, in); err != nil { t.Fatalf("%s: convertAssign = %v", name, err) } @@ -350,7 +350,7 @@ func TestRawBytesAllocs(t *testing.T) { t.Fatalf("allocs = %v; want 0", n) } - // This one involves a convT2E allocation, string -> interface{} + // This one involves a convT2E allocation, string -> any n = testing.AllocsPerRun(100, func() { test("string", "foo", "foo") }) @@ -462,7 +462,7 @@ func TestAssignZero(t *testing.T) { t.Error("vfloat64 is not zero") } - vinterface := interface{}("a") + vinterface := any("a") assignZero(&vinterface) if vinterface != nil { t.Error("vinterface is not zero") diff --git a/cursor.go b/cursor.go index 7c074e0c..96892529 100644 --- a/cursor.go +++ b/cursor.go @@ -10,8 +10,8 @@ type Cursor interface { Close() error Fields() ([]string, error) Next() bool - Scan(...interface{}) error - NopScanner() interface{} // TODO: conflict with manual scanners interface + Scan(...any) error + NopScanner() any // TODO: conflict with manual scanners interface } func scanOne(cur Cursor, doc *Document) error { @@ -55,7 +55,7 @@ func scanAll(cur Cursor, col *Collection) error { return nil } -func scanMulti(cur Cursor, keyField string, keyType reflect.Type, cols map[interface{}][]slice) error { +func scanMulti(cur Cursor, keyField string, keyType reflect.Type, cols map[any][]slice) error { defer cur.Close() fields, err := cur.Fields() @@ -66,7 +66,7 @@ func scanMulti(cur Cursor, keyField string, keyType reflect.Type, cols map[inter var ( found = false keyValue = reflect.New(keyType) - keyScanners = make([]interface{}, len(fields)) + keyScanners = make([]any, len(fields)) ) for i, field := range fields { diff --git a/cursor_test.go b/cursor_test.go index c211245b..b25bf39a 100644 --- a/cursor_test.go +++ b/cursor_test.go @@ -31,15 +31,15 @@ func (tc *testCursor) Next() bool { return ret.Get(0).(bool) } -func (tc *testCursor) NopScanner() interface{} { +func (tc *testCursor) NopScanner() any { return &sql.RawBytes{} } -func (tc *testCursor) Scan(scanners ...interface{}) error { +func (tc *testCursor) Scan(scanners ...any) error { ret := tc.Called(scanners...) var err error - if fn, ok := ret.Get(0).(func(...interface{}) error); ok { + if fn, ok := ret.Get(0).(func(...any) error); ok { err = fn(scanners...) } else { err = ret.Error(0) @@ -48,14 +48,14 @@ func (tc *testCursor) Scan(scanners ...interface{}) error { return err } -func (tc *testCursor) MockScan(ret ...interface{}) *mock.Call { - args := make([]interface{}, len(ret)) +func (tc *testCursor) MockScan(ret ...any) *mock.Call { + args := make([]any, len(ret)) for i := 0; i < len(args); i++ { args[i] = mock.Anything } return tc.On("Scan", args...). - Return(func(scanners ...interface{}) error { + Return(func(scanners ...any) error { for i := 0; i < len(scanners); i++ { if v, ok := scanners[i].(sql.Scanner); ok { v.Scan(ret[i]) @@ -181,7 +181,7 @@ func TestScanMulti(t *testing.T) { cur = &testCursor{} keyField = "id" keyType = reflect.TypeOf(0) - cols = map[interface{}][]slice{ + cols = map[any][]slice{ 10: {NewCollection(&users1), NewCollection(&users2)}, 11: {NewCollection(&users3)}, } @@ -227,7 +227,7 @@ func TestScanMulti_scanError(t *testing.T) { cur = &testCursor{} keyField = "id" keyType = reflect.TypeOf(0) - cols = map[interface{}][]slice{ + cols = map[any][]slice{ 11: {NewCollection(&users)}, } err = errors.New("scan error") @@ -250,7 +250,7 @@ func TestScanMulti_scanKeyError(t *testing.T) { cur = &testCursor{} keyField = "id" keyType = reflect.TypeOf(0) - cols = map[interface{}][]slice{ + cols = map[any][]slice{ 11: {NewCollection(&users)}, } err = errors.New("scan key error") @@ -272,7 +272,7 @@ func TestScanMulti_keyFieldsNotExists(t *testing.T) { cur = &testCursor{} keyField = "id" keyType = reflect.TypeOf(0) - cols = map[interface{}][]slice{ + cols = map[any][]slice{ 11: {NewCollection(&users)}, } ) @@ -292,7 +292,7 @@ func TestScanMulti_fieldsError(t *testing.T) { cur = &testCursor{} keyField = "id" keyType = reflect.TypeOf(0) - cols = map[interface{}][]slice{ + cols = map[any][]slice{ 11: {NewCollection(&users)}, } err = errors.New("fields error") @@ -311,7 +311,7 @@ func TestScanMulti_multipleTimes(t *testing.T) { cur = &testCursor{} keyField = "id" keyType = reflect.TypeOf(0) - cols = map[interface{}][]slice{ + cols = map[any][]slice{ 10: {NewCollection(&users[0]), NewCollection(&users[1])}, 11: {NewCollection(&users[2])}, 12: {NewCollection(&users[3]), NewCollection(&users[4])}, diff --git a/document.go b/document.go index 05d56ba4..97a0b77d 100644 --- a/document.go +++ b/document.go @@ -8,7 +8,7 @@ import ( // Document provides an abstraction over reflect to easily works with struct for database purpose. type Document struct { - v interface{} + v any rv reflect.Value rt reflect.Type meta DocumentMeta @@ -37,7 +37,7 @@ func (d Document) PrimaryField() string { } // PrimaryValues of this document. -func (d Document) PrimaryValues() []interface{} { +func (d Document) PrimaryValues() []any { if p, ok := d.v.(primary); ok { return p.PrimaryValues() } @@ -47,7 +47,7 @@ func (d Document) PrimaryValues() []interface{} { } var ( - pValues = make([]interface{}, len(d.meta.primaryIndex)) + pValues = make([]any, len(d.meta.primaryIndex)) ) for i := range pValues { @@ -59,7 +59,7 @@ func (d Document) PrimaryValues() []interface{} { // PrimaryValue of this document. // panic if document uses composite key. -func (d Document) PrimaryValue() interface{} { +func (d Document) PrimaryValue() any { if values := d.PrimaryValues(); len(values) == 1 { return values[0] } @@ -98,11 +98,11 @@ func (d Document) Type(field string) (reflect.Type, bool) { } // Value returns value of given field. if field does not exist, second returns value will be false. -func (d Document) Value(field string) (interface{}, bool) { +func (d Document) Value(field string) (any, bool) { if i, ok := d.meta.index[field]; ok { var ( - value interface{} + value any fv = reflectValueFieldByIndex(d.rv, i, false) ft = fv.Type() ) @@ -122,7 +122,7 @@ func (d Document) Value(field string) (interface{}, bool) { } // SetValue of the field, it returns false if field does not exist, or it's not assignable. -func (d Document) SetValue(field string, value interface{}) bool { +func (d Document) SetValue(field string, value any) bool { if i, ok := d.meta.index[field]; ok { var ( rv reflect.Value @@ -160,9 +160,9 @@ func (d Document) SetValue(field string, value interface{}) bool { } // Scanners returns slice of sql.Scanner for given fields. -func (d Document) Scanners(fields []string) []interface{} { +func (d Document) Scanners(fields []string) []any { var ( - result = make([]interface{}, len(fields)) + result = make([]any, len(fields)) assocRefs map[string]struct { fields []string indexes []int @@ -294,7 +294,7 @@ func (d Document) Flag(flag DocumentFlag) bool { // NewDocument used to create abstraction to work with struct. // Document can be created using interface or reflect.Value. -func NewDocument(record interface{}, readonly ...bool) *Document { +func NewDocument(record any, readonly ...bool) *Document { switch v := record.(type) { case *Document: return v @@ -309,7 +309,7 @@ func NewDocument(record interface{}, readonly ...bool) *Document { } } -func newDocument(v interface{}, rv reflect.Value, readonly bool) *Document { +func newDocument(v any, rv reflect.Value, readonly bool) *Document { var ( rt = rv.Type() ) diff --git a/document_meta.go b/document_meta.go index ccfc6e3e..00442540 100644 --- a/document_meta.go +++ b/document_meta.go @@ -49,7 +49,7 @@ type table interface { type primary interface { PrimaryFields() []string - PrimaryValues() []interface{} + PrimaryValues() []any } type primaryData struct { diff --git a/document_test.go b/document_test.go index d084834f..82ee9683 100644 --- a/document_test.go +++ b/document_test.go @@ -23,8 +23,8 @@ func (i Item) PrimaryFields() []string { return []string{"_uuid"} } -func (i Item) PrimaryValues() []interface{} { - return []interface{}{i.UUID} +func (i Item) PrimaryValues() []any { + return []any{i.UUID} } func TestDocument_ReflectValue(t *testing.T) { @@ -168,7 +168,7 @@ func TestDocument_Primary_composite(t *testing.T) { }) assert.Equal(t, []string{"user_id", "role_id"}, doc.PrimaryFields()) - assert.Equal(t, []interface{}{1, 2}, doc.PrimaryValues()) + assert.Equal(t, []any{1, 2}, doc.PrimaryValues()) } func TestDocument_Fields(t *testing.T) { @@ -324,7 +324,7 @@ func TestDocument_Value(t *testing.T) { Data: []byte("data"), } doc = NewDocument(&record) - values = map[string]interface{}{ + values = map[string]any{ "id": 1, "name": "name", "number": 10.5, @@ -478,7 +478,7 @@ func TestDocument_Scanners(t *testing.T) { } doc = NewDocument(&record) fields = []string{"name", "id", "skip", "data", "number", "address", "not_exist"} - scanners = []interface{}{ + scanners = []any{ Nullable(&record.Name), Nullable(&record.ID), &sql.RawBytes{}, @@ -508,7 +508,7 @@ func TestDocument_Scanners_withAssoc(t *testing.T) { } doc = NewDocument(&record) fields = []string{"id", "user_id", "buyer.id", "buyer.name", "buyer.work_address.street", "status", "invalid_assoc.id"} - scanners = []interface{}{ + scanners = []any{ Nullable(&record.ID), Nullable(&record.BuyerID), Nullable(&record.Buyer.ID), @@ -528,7 +528,7 @@ func TestDocument_Scanners_withUnitializedAssoc(t *testing.T) { doc = NewDocument(&record) fields = []string{"id", "user_id", "buyer.id", "buyer.name", "status", "buyer.work_address.street"} result = doc.Scanners(fields) - expected = []interface{}{ + expected = []any{ Nullable(&record.ID), Nullable(&record.BuyerID), Nullable(&record.Buyer.ID), @@ -578,7 +578,7 @@ func TestDocument_Slice(t *testing.T) { func TestDocument_Association(t *testing.T) { tests := []struct { name string - record interface{} + record any belongsTo []string hasOne []string hasMany []string @@ -655,7 +655,7 @@ func TestDocument_Association_notFOund(t *testing.T) { func TestDocument(t *testing.T) { tests := []struct { - record interface{} + record any panics bool }{ { diff --git a/filter_query.go b/filter_query.go index 5fcc62c7..955cc77b 100644 --- a/filter_query.go +++ b/filter_query.go @@ -74,7 +74,7 @@ const ( type FilterQuery struct { Type FilterOp Field string - Value interface{} + Value any Inner []FilterQuery } @@ -123,9 +123,9 @@ func (fq FilterQuery) String() string { builder.WriteByte('"') builder.WriteString(fq.Field) builder.WriteString("\", ") - builder.WriteString(fmtifaces(fq.Value.([]interface{}))) + builder.WriteString(fmtifaces(fq.Value.([]any))) case FilterFragmentOp: - v := fq.Value.([]interface{}) + v := fq.Value.([]any) builder.WriteByte('"') builder.WriteString(fq.Field) builder.WriteByte('"') @@ -192,32 +192,32 @@ func (fq FilterQuery) applyIndex(index *Index) { } // AndEq append equal expression using and. -func (fq FilterQuery) AndEq(field string, value interface{}) FilterQuery { +func (fq FilterQuery) AndEq(field string, value any) FilterQuery { return fq.and(Eq(field, value)) } // AndNe append not equal expression using and. -func (fq FilterQuery) AndNe(field string, value interface{}) FilterQuery { +func (fq FilterQuery) AndNe(field string, value any) FilterQuery { return fq.and(Ne(field, value)) } // AndLt append lesser than expression using and. -func (fq FilterQuery) AndLt(field string, value interface{}) FilterQuery { +func (fq FilterQuery) AndLt(field string, value any) FilterQuery { return fq.and(Lt(field, value)) } // AndLte append lesser than or equal expression using and. -func (fq FilterQuery) AndLte(field string, value interface{}) FilterQuery { +func (fq FilterQuery) AndLte(field string, value any) FilterQuery { return fq.and(Lte(field, value)) } // AndGt append greater than expression using and. -func (fq FilterQuery) AndGt(field string, value interface{}) FilterQuery { +func (fq FilterQuery) AndGt(field string, value any) FilterQuery { return fq.and(Gt(field, value)) } // AndGte append greater than or equal expression using and. -func (fq FilterQuery) AndGte(field string, value interface{}) FilterQuery { +func (fq FilterQuery) AndGte(field string, value any) FilterQuery { return fq.and(Gte(field, value)) } @@ -232,12 +232,12 @@ func (fq FilterQuery) AndNotNil(field string) FilterQuery { } // AndIn append is in expression using and. -func (fq FilterQuery) AndIn(field string, values ...interface{}) FilterQuery { +func (fq FilterQuery) AndIn(field string, values ...any) FilterQuery { return fq.and(In(field, values...)) } // AndNin append is not in expression using and. -func (fq FilterQuery) AndNin(field string, values ...interface{}) FilterQuery { +func (fq FilterQuery) AndNin(field string, values ...any) FilterQuery { return fq.and(Nin(field, values...)) } @@ -252,37 +252,37 @@ func (fq FilterQuery) AndNotLike(field string, pattern string) FilterQuery { } // AndFragment append fragment using and. -func (fq FilterQuery) AndFragment(expr string, values ...interface{}) FilterQuery { +func (fq FilterQuery) AndFragment(expr string, values ...any) FilterQuery { return fq.and(FilterFragment(expr, values...)) } // OrEq append equal expression using or. -func (fq FilterQuery) OrEq(field string, value interface{}) FilterQuery { +func (fq FilterQuery) OrEq(field string, value any) FilterQuery { return fq.or(Eq(field, value)) } // OrNe append not equal expression using or. -func (fq FilterQuery) OrNe(field string, value interface{}) FilterQuery { +func (fq FilterQuery) OrNe(field string, value any) FilterQuery { return fq.or(Ne(field, value)) } // OrLt append lesser than expression using or. -func (fq FilterQuery) OrLt(field string, value interface{}) FilterQuery { +func (fq FilterQuery) OrLt(field string, value any) FilterQuery { return fq.or(Lt(field, value)) } // OrLte append lesser than or equal expression using or. -func (fq FilterQuery) OrLte(field string, value interface{}) FilterQuery { +func (fq FilterQuery) OrLte(field string, value any) FilterQuery { return fq.or(Lte(field, value)) } // OrGt append greater than expression using or. -func (fq FilterQuery) OrGt(field string, value interface{}) FilterQuery { +func (fq FilterQuery) OrGt(field string, value any) FilterQuery { return fq.or(Gt(field, value)) } // OrGte append greater than or equal expression using or. -func (fq FilterQuery) OrGte(field string, value interface{}) FilterQuery { +func (fq FilterQuery) OrGte(field string, value any) FilterQuery { return fq.or(Gte(field, value)) } @@ -297,12 +297,12 @@ func (fq FilterQuery) OrNotNil(field string) FilterQuery { } // OrIn append is in expression using or. -func (fq FilterQuery) OrIn(field string, values ...interface{}) FilterQuery { +func (fq FilterQuery) OrIn(field string, values ...any) FilterQuery { return fq.or(In(field, values...)) } // OrNin append is not in expression using or. -func (fq FilterQuery) OrNin(field string, values ...interface{}) FilterQuery { +func (fq FilterQuery) OrNin(field string, values ...any) FilterQuery { return fq.or(Nin(field, values...)) } @@ -317,7 +317,7 @@ func (fq FilterQuery) OrNotLike(field string, pattern string) FilterQuery { } // OrFragment append fragment using or. -func (fq FilterQuery) OrFragment(expr string, values ...interface{}) FilterQuery { +func (fq FilterQuery) OrFragment(expr string, values ...any) FilterQuery { return fq.or(FilterFragment(expr, values...)) } @@ -385,7 +385,7 @@ func Not(inner ...FilterQuery) FilterQuery { } // Eq expression field equal to value. -func Eq(field string, value interface{}) FilterQuery { +func Eq(field string, value any) FilterQuery { return FilterQuery{ Type: FilterEqOp, Field: field, @@ -398,7 +398,7 @@ func lockVersion(version int) FilterQuery { } // Ne compares that left value is not equal to right value. -func Ne(field string, value interface{}) FilterQuery { +func Ne(field string, value any) FilterQuery { return FilterQuery{ Type: FilterNeOp, Field: field, @@ -407,7 +407,7 @@ func Ne(field string, value interface{}) FilterQuery { } // Lt compares that left value is less than to right value. -func Lt(field string, value interface{}) FilterQuery { +func Lt(field string, value any) FilterQuery { return FilterQuery{ Type: FilterLtOp, Field: field, @@ -416,7 +416,7 @@ func Lt(field string, value interface{}) FilterQuery { } // Lte compares that left value is less than or equal to right value. -func Lte(field string, value interface{}) FilterQuery { +func Lte(field string, value any) FilterQuery { return FilterQuery{ Type: FilterLteOp, Field: field, @@ -425,7 +425,7 @@ func Lte(field string, value interface{}) FilterQuery { } // Gt compares that left value is greater than to right value. -func Gt(field string, value interface{}) FilterQuery { +func Gt(field string, value any) FilterQuery { return FilterQuery{ Type: FilterGtOp, Field: field, @@ -434,7 +434,7 @@ func Gt(field string, value interface{}) FilterQuery { } // Gte compares that left value is greater than or equal to right value. -func Gte(field string, value interface{}) FilterQuery { +func Gte(field string, value any) FilterQuery { return FilterQuery{ Type: FilterGteOp, Field: field, @@ -459,7 +459,7 @@ func NotNil(field string) FilterQuery { } // In check whethers value of the field is included in values. -func In(field string, values ...interface{}) FilterQuery { +func In(field string, values ...any) FilterQuery { return FilterQuery{ Type: FilterInOp, Field: field, @@ -470,7 +470,7 @@ func In(field string, values ...interface{}) FilterQuery { // InInt check whethers integer values of the field is included. func InInt(field string, values []int) FilterQuery { var ( - ivalues = make([]interface{}, len(values)) + ivalues = make([]any, len(values)) ) for i := range values { @@ -483,7 +483,7 @@ func InInt(field string, values []int) FilterQuery { // InUint check whethers unsigned integer values of the field is included. func InUint(field string, values []uint) FilterQuery { var ( - ivalues = make([]interface{}, len(values)) + ivalues = make([]any, len(values)) ) for i := range values { @@ -496,7 +496,7 @@ func InUint(field string, values []uint) FilterQuery { // InString check whethers string values of the field is included. func InString(field string, values []string) FilterQuery { var ( - ivalues = make([]interface{}, len(values)) + ivalues = make([]any, len(values)) ) for i := range values { @@ -507,7 +507,7 @@ func InString(field string, values []string) FilterQuery { } // Nin check whethers value of the field is not included in values. -func Nin(field string, values ...interface{}) FilterQuery { +func Nin(field string, values ...any) FilterQuery { return FilterQuery{ Type: FilterNinOp, Field: field, @@ -518,7 +518,7 @@ func Nin(field string, values ...interface{}) FilterQuery { // NinInt check whethers integer values of the is not included. func NinInt(field string, values []int) FilterQuery { var ( - ivalues = make([]interface{}, len(values)) + ivalues = make([]any, len(values)) ) for i := range values { @@ -531,7 +531,7 @@ func NinInt(field string, values []int) FilterQuery { // NinUint check whethers unsigned integer values of the is not included. func NinUint(field string, values []uint) FilterQuery { var ( - ivalues = make([]interface{}, len(values)) + ivalues = make([]any, len(values)) ) for i := range values { @@ -544,7 +544,7 @@ func NinUint(field string, values []uint) FilterQuery { // NinString check whethers string values of the is not included. func NinString(field string, values []string) FilterQuery { var ( - ivalues = make([]interface{}, len(values)) + ivalues = make([]any, len(values)) ) for i := range values { @@ -573,7 +573,7 @@ func NotLike(field string, pattern string) FilterQuery { } // FilterFragment add custom filter. -func FilterFragment(expr string, values ...interface{}) FilterQuery { +func FilterFragment(expr string, values ...any) FilterQuery { return FilterQuery{ Type: FilterFragmentOp, Field: expr, @@ -590,7 +590,7 @@ func filterDocument(doc *Document) FilterQuery { return filterDocumentPrimary(pFields, pValues, FilterEqOp) } -func filterDocumentPrimary(pFields []string, pValues []interface{}, op FilterOp) FilterQuery { +func filterDocumentPrimary(pFields []string, pValues []any, op FilterOp) FilterQuery { var filter FilterQuery for i := range pFields { @@ -615,11 +615,11 @@ func filterCollection(col *Collection) FilterQuery { return filterCollectionPrimary(pFields, pValues, length) } -func filterCollectionPrimary(pFields []string, pValues []interface{}, length int) FilterQuery { +func filterCollectionPrimary(pFields []string, pValues []any, length int) FilterQuery { var filter FilterQuery if len(pFields) == 1 { - filter = In(pFields[0], pValues[0].([]interface{})...) + filter = In(pFields[0], pValues[0].([]any)...) } else { var ( andFilters = make([]FilterQuery, length) @@ -627,7 +627,7 @@ func filterCollectionPrimary(pFields []string, pValues []interface{}, length int for i := range pValues { var ( - values = pValues[i].([]interface{}) + values = pValues[i].([]any) ) for j := range values { diff --git a/filter_query_test.go b/filter_query_test.go index 3a73c8f8..93933265 100644 --- a/filter_query_test.go +++ b/filter_query_test.go @@ -547,7 +547,7 @@ func TestFilterQuery_AndIn(t *testing.T) { { Type: FilterInOp, Field: "field", - Value: []interface{}{"value1", "value2"}, + Value: []any{"value1", "value2"}, }, }, }, FilterQuery{}.AndIn("field", "value1", "value2")) @@ -559,7 +559,7 @@ func TestFilterQuery_AndNin(t *testing.T) { { Type: FilterNinOp, Field: "field", - Value: []interface{}{"value1", "value2"}, + Value: []any{"value1", "value2"}, }, }, }, FilterQuery{}.AndNin("field", "value1", "value2")) @@ -595,7 +595,7 @@ func TestFilterQuery_AndFragment(t *testing.T) { { Type: FilterFragmentOp, Field: "expr", - Value: []interface{}{"value"}, + Value: []any{"value"}, }, }, }, FilterQuery{}.AndFragment("expr", "value")) @@ -710,7 +710,7 @@ func TestFilterQuery_OrIn(t *testing.T) { { Type: FilterInOp, Field: "field", - Value: []interface{}{"value1", "value2"}, + Value: []any{"value1", "value2"}, }, }, }, FilterQuery{}.OrIn("field", "value1", "value2")) @@ -723,7 +723,7 @@ func TestFilterQuery_OrNin(t *testing.T) { { Type: FilterNinOp, Field: "field", - Value: []interface{}{"value1", "value2"}, + Value: []any{"value1", "value2"}, }, }, }, FilterQuery{}.OrNin("field", "value1", "value2")) @@ -762,7 +762,7 @@ func TestFilterQuery_OrFragment(t *testing.T) { { Type: FilterFragmentOp, Field: "expr", - Value: []interface{}{"value"}, + Value: []any{"value"}, }, }, }, FilterQuery{}.OrFragment("expr", "value")) @@ -834,7 +834,7 @@ func TestIn(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterInOp, Field: "field", - Value: []interface{}{"value1", "value2"}, + Value: []any{"value1", "value2"}, }, In("field", "value1", "value2")) } @@ -842,7 +842,7 @@ func TestInInt(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterInOp, Field: "field", - Value: []interface{}{1, 2}, + Value: []any{1, 2}, }, InInt("field", []int{1, 2})) } @@ -850,7 +850,7 @@ func TestInUint(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterInOp, Field: "field", - Value: []interface{}{uint(1), uint(2)}, + Value: []any{uint(1), uint(2)}, }, InUint("field", []uint{1, 2})) } @@ -858,7 +858,7 @@ func TestInString(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterInOp, Field: "field", - Value: []interface{}{"1", "2"}, + Value: []any{"1", "2"}, }, InString("field", []string{"1", "2"})) } @@ -866,7 +866,7 @@ func TestNin(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterNinOp, Field: "field", - Value: []interface{}{"value1", "value2"}, + Value: []any{"value1", "value2"}, }, Nin("field", "value1", "value2")) } @@ -874,7 +874,7 @@ func TestNinInt(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterNinOp, Field: "field", - Value: []interface{}{1, 2}, + Value: []any{1, 2}, }, NinInt("field", []int{1, 2})) } @@ -882,7 +882,7 @@ func TestNinUint(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterNinOp, Field: "field", - Value: []interface{}{uint(1), uint(2)}, + Value: []any{uint(1), uint(2)}, }, NinUint("field", []uint{1, 2})) } @@ -890,7 +890,7 @@ func TestNinString(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterNinOp, Field: "field", - Value: []interface{}{"1", "2"}, + Value: []any{"1", "2"}, }, NinString("field", []string{"1", "2"})) } @@ -914,7 +914,7 @@ func TestFilterFragment(t *testing.T) { assert.Equal(t, FilterQuery{ Type: FilterFragmentOp, Field: "expr", - Value: []interface{}{"value"}, + Value: []any{"value"}, }, FilterFragment("expr", "value")) } diff --git a/go.mod b/go.mod index 86a561a6..38431a56 100644 --- a/go.mod +++ b/go.mod @@ -2,11 +2,18 @@ module github.com/go-rel/rel require ( github.com/jinzhu/inflection v1.0.0 - github.com/onsi/ginkgo v1.15.0 // indirect - github.com/onsi/gomega v1.10.5 // indirect github.com/serenize/snaker v0.0.0-20201027110005-a7ad2135616e github.com/stretchr/testify v1.8.0 github.com/subosito/gotenv v1.4.1 ) -go 1.15 +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/onsi/ginkgo v1.15.0 // indirect + github.com/onsi/gomega v1.10.5 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/objx v0.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +go 1.19 diff --git a/go.sum b/go.sum index ab21e914..fd385d92 100644 --- a/go.sum +++ b/go.sum @@ -10,11 +10,9 @@ github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:x github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= @@ -37,7 +35,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.4.0 h1:M2gUjqZET1qApGOWNSnZ49BAIMX4F/1plDv3+l31EJ4= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= @@ -76,14 +73,12 @@ golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4f golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/iterator.go b/iterator.go index 32cf7055..27e4a406 100644 --- a/iterator.go +++ b/iterator.go @@ -9,7 +9,7 @@ import ( // Iterator allows iterating through all record in database in batch. type Iterator interface { io.Closer - Next(record interface{}) error + Next(record any) error } // IteratorOption is used to configure iteration behaviour, such as batch size, start id and finish id. @@ -33,7 +33,7 @@ func BatchSize(size int) IteratorOption { return batchSize(size) } -type start []interface{} +type start []any func (s start) apply(i *iterator) { i.start = s @@ -45,11 +45,11 @@ func (s start) String() string { } // Start specifies the primary value to start from (inclusive). -func Start(id ...interface{}) IteratorOption { +func Start(id ...any) IteratorOption { return start(id) } -type finish []interface{} +type finish []any func (f finish) apply(i *iterator) { i.finish = f @@ -61,14 +61,14 @@ func (f finish) String() string { } // Finish specifies the primary value to finish at (inclusive). -func Finish(id ...interface{}) IteratorOption { +func Finish(id ...any) IteratorOption { return finish(id) } type iterator struct { ctx context.Context - start []interface{} - finish []interface{} + start []any + finish []any batchSize int current int query Query @@ -87,7 +87,7 @@ func (i *iterator) Close() error { return nil } -func (i *iterator) Next(record interface{}) error { +func (i *iterator) Next(record any) error { if i.current%i.batchSize == 0 { if err := i.fetch(i.ctx, record); err != nil { return err @@ -107,7 +107,7 @@ func (i *iterator) Next(record interface{}) error { return i.cursor.Scan(scanners...) } -func (i *iterator) fetch(ctx context.Context, record interface{}) error { +func (i *iterator) fetch(ctx context.Context, record any) error { if i.current == 0 { i.init(record) } else { @@ -132,7 +132,7 @@ func (i *iterator) fetch(ctx context.Context, record interface{}) error { return nil } -func (i *iterator) init(record interface{}) { +func (i *iterator) init(record any) { var ( doc = NewDocument(record) ) diff --git a/join_query.go b/join_query.go index 61c6e43b..6df629c7 100644 --- a/join_query.go +++ b/join_query.go @@ -8,7 +8,7 @@ type JoinQuery struct { To string Assoc string Filter FilterQuery - Arguments []interface{} + Arguments []any } // Build query. @@ -68,10 +68,10 @@ func NewJoinWith(mode string, table string, from string, to string, filter ...Fi } // NewJoinFragment defines a join clause using raw query. -func NewJoinFragment(expr string, args ...interface{}) JoinQuery { +func NewJoinFragment(expr string, args ...any) JoinQuery { if args == nil { // prevent buildJoin to populate From and To variable. - args = []interface{}{} + args = []any{} } return JoinQuery{ diff --git a/join_query_test.go b/join_query_test.go index 7a6e748c..fa7aa400 100644 --- a/join_query_test.go +++ b/join_query_test.go @@ -55,12 +55,12 @@ func TestJoinWithMultipleFilters(t *testing.T) { func TestJoinFragment(t *testing.T) { assert.Equal(t, rel.JoinQuery{ Mode: "JOIN transactions ON id=?", - Arguments: []interface{}{1}, + Arguments: []any{1}, }, rel.NewJoinFragment("JOIN transactions ON id=?", 1)) assert.Equal(t, rel.JoinQuery{ Mode: "JOIN transactions ON transactions.user_id=users.id", - Arguments: []interface{}{}, + Arguments: []any{}, }, rel.NewJoinFragment("JOIN transactions ON transactions.user_id=users.id")) } diff --git a/map.go b/map.go index c9e58163..ca807495 100644 --- a/map.go +++ b/map.go @@ -10,7 +10,7 @@ import ( // Insert/Update of has one or belongs to can be done using other Map as a value. // Insert/Update of has many can be done using slice of Map as a value. // Map is intended to be used internally within application, and not to be exposed directly as an APIs. -type Map map[string]interface{} +type Map map[string]any // Apply mutation. func (m Map) Apply(doc *Document, mutation *Mutation) { @@ -102,17 +102,17 @@ func (m Map) String() string { return builder.String() } -func applyMaps(maps []Map, assoc Association) ([]Mutation, []interface{}) { +func applyMaps(maps []Map, assoc Association) ([]Mutation, []any) { var ( - deletedIDs []interface{} + deletedIDs []any muts = make([]Mutation, len(maps)) col, _ = assoc.Collection() ) var ( pField = col.PrimaryField() - pIndex = make(map[interface{}]int) - pValues = col.PrimaryValue().([]interface{}) + pIndex = make(map[any]int) + pValues = col.PrimaryValue().([]any) ) for i, v := range pValues { @@ -150,7 +150,7 @@ func applyMaps(maps []Map, assoc Association) ([]Mutation, []interface{}) { deletedIDs = pValues[curr:] col.Truncate(0, curr) } else { - deletedIDs = []interface{}{} + deletedIDs = []any{} } // inserts remaining diff --git a/map_test.go b/map_test.go index 386621e1..fa69f576 100644 --- a/map_test.go +++ b/map_test.go @@ -38,7 +38,7 @@ func TestMap(t *testing.T) { userMutation.SetAssoc("transactions", transaction1Mutation, transaction2Mutation) userMutation.SetAssoc("address", addressMutation) - userMutation.SetDeletedIDs("transactions", []interface{}{}) + userMutation.SetDeletedIDs("transactions", []any{}) assert.Equal(t, userMutation, Apply(doc, data)) assert.Equal(t, User{ @@ -124,7 +124,7 @@ func TestMap_update(t *testing.T) { userMutation.SetAssoc("transactions", transaction1Mutation, transaction2Mutation) userMutation.SetAssoc("address", addressMutation) - userMutation.SetDeletedIDs("transactions", []interface{}{}) + userMutation.SetDeletedIDs("transactions", []any{}) assert.Equal(t, userMutation, Apply(doc, data)) assert.Equal(t, User{ @@ -167,7 +167,7 @@ func TestMap_hasManyUpdateDeleteInsert(t *testing.T) { ) userMutation.SetAssoc("transactions", transaction2Mutation, transaction1Mutation) - userMutation.SetDeletedIDs("transactions", []interface{}{2}) + userMutation.SetDeletedIDs("transactions", []any{2}) assert.Equal(t, userMutation, Apply(doc, data)) assert.Equal(t, User{ diff --git a/mutation.go b/mutation.go index abc9ad86..7d31e113 100644 --- a/mutation.go +++ b/mutation.go @@ -47,7 +47,7 @@ func applyMutators(doc *Document, cascade, applyStructset bool, mutators ...Muta // AssocMutation represents mutation for association. type AssocMutation struct { Mutations []Mutation - DeletedIDs []interface{} // This is array of single id, and doesn't support composite primary key. + DeletedIDs []any // This is array of single id, and doesn't support composite primary key. } // Mutation represents value to be inserted or updated to database. @@ -107,7 +107,7 @@ func (m *Mutation) SetAssoc(field string, muts ...Mutation) { // SetDeletedIDs mutation. // nil slice will clear association. -func (m *Mutation) SetDeletedIDs(field string, ids []interface{}) { +func (m *Mutation) SetDeletedIDs(field string, ids []any) { m.initAssoc() assoc := m.Assoc[field] @@ -133,7 +133,7 @@ const ( type Mutate struct { Type ChangeOp Field string - Value interface{} + Value any } // Apply mutation. @@ -173,14 +173,14 @@ func (m Mutate) String() string { case ChangeIncOp: str = fmt.Sprintf("rel.IncBy(\"%s\", %s)", m.Field, fmtiface(m.Value)) case ChangeFragmentOp: - str = fmt.Sprintf("rel.SetFragment(\"%s\", %s)", m.Field, fmtifaces(m.Value.([]interface{}))) + str = fmt.Sprintf("rel.SetFragment(\"%s\", %s)", m.Field, fmtifaces(m.Value.([]any))) } return str } // Set create a mutate using set operation. -func Set(field string, value interface{}) Mutate { +func Set(field string, value any) Mutate { return Mutate{ Type: ChangeSetOp, Field: field, @@ -218,7 +218,7 @@ func DecBy(field string, n int) Mutate { // SetFragment create a mutate operation using fragment operation. // Only available for Update. -func SetFragment(raw string, args ...interface{}) Mutate { +func SetFragment(raw string, args ...any) Mutate { return Mutate{ Type: ChangeFragmentOp, Field: raw, diff --git a/nullable.go b/nullable.go index 7d42807a..cf5e3141 100644 --- a/nullable.go +++ b/nullable.go @@ -6,18 +6,18 @@ import ( ) type nullable struct { - dest interface{} + dest any } var _ sql.Scanner = (*nullable)(nil) -func (n nullable) Scan(src interface{}) error { +func (n nullable) Scan(src any) error { return convertAssign(n.dest, src) } // Nullable wrap value as a nullable sql.Scanner. // If value returned from database is nil, nullable scanner will set dest to zero value. -func Nullable(dest interface{}) interface{} { +func Nullable(dest any) any { if s, ok := dest.(sql.Scanner); ok { return s } diff --git a/nullable_test.go b/nullable_test.go index b6914444..3f650af6 100644 --- a/nullable_test.go +++ b/nullable_test.go @@ -22,7 +22,7 @@ func TestNullable(t *testing.T) { type customScanner int -func (*customScanner) Scan(interface{}) error { +func (*customScanner) Scan(any) error { return nil } diff --git a/on_conflict.go b/on_conflict.go index 502283bd..d1f3bff1 100644 --- a/on_conflict.go +++ b/on_conflict.go @@ -6,7 +6,7 @@ type OnConflict struct { Ignore bool Replace bool Fragment string - FragmentArgs []interface{} + FragmentArgs []any } // Apply mutation. @@ -59,6 +59,6 @@ func OnConflictKeysReplace(keys []string) OnConflict { // OnConflictFragment allows to write custom sql for on conflict. // // This will add custom sql after ON CONFLICT, example: ON CONFLICT [FRAGMENT] -func OnConflictFragment(sql string, args ...interface{}) OnConflict { +func OnConflictFragment(sql string, args ...any) OnConflict { return OnConflict{Fragment: sql, FragmentArgs: args} } diff --git a/on_conflict_test.go b/on_conflict_test.go index e42cca56..3bdc8d11 100644 --- a/on_conflict_test.go +++ b/on_conflict_test.go @@ -15,5 +15,5 @@ func TestOnConflict(t *testing.T) { assert.Equal(t, OnConflict{Keys: []string{"id"}, Replace: true}, OnConflictKeyReplace("id")) assert.Equal(t, OnConflict{Keys: []string{"id"}, Replace: true}, OnConflictKeysReplace([]string{"id"})) - assert.Equal(t, OnConflict{Fragment: "sql", FragmentArgs: []interface{}{1}}, OnConflictFragment("sql", 1)) + assert.Equal(t, OnConflict{Fragment: "sql", FragmentArgs: []any{1}}, OnConflictFragment("sql", 1)) } diff --git a/query.go b/query.go index 23a40b73..58445b62 100644 --- a/query.go +++ b/query.go @@ -176,7 +176,7 @@ func (q Query) JoinWith(mode string, table string, from string, to string, filte } // Joinf create join query using a raw query. -func (q Query) Joinf(expr string, args ...interface{}) Query { +func (q Query) Joinf(expr string, args ...any) Query { NewJoinFragment(expr, args...).Build(&q) // TODO: ensure this always called last return q @@ -201,7 +201,7 @@ func (q Query) Where(filters ...FilterQuery) Query { } // Wheref create where query using a raw query. -func (q Query) Wheref(expr string, args ...interface{}) Query { +func (q Query) Wheref(expr string, args ...any) Query { q.WhereQuery = q.WhereQuery.And(FilterFragment(expr, args...)) return q } @@ -213,7 +213,7 @@ func (q Query) OrWhere(filters ...FilterQuery) Query { } // OrWheref create where query using a raw query. -func (q Query) OrWheref(expr string, args ...interface{}) Query { +func (q Query) OrWheref(expr string, args ...any) Query { q.WhereQuery = q.WhereQuery.Or(FilterFragment(expr, args...)) return q } @@ -231,7 +231,7 @@ func (q Query) Having(filters ...FilterQuery) Query { } // Havingf create having query using a raw query. -func (q Query) Havingf(expr string, args ...interface{}) Query { +func (q Query) Havingf(expr string, args ...any) Query { q.GroupQuery.Filter = q.GroupQuery.Filter.And(FilterFragment(expr, args...)) return q } @@ -243,7 +243,7 @@ func (q Query) OrHaving(filters ...FilterQuery) Query { } // OrHavingf create having query using a raw query. -func (q Query) OrHavingf(expr string, args ...interface{}) Query { +func (q Query) OrHavingf(expr string, args ...any) Query { q.GroupQuery.Filter = q.GroupQuery.Filter.Or(FilterFragment(expr, args...)) return q } @@ -495,7 +495,7 @@ func JoinAssocWith(mode string, assoc string, filter ...FilterQuery) Query { } // Joinf create a query with chainable syntax, using join as the starting point. -func Joinf(expr string, args ...interface{}) Query { +func Joinf(expr string, args ...any) Query { query := newQuery() query.JoinQuery = []JoinQuery{ NewJoinFragment(expr, args...), diff --git a/query_test.go b/query_test.go index d95d3e76..ccfb03f9 100644 --- a/query_test.go +++ b/query_test.go @@ -246,7 +246,7 @@ func TestQuerier(t *testing.T) { query: rel.Query{ SQLQuery: rel.SQLQuery{ Statement: "SELECT ?;", - Values: []interface{}{1}, + Values: []any{1}, }, CascadeQuery: true, }, @@ -367,7 +367,7 @@ func TestQuery_Joinf(t *testing.T) { JoinQuery: []rel.JoinQuery{ { Mode: "JOIN transactions ON transacations.id=?", - Arguments: []interface{}{1}, + Arguments: []any{1}, }, }, CascadeQuery: true, diff --git a/rel_test.go b/rel_test.go index 079428da..294424ad 100644 --- a/rel_test.go +++ b/rel_test.go @@ -90,7 +90,7 @@ type History struct { type Notes string -func (n Notes) Equal(other interface{}) bool { +func (n Notes) Equal(other any) bool { if o, ok := other.(Notes); ok { return n == o } diff --git a/repository.go b/repository.go index cd9f9d5c..39327cbe 100644 --- a/repository.go +++ b/repository.go @@ -46,53 +46,53 @@ type Repository interface { // Find a record that match the query. // If no result found, it'll return not found error. - Find(ctx context.Context, record interface{}, queriers ...Querier) error + Find(ctx context.Context, record any, queriers ...Querier) error // MustFind a record that match the query. // If no result found, it'll panic. - MustFind(ctx context.Context, record interface{}, queriers ...Querier) + MustFind(ctx context.Context, record any, queriers ...Querier) // FindAll records that match the query. - FindAll(ctx context.Context, records interface{}, queriers ...Querier) error + FindAll(ctx context.Context, records any, queriers ...Querier) error // MustFindAll records that match the query. // It'll panic if any error eccured. - MustFindAll(ctx context.Context, records interface{}, queriers ...Querier) + MustFindAll(ctx context.Context, records any, queriers ...Querier) // FindAndCountAll records that match the query. // This is a convenient method that combines FindAll and Count. It's useful when dealing with queries related to pagination. // Limit and Offset property will be ignored when performing count query. - FindAndCountAll(ctx context.Context, records interface{}, queriers ...Querier) (int, error) + FindAndCountAll(ctx context.Context, records any, queriers ...Querier) (int, error) // MustFindAndCountAll records that match the query. // This is a convenient method that combines FindAll and Count. It's useful when dealing with queries related to pagination. // Limit and Offset property will be ignored when performing count query. // It'll panic if any error eccured. - MustFindAndCountAll(ctx context.Context, records interface{}, queriers ...Querier) int + MustFindAndCountAll(ctx context.Context, records any, queriers ...Querier) int // Insert a record to database. - Insert(ctx context.Context, record interface{}, mutators ...Mutator) error + Insert(ctx context.Context, record any, mutators ...Mutator) error // MustInsert an record to database. // It'll panic if any error occurred. - MustInsert(ctx context.Context, record interface{}, mutators ...Mutator) + MustInsert(ctx context.Context, record any, mutators ...Mutator) // InsertAll records. // Does not supports application cascade insert. - InsertAll(ctx context.Context, records interface{}, mutators ...Mutator) error + InsertAll(ctx context.Context, records any, mutators ...Mutator) error // MustInsertAll records. // It'll panic if any error occurred. // Does not supports application cascade insert. - MustInsertAll(ctx context.Context, records interface{}, mutators ...Mutator) + MustInsertAll(ctx context.Context, records any, mutators ...Mutator) // Update a record in database. // It'll panic if any error occurred. - Update(ctx context.Context, record interface{}, mutators ...Mutator) error + Update(ctx context.Context, record any, mutators ...Mutator) error // MustUpdate a record in database. // It'll panic if any error occurred. - MustUpdate(ctx context.Context, record interface{}, mutators ...Mutator) + MustUpdate(ctx context.Context, record any, mutators ...Mutator) // UpdateAny records tha match the query. // Returns number of updated records and error. @@ -104,20 +104,20 @@ type Repository interface { MustUpdateAny(ctx context.Context, query Query, mutates ...Mutate) int // Delete a record. - Delete(ctx context.Context, record interface{}, mutators ...Mutator) error + Delete(ctx context.Context, record any, mutators ...Mutator) error // MustDelete a record. // It'll panic if any error eccured. - MustDelete(ctx context.Context, record interface{}, mutators ...Mutator) + MustDelete(ctx context.Context, record any, mutators ...Mutator) // DeleteAll records. // Does not supports application cascade delete. - DeleteAll(ctx context.Context, records interface{}) error + DeleteAll(ctx context.Context, records any) error // MustDeleteAll records. // It'll panic if any error occurred. // Does not supports application cascade delete. - MustDeleteAll(ctx context.Context, records interface{}) + MustDeleteAll(ctx context.Context, records any) // DeleteAny records that match the query. // Returns number of deleted records and error. @@ -132,20 +132,20 @@ type Repository interface { // This function can accepts either a struct or a slice of structs. // If association is already loaded, this will do nothing. // To force preloading even though association is already loaeded, add `Reload(true)` as query. - Preload(ctx context.Context, records interface{}, field string, queriers ...Querier) error + Preload(ctx context.Context, records any, field string, queriers ...Querier) error // MustPreload association with given query. // This function can accepts either a struct or a slice of structs. // It'll panic if any error occurred. - MustPreload(ctx context.Context, records interface{}, field string, queriers ...Querier) + MustPreload(ctx context.Context, records any, field string, queriers ...Querier) // Exec raw statement. // Returns last inserted id, rows affected and error. - Exec(ctx context.Context, statement string, args ...interface{}) (int, int, error) + Exec(ctx context.Context, statement string, args ...any) (int, int, error) // MustExec raw statement. // Returns last inserted id, rows affected and error. - MustExec(ctx context.Context, statement string, args ...interface{}) (int, int) + MustExec(ctx context.Context, statement string, args ...any) (int, int) // Transaction performs transaction with given function argument. // Transaction scope/connection is automatically passed using context. @@ -221,7 +221,7 @@ func (r repository) MustCount(ctx context.Context, collection string, queriers . return count } -func (r repository) Find(ctx context.Context, record interface{}, queriers ...Querier) error { +func (r repository) Find(ctx context.Context, record any, queriers ...Querier) error { finish := r.instrumenter.Observe(ctx, "rel-find", "finding a record") defer finish(nil) @@ -234,7 +234,7 @@ func (r repository) Find(ctx context.Context, record interface{}, queriers ...Qu return r.find(cw, doc, query) } -func (r repository) MustFind(ctx context.Context, record interface{}, queriers ...Querier) { +func (r repository) MustFind(ctx context.Context, record any, queriers ...Querier) { must(r.Find(ctx, record, queriers...)) } @@ -261,7 +261,7 @@ func (r repository) find(cw contextWrapper, doc *Document, query Query) error { return nil } -func (r repository) FindAll(ctx context.Context, records interface{}, queriers ...Querier) error { +func (r repository) FindAll(ctx context.Context, records any, queriers ...Querier) error { finish := r.instrumenter.Observe(ctx, "rel-find-all", "finding all records") defer finish(nil) @@ -276,7 +276,7 @@ func (r repository) FindAll(ctx context.Context, records interface{}, queriers . return r.findAll(cw, col, query) } -func (r repository) MustFindAll(ctx context.Context, records interface{}, queriers ...Querier) { +func (r repository) MustFindAll(ctx context.Context, records any, queriers ...Querier) { must(r.FindAll(ctx, records, queriers...)) } @@ -303,7 +303,7 @@ func (r repository) findAll(cw contextWrapper, col *Collection, query Query) err return nil } -func (r repository) FindAndCountAll(ctx context.Context, records interface{}, queriers ...Querier) (int, error) { +func (r repository) FindAndCountAll(ctx context.Context, records any, queriers ...Querier) (int, error) { finish := r.instrumenter.Observe(ctx, "rel-find-and-count-all", "finding all records") defer finish(nil) @@ -322,14 +322,14 @@ func (r repository) FindAndCountAll(ctx context.Context, records interface{}, qu return r.aggregate(cw, r.withDefaultScope(col.meta, query, false), "count", "*") } -func (r repository) MustFindAndCountAll(ctx context.Context, records interface{}, queriers ...Querier) int { +func (r repository) MustFindAndCountAll(ctx context.Context, records any, queriers ...Querier) int { count, err := r.FindAndCountAll(ctx, records, queriers...) must(err) return count } -func (r repository) Insert(ctx context.Context, record interface{}, mutators ...Mutator) error { +func (r repository) Insert(ctx context.Context, record any, mutators ...Mutator) error { finish := r.instrumenter.Observe(ctx, "rel-insert", "inserting a record") defer finish(nil) @@ -392,11 +392,11 @@ func (r repository) insert(cw contextWrapper, doc *Document, mutation Mutation) return nil } -func (r repository) MustInsert(ctx context.Context, record interface{}, mutators ...Mutator) { +func (r repository) MustInsert(ctx context.Context, record any, mutators ...Mutator) { must(r.Insert(ctx, record, mutators...)) } -func (r repository) InsertAll(ctx context.Context, records interface{}, mutators ...Mutator) error { +func (r repository) InsertAll(ctx context.Context, records any, mutators ...Mutator) error { finish := r.instrumenter.Observe(ctx, "rel-insert-all", "inserting multiple records") defer finish(nil) @@ -423,7 +423,7 @@ func (r repository) InsertAll(ctx context.Context, records interface{}, mutators return r.insertAll(cw, col, muts) } -func (r repository) MustInsertAll(ctx context.Context, records interface{}, mutators ...Mutator) { +func (r repository) MustInsertAll(ctx context.Context, records any, mutators ...Mutator) { must(r.InsertAll(ctx, records, mutators...)) } @@ -473,7 +473,7 @@ func (r repository) insertAll(cw contextWrapper, col *Collection, mutation []Mut return nil } -func (r repository) Update(ctx context.Context, record interface{}, mutators ...Mutator) error { +func (r repository) Update(ctx context.Context, record any, mutators ...Mutator) error { finish := r.instrumenter.Observe(ctx, "rel-update", "updating a record") defer finish(nil) @@ -576,7 +576,7 @@ func (r repository) applyMutates(cw contextWrapper, doc *Document, mutation Muta return nil } -func (r repository) MustUpdate(ctx context.Context, record interface{}, mutators ...Mutator) { +func (r repository) MustUpdate(ctx context.Context, record any, mutators ...Mutator) { must(r.Update(ctx, record, mutators...)) } @@ -800,7 +800,7 @@ func (r repository) MustUpdateAny(ctx context.Context, query Query, mutates ...M return updatedCount } -func (r repository) Delete(ctx context.Context, record interface{}, mutators ...Mutator) error { +func (r repository) Delete(ctx context.Context, record any, mutators ...Mutator) error { finish := r.instrumenter.Observe(ctx, "rel-delete", "deleting a record") defer finish(nil) @@ -932,11 +932,11 @@ func (r repository) deleteHasMany(cw contextWrapper, doc *Document) error { return nil } -func (r repository) MustDelete(ctx context.Context, record interface{}, mutators ...Mutator) { +func (r repository) MustDelete(ctx context.Context, record any, mutators ...Mutator) { must(r.Delete(ctx, record, mutators...)) } -func (r repository) DeleteAll(ctx context.Context, records interface{}) error { +func (r repository) DeleteAll(ctx context.Context, records any) error { finish := r.instrumenter.Observe(ctx, "rel-delete-all", "deleting records") defer finish(nil) @@ -957,7 +957,7 @@ func (r repository) DeleteAll(ctx context.Context, records interface{}) error { return err } -func (r repository) MustDeleteAll(ctx context.Context, records interface{}) { +func (r repository) MustDeleteAll(ctx context.Context, records any) { must(r.DeleteAll(ctx, records)) } @@ -1001,7 +1001,7 @@ func (r repository) deleteAny(cw contextWrapper, flag DocumentFlag, query Query) return cw.adapter.Delete(cw.ctx, query) } -func (r repository) Preload(ctx context.Context, records interface{}, field string, queriers ...Querier) error { +func (r repository) Preload(ctx context.Context, records any, field string, queriers ...Querier) error { finish := r.instrumenter.Observe(ctx, "rel-preload", "preloading associations") defer finish(nil) @@ -1075,11 +1075,11 @@ func (r repository) preload(cw contextWrapper, records slice, field string, quer return nil } -func (r repository) MustPreload(ctx context.Context, records interface{}, field string, queriers ...Querier) { +func (r repository) MustPreload(ctx context.Context, records any, field string, queriers ...Querier) { must(r.Preload(ctx, records, field, queriers...)) } -func (r repository) mapPreloadTargets(sl slice, path []string) (map[interface{}][]slice, string, string, reflect.Type, DocumentMeta, bool) { +func (r repository) mapPreloadTargets(sl slice, path []string) (map[any][]slice, string, string, reflect.Type, DocumentMeta, bool) { type frame struct { index int doc *Document @@ -1091,7 +1091,7 @@ func (r repository) mapPreloadTargets(sl slice, path []string) (map[interface{}] keyType reflect.Type meta DocumentMeta loaded = true - mapTarget = make(map[interface{}][]slice) + mapTarget = make(map[any][]slice) stack = make([]frame, sl.Len()) ) @@ -1175,9 +1175,9 @@ func (r repository) mapPreloadTargets(sl slice, path []string) (map[interface{}] return mapTarget, table, keyField, keyType, meta, loaded } -func (r repository) targetIDs(targets map[interface{}][]slice) []interface{} { +func (r repository) targetIDs(targets map[any][]slice) []any { var ( - ids = make([]interface{}, len(targets)) + ids = make([]any, len(targets)) i = 0 ) @@ -1209,14 +1209,14 @@ func (r repository) withDefaultScope(meta DocumentMeta, query Query, preload boo // Exec raw statement. // Returns last inserted id, rows affected and error. -func (r repository) Exec(ctx context.Context, stmt string, args ...interface{}) (int, int, error) { +func (r repository) Exec(ctx context.Context, stmt string, args ...any) (int, int, error) { lastInsertedId, rowsAffected, err := r.Adapter(ctx).Exec(ctx, stmt, args) return int(lastInsertedId), int(rowsAffected), err } // MustExec raw statement. // Returns last inserted id, rows affected and error. -func (r repository) MustExec(ctx context.Context, stmt string, args ...interface{}) (int, int) { +func (r repository) MustExec(ctx context.Context, stmt string, args ...any) (int, int) { lastInsertedId, rowsAffected, err := r.Exec(ctx, stmt, args...) must(err) return lastInsertedId, rowsAffected diff --git a/repository_test.go b/repository_test.go index 57693407..c5b12418 100644 --- a/repository_test.go +++ b/repository_test.go @@ -999,7 +999,7 @@ func TestRepository_Insert_saveHasMany(t *testing.T) { adapter.On("Begin").Return(nil).Once() adapter.On("Insert", From("users"), mock.Anything, OnConflict{}).Return(1, nil).Once() - adapter.On("InsertAll", From("user_roles"), mock.Anything, mock.Anything, OnConflict{}).Return([]interface{}(nil), nil).Once() + adapter.On("InsertAll", From("user_roles"), mock.Anything, mock.Anything, OnConflict{}).Return([]any(nil), nil).Once() adapter.On("Commit").Return(nil).Once() assert.Nil(t, repo.Insert(context.TODO(), &user)) @@ -1059,7 +1059,7 @@ func TestRepository_Insert_saveHasManyError(t *testing.T) { adapter.On("Begin").Return(nil).Once() adapter.On("Insert", From("users"), mock.Anything, OnConflict{}).Return(1, nil).Once() - adapter.On("InsertAll", From("user_roles"), mock.Anything, mock.Anything, OnConflict{}).Return([]interface{}{}, err).Once() + adapter.On("InsertAll", From("user_roles"), mock.Anything, mock.Anything, OnConflict{}).Return([]any{}, err).Once() adapter.On("Rollback").Return(nil).Once() assert.Equal(t, err, repo.Insert(context.TODO(), &user)) @@ -1174,7 +1174,7 @@ func TestRepository_InsertAll(t *testing.T) { } ) - adapter.On("InsertAll", From("users"), mock.Anything, mutates, OnConflict{}).Return([]interface{}{1, 2}, nil).Once() + adapter.On("InsertAll", From("users"), mock.Anything, mutates, OnConflict{}).Return([]any{1, 2}, nil).Once() assert.Nil(t, repo.InsertAll(context.TODO(), &users)) assert.Equal(t, []User{ @@ -1205,7 +1205,7 @@ func TestRepository_InsertAll_compositePrimaryFields(t *testing.T) { } ) - adapter.On("InsertAll", From("user_roles"), mock.Anything, mutates, OnConflict{}).Return([]interface{}{0, 0}, nil).Once() + adapter.On("InsertAll", From("user_roles"), mock.Anything, mutates, OnConflict{}).Return([]any{0, 0}, nil).Once() assert.Nil(t, repo.InsertAll(context.TODO(), &userRoles)) assert.Equal(t, []UserRole{ @@ -1240,7 +1240,7 @@ func TestRepository_InsertAll_ptrElem(t *testing.T) { } ) - adapter.On("InsertAll", From("users"), mock.Anything, mutates, OnConflict{}).Return([]interface{}{1, 2}, nil).Once() + adapter.On("InsertAll", From("users"), mock.Anything, mutates, OnConflict{}).Return([]any{1, 2}, nil).Once() assert.Nil(t, repo.InsertAll(context.TODO(), &users)) assert.Equal(t, []*User{ @@ -1731,7 +1731,7 @@ func TestRepository_Update_saveHasMany(t *testing.T) { adapter.On("Begin").Return(nil).Once() adapter.On("Update", From("users").Where(Eq("id", 10)), "id", mock.Anything).Return(1, nil).Once() adapter.On("Delete", From("user_roles").Where(Eq("user_id", 10))).Return(1, nil).Once() - adapter.On("InsertAll", From("user_roles"), mock.Anything, mock.Anything, OnConflict{}).Return([]interface{}(nil), nil).Once() + adapter.On("InsertAll", From("user_roles"), mock.Anything, mock.Anything, OnConflict{}).Return([]any(nil), nil).Once() adapter.On("Commit").Return(nil).Once() assert.Nil(t, repo.Update(context.TODO(), &user)) @@ -2189,8 +2189,8 @@ func TestRepository_saveHasMany_insert(t *testing.T) { q = Build("emails") ) - adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates, OnConflict{}).Return([]interface{}{2, 3}, nil).Maybe() - adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates, OnConflict{}).Return([]interface{}{2, 3}, nil).Maybe() + adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates, OnConflict{}).Return([]any{2, 3}, nil).Maybe() + adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates, OnConflict{}).Return([]any{2, 3}, nil).Maybe() assert.Nil(t, repo.(*repository).saveHasMany(cw, doc, &mutation, true)) assert.Equal(t, User{ @@ -2227,8 +2227,8 @@ func TestRepository_saveHasMany_insertError(t *testing.T) { err = errors.New("insert all error") ) - adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates, OnConflict{}).Return([]interface{}{}, err).Maybe() - adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates, OnConflict{}).Return([]interface{}{}, err).Maybe() + adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates, OnConflict{}).Return([]any{}, err).Maybe() + adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates, OnConflict{}).Return([]any{}, err).Maybe() assert.Equal(t, err, repo.(*repository).saveHasMany(cw, doc, &mutation, true)) @@ -2264,7 +2264,7 @@ func TestRepository_saveHasMany_update(t *testing.T) { q = Build("emails") ) - mutation.SetDeletedIDs("emails", []interface{}{2}) + mutation.SetDeletedIDs("emails", []any{2}) adapter.On("Delete", q.Where(Eq("user_id", 1).AndIn("id", 2))).Return(1, nil).Once() adapter.On("Update", q.Where(Eq("id", 1).AndEq("user_id", 1)), "id", mutates[0]).Return(1, nil).Once() @@ -2303,7 +2303,7 @@ func TestRepository_saveHasMany_updateInconsistentReferences(t *testing.T) { ) ) - mutation.SetDeletedIDs("emails", []interface{}{}) + mutation.SetDeletedIDs("emails", []any{}) assert.Equal(t, ConstraintError{ Key: "user_id", @@ -2340,7 +2340,7 @@ func TestRepository_saveHasMany_updateError(t *testing.T) { err = errors.New("update error") ) - mutation.SetDeletedIDs("emails", []interface{}{}) + mutation.SetDeletedIDs("emails", []any{}) adapter.On("Update", q.Where(Eq("id", 1).AndEq("user_id", 1)), "id", mutates[0]).Return(0, err).Once() @@ -2377,8 +2377,8 @@ func TestRepository_saveHasMany_updateWithInsert(t *testing.T) { ) adapter.On("Update", q.Where(Eq("id", 1).AndEq("user_id", 1)), "id", mutates[0]).Return(1, nil).Once() - adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates[1:], OnConflict{}).Return([]interface{}{2}, nil).Maybe() - adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates[1:], OnConflict{}).Return([]interface{}{2}, nil).Maybe() + adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates[1:], OnConflict{}).Return([]any{2}, nil).Maybe() + adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates[1:], OnConflict{}).Return([]any{2}, nil).Maybe() assert.Nil(t, repo.(*repository).saveHasMany(cw, doc, &mutation, false)) assert.Equal(t, User{ @@ -2418,11 +2418,11 @@ func TestRepository_saveHasMany_updateWithReorderInsert(t *testing.T) { Apply(NewDocument(&user.Emails[0]), Set("email", "new@gmail.com")), Apply(NewDocument(&user.Emails[1]), Set("email", "update@gmail.com")), ) - mutation.SetDeletedIDs("emails", []interface{}{}) + mutation.SetDeletedIDs("emails", []any{}) adapter.On("Update", q.Where(Eq("id", 1).AndEq("user_id", 1)), "id", mutates[0]).Return(1, nil).Once() - adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates[1:], OnConflict{}).Return([]interface{}{2}, nil).Maybe() - adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates[1:], OnConflict{}).Return([]interface{}{2}, nil).Maybe() + adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates[1:], OnConflict{}).Return([]any{2}, nil).Maybe() + adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates[1:], OnConflict{}).Return([]any{2}, nil).Maybe() assert.Nil(t, repo.(*repository).saveHasMany(cw, doc, &mutation, false)) assert.Equal(t, User{ @@ -2467,8 +2467,8 @@ func TestRepository_saveHasMany_deleteWithInsert(t *testing.T) { ) adapter.On("Delete", q.Where(Eq("user_id", 1).AndIn("id", 1, 2))).Return(1, nil).Once() - adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates, OnConflict{}).Return([]interface{}{3, 4, 5}, nil).Maybe() - adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates, OnConflict{}).Return([]interface{}{3, 4, 5}, nil).Maybe() + adapter.On("InsertAll", q, []string{"email", "user_id"}, mutates, OnConflict{}).Return([]any{3, 4, 5}, nil).Maybe() + adapter.On("InsertAll", q, []string{"user_id", "email"}, mutates, OnConflict{}).Return([]any{3, 4, 5}, nil).Maybe() assert.Nil(t, repo.(*repository).saveHasMany(cw, doc, &mutation, false)) assert.Equal(t, User{ @@ -2540,7 +2540,7 @@ func TestRepository_saveHasMany_replace(t *testing.T) { ) adapter.On("Delete", q.Where(Eq("user_id", 1))).Return(1, nil).Once() - adapter.On("InsertAll", q, mock.Anything, mutates, OnConflict{}).Return([]interface{}{3, 4, 5}, nil).Once() + adapter.On("InsertAll", q, mock.Anything, mutates, OnConflict{}).Return([]any{3, 4, 5}, nil).Once() assert.Nil(t, repo.(*repository).saveHasMany(cw, doc, &mutation, false)) assert.Equal(t, User{ @@ -3983,8 +3983,8 @@ func TestRepository_Exec(t *testing.T) { adapter = &testAdapter{} repo = New(adapter) query = "UPDATE users SET something = ? WHERE something2 = ?;" - args = []interface{}{3, "sdfds"} - rets = []interface{}{1, 2, nil} + args = []any{3, "sdfds"} + rets = []any{1, 2, nil} ) adapter.On("Exec", context.TODO(), query, args).Return(rets...).Once() @@ -4002,8 +4002,8 @@ func TestRepository_MustExec(t *testing.T) { adapter = &testAdapter{} repo = New(adapter) query = "UPDATE users SET something = ? WHERE something2 = ?;" - args = []interface{}{3, "sdfds"} - rets = []interface{}{1, 2, nil} + args = []any{3, "sdfds"} + rets = []any{1, 2, nil} ) adapter.On("Exec", context.TODO(), query, args).Return(rets...).Once() diff --git a/schema_options.go b/schema_options.go index c6c72f1c..5ffe6e56 100644 --- a/schema_options.go +++ b/schema_options.go @@ -83,7 +83,7 @@ func (s Scale) applyColumn(column *Column) { } type defaultValue struct { - value interface{} + value any } func (d defaultValue) applyColumn(column *Column) { @@ -91,7 +91,7 @@ func (d defaultValue) applyColumn(column *Column) { } // Default allows to set a default value on the column.). -func Default(def interface{}) ColumnOption { +func Default(def any) ColumnOption { return defaultValue{value: def} } diff --git a/sql_query.go b/sql_query.go index 8922c312..43860207 100644 --- a/sql_query.go +++ b/sql_query.go @@ -5,7 +5,7 @@ import "strings" // SQLQuery allows querying using native query supported by database. type SQLQuery struct { Statement string - Values []interface{} + Values []any } // Build Raw Query. @@ -29,7 +29,7 @@ func (sq SQLQuery) String() string { } // SQL Query. -func SQL(statement string, values ...interface{}) SQLQuery { +func SQL(statement string, values ...any) SQLQuery { return SQLQuery{ Statement: statement, Values: values, diff --git a/sql_query_test.go b/sql_query_test.go index 0bd5c156..fe8de0ac 100644 --- a/sql_query_test.go +++ b/sql_query_test.go @@ -14,6 +14,6 @@ func TestSQLQuery(t *testing.T) { assert.Equal(t, rel.SQLQuery{ Statement: "SELECT * FROM `users` WHERE id=?;", - Values: []interface{}{1}, + Values: []any{1}, }, rel.SQL("SELECT * FROM `users` WHERE id=?;", 1)) } diff --git a/structset.go b/structset.go index 26b6d5bc..944ef384 100644 --- a/structset.go +++ b/structset.go @@ -58,7 +58,7 @@ func (s Structset) Apply(doc *Document, mut *Mutation) { } } -func (s Structset) set(doc *Document, mut *Mutation, field string, value interface{}, force bool) { +func (s Structset) set(doc *Document, mut *Mutation, field string, value any, force bool) { if (force || doc.v != s.doc.v) && !doc.SetValue(field, value) { panic(fmt.Sprint("rel: cannot assign ", value, " as ", field, " into ", doc.Table())) } @@ -133,6 +133,6 @@ func newStructset(doc *Document, skipZero bool) Structset { } // NewStructset from a struct. -func NewStructset(record interface{}, skipZero bool) Structset { +func NewStructset(record any, skipZero bool) Structset { return newStructset(NewDocument(record), skipZero) } diff --git a/util.go b/util.go index 08f26be6..e4a78b32 100644 --- a/util.go +++ b/util.go @@ -8,7 +8,7 @@ import ( "strings" ) -func indirectInterface(rv reflect.Value) interface{} { +func indirectInterface(rv reflect.Value) any { if rv.Kind() == reflect.Ptr { if rv.IsNil() { return nil @@ -39,7 +39,7 @@ type isZeroer interface { } // isZero shallowly check wether a field in struct is zero or not -func isZero(value interface{}) bool { +func isZero(value any) bool { var ( zero bool ) @@ -162,7 +162,7 @@ func setConvertValue(ft reflect.Type, fv reflect.Value, rt reflect.Type, rv refl return true } -func fmtiface(v interface{}) string { +func fmtiface(v any) string { if str, ok := v.(string); ok { return "\"" + str + "\"" } @@ -170,7 +170,7 @@ func fmtiface(v interface{}) string { return fmt.Sprint(v) } -func fmtifaces(v []interface{}) string { +func fmtifaces(v []any) string { var str strings.Builder for i := range v { if i > 0 { @@ -193,7 +193,8 @@ func encodeIndices(indices []int) string { } // Get field by index and init pointers on path if flag is true -// modified from: https://cs.opensource.google/go/go/+/refs/tags/go1.17.7:src/reflect/value.go;l=1228-1245;bpv +// +// modified from: https://cs.opensource.google/go/go/+/refs/tags/go1.17.7:src/reflect/value.go;l=1228-1245;bpv func reflectValueFieldByIndex(rv reflect.Value, index []int, init bool) reflect.Value { if len(index) == 1 { return rv.Field(index[0]) diff --git a/util_test.go b/util_test.go index 67605d77..5fa1b6d7 100644 --- a/util_test.go +++ b/util_test.go @@ -16,7 +16,7 @@ func TestMust(t *testing.T) { } func TestIsZero(t *testing.T) { - tests := []interface{}{ + tests := []any{ nil, false, "", From 98b9c9a9b70c2b9f4a3d65c007ca2918fbc3234e Mon Sep 17 00:00:00 2001 From: Fs02 Date: Mon, 10 Oct 2022 08:19:37 +0900 Subject: [PATCH 2/9] rename file --- any_nogo1.18.go => any_notgo1.18.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename any_nogo1.18.go => any_notgo1.18.go (100%) diff --git a/any_nogo1.18.go b/any_notgo1.18.go similarity index 100% rename from any_nogo1.18.go rename to any_notgo1.18.go From 5b63ccb79a74f96bdbe34eb5b2a7edb9321fdb6b Mon Sep 17 00:00:00 2001 From: Fs02 Date: Mon, 10 Oct 2022 08:38:00 +0900 Subject: [PATCH 3/9] only test in ubuntu to speed up test --- .github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b9d46d37..c8a42621 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,7 +12,7 @@ jobs: name: Unit Test strategy: matrix: - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-latest] go: [1.12, 1.13, 1.14, 1.15, 1.16] runs-on: ${{ matrix.os }} steps: @@ -30,7 +30,7 @@ jobs: SQLITE3_DATABASE: cli-test.db strategy: matrix: - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-latest] go: [1.12, 1.13, 1.14, 1.15, 1.16] runs-on: ${{ matrix.os }} steps: From 28bc5787b7d97c28b131ed458e9079bbc47bdd90 Mon Sep 17 00:00:00 2001 From: Fs02 Date: Mon, 10 Oct 2022 08:48:32 +0900 Subject: [PATCH 4/9] fix test was not run on different go version --- .github/workflows/release.yml | 2 +- .github/workflows/test.yml | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2bec73cd..1e3d918b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ jobs: with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: go-version: 1.19 - name: Run GoReleaser diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 289520b2..a367e3f3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,9 +17,9 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Set up Go 1.x - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: - go-version: ^${{ matrix.go }} + go-version: ${{ matrix.go }} - name: Check out code into the Go module directory uses: actions/checkout@v2 - run: go test -race ./... @@ -35,9 +35,9 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Set up Go 1.x - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 with: - go-version: ^${{ matrix.go }} + go-version: ${{ matrix.go }} - name: Check out code into the Go module directory uses: actions/checkout@v2 - run: go install ./cmd/rel @@ -60,7 +60,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Set up Go 1.x - uses: actions/setup-go@v2 + uses: actions/setup-go@v3 - name: Check out code into the Go module directory uses: actions/checkout@v2 with: From ce0fae8e5c3f5f8cca4a37871572ff2b022f27b5 Mon Sep 17 00:00:00 2001 From: Fs02 Date: Mon, 10 Oct 2022 12:55:23 +0900 Subject: [PATCH 5/9] run go mod tidy --- .github/workflows/test.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a367e3f3..9d979ea1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,7 +22,9 @@ jobs: go-version: ${{ matrix.go }} - name: Check out code into the Go module directory uses: actions/checkout@v2 - - run: go test -race ./... + - run: | + go mod tidy + go test -race ./... cli: name: CLI @@ -65,6 +67,8 @@ jobs: uses: actions/checkout@v2 with: fetch-depth: 2 - - run: go test -race -tags=all -coverprofile=coverage.txt -covermode=atomic ./... + - run: | + go mod tidy + go test -race -tags=all -coverprofile=coverage.txt -covermode=atomic ./... - name: Codecov uses: codecov/codecov-action@v1 From dd3050f11b816dae68ae926fe646f1f87eb0aec8 Mon Sep 17 00:00:00 2001 From: Fs02 Date: Mon, 10 Oct 2022 17:09:06 +0900 Subject: [PATCH 6/9] fix build flag --- any_notgo1.18.go | 4 ++-- any_notgo1.18_test.go | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 any_notgo1.18_test.go diff --git a/any_notgo1.18.go b/any_notgo1.18.go index ad0496a8..02bde3bd 100644 --- a/any_notgo1.18.go +++ b/any_notgo1.18.go @@ -1,5 +1,5 @@ -//go:build !go1.18 -// +build !go1.18 +//go:build !go118 +// +build !go118 package rel diff --git a/any_notgo1.18_test.go b/any_notgo1.18_test.go new file mode 100644 index 00000000..c4b01da6 --- /dev/null +++ b/any_notgo1.18_test.go @@ -0,0 +1,6 @@ +//go:build !go118 +// +build !go118 + +package rel_test + +type any = interface{} From 50142dab25bbabbd8ee7fb78c5a4ea2a4d7ba2b5 Mon Sep 17 00:00:00 2001 From: Fs02 Date: Mon, 10 Oct 2022 17:53:30 +0900 Subject: [PATCH 7/9] refactor fmtiface to fmtAny --- filter_query.go | 6 +++--- iterator.go | 4 ++-- map.go | 2 +- mutation.go | 6 +++--- sql_query.go | 2 +- util.go | 6 +++--- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/filter_query.go b/filter_query.go index 955cc77b..63cb2e5f 100644 --- a/filter_query.go +++ b/filter_query.go @@ -114,7 +114,7 @@ func (fq FilterQuery) String() string { builder.WriteByte('"') builder.WriteString(fq.Field) builder.WriteString("\", ") - builder.WriteString(fmtiface(fq.Value)) + builder.WriteString(fmtAny(fq.Value)) case FilterNilOp, FilterNotNilOp, FilterLikeOp, FilterNotLikeOp: builder.WriteByte('"') builder.WriteString(fq.Field) @@ -123,7 +123,7 @@ func (fq FilterQuery) String() string { builder.WriteByte('"') builder.WriteString(fq.Field) builder.WriteString("\", ") - builder.WriteString(fmtifaces(fq.Value.([]any))) + builder.WriteString(fmtAnys(fq.Value.([]any))) case FilterFragmentOp: v := fq.Value.([]any) builder.WriteByte('"') @@ -132,7 +132,7 @@ func (fq FilterQuery) String() string { if len(v) > 0 { builder.WriteString(", ") - builder.WriteString(fmtifaces(v)) + builder.WriteString(fmtAnys(v)) } } diff --git a/iterator.go b/iterator.go index 27e4a406..c798712e 100644 --- a/iterator.go +++ b/iterator.go @@ -41,7 +41,7 @@ func (s start) apply(i *iterator) { // String representation. func (s start) String() string { - return fmt.Sprintf("rel.Start(%s)", fmtifaces(s)) + return fmt.Sprintf("rel.Start(%s)", fmtAnys(s)) } // Start specifies the primary value to start from (inclusive). @@ -57,7 +57,7 @@ func (f finish) apply(i *iterator) { // String representation. func (f finish) String() string { - return fmt.Sprintf("rel.Finish(%s)", fmtifaces(f)) + return fmt.Sprintf("rel.Finish(%s)", fmtAnys(f)) } // Finish specifies the primary value to finish at (inclusive). diff --git a/map.go b/map.go index ca807495..617a8554 100644 --- a/map.go +++ b/map.go @@ -94,7 +94,7 @@ func (m Map) String() string { } builder.WriteString("}") default: - builder.WriteString(fmtiface(v)) // TODO: use compact struct print (reltest.csprint) + builder.WriteString(fmtAny(v)) // TODO: use compact struct print (reltest.csprint) } } builder.WriteString("}") diff --git a/mutation.go b/mutation.go index 7d31e113..9b967df1 100644 --- a/mutation.go +++ b/mutation.go @@ -169,11 +169,11 @@ func (m Mutate) String() string { str := "≤Invalid Mutator>" switch m.Type { case ChangeSetOp: - str = fmt.Sprintf("rel.Set(\"%s\", %s)", m.Field, fmtiface(m.Value)) + str = fmt.Sprintf("rel.Set(\"%s\", %s)", m.Field, fmtAny(m.Value)) case ChangeIncOp: - str = fmt.Sprintf("rel.IncBy(\"%s\", %s)", m.Field, fmtiface(m.Value)) + str = fmt.Sprintf("rel.IncBy(\"%s\", %s)", m.Field, fmtAny(m.Value)) case ChangeFragmentOp: - str = fmt.Sprintf("rel.SetFragment(\"%s\", %s)", m.Field, fmtifaces(m.Value.([]any))) + str = fmt.Sprintf("rel.SetFragment(\"%s\", %s)", m.Field, fmtAnys(m.Value.([]any))) } return str diff --git a/sql_query.go b/sql_query.go index 43860207..69d369be 100644 --- a/sql_query.go +++ b/sql_query.go @@ -21,7 +21,7 @@ func (sq SQLQuery) String() string { if len(sq.Values) != 0 { builder.WriteString(", ") - builder.WriteString(fmtifaces(sq.Values)) + builder.WriteString(fmtAnys(sq.Values)) } builder.WriteString(")") diff --git a/util.go b/util.go index e4a78b32..dbcd0bda 100644 --- a/util.go +++ b/util.go @@ -162,7 +162,7 @@ func setConvertValue(ft reflect.Type, fv reflect.Value, rt reflect.Type, rv refl return true } -func fmtiface(v any) string { +func fmtAny(v any) string { if str, ok := v.(string); ok { return "\"" + str + "\"" } @@ -170,13 +170,13 @@ func fmtiface(v any) string { return fmt.Sprint(v) } -func fmtifaces(v []any) string { +func fmtAnys(v []any) string { var str strings.Builder for i := range v { if i > 0 { str.WriteString(", ") } - str.WriteString(fmtiface(v[i])) + str.WriteString(fmtAny(v[i])) } return str.String() From 39bdc46ca08383a5c0bb121936537f6b4310e353 Mon Sep 17 00:00:00 2001 From: Fs02 Date: Mon, 10 Oct 2022 17:54:26 +0900 Subject: [PATCH 8/9] revert --- .github/workflows/test.yml | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index be730964..6cae2738 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,9 +22,7 @@ jobs: go-version: ${{ matrix.go }} - name: Check out code into the Go module directory uses: actions/checkout@v2 - - run: | - go mod tidy - go test -race ./... + - run: go test -race ./... cli: name: CLI @@ -67,8 +65,6 @@ jobs: uses: actions/checkout@v2 with: fetch-depth: 2 - - run: | - go mod tidy - go test -race -tags=all -coverprofile=coverage.txt -covermode=atomic ./... + - run: go test -race -tags=all -coverprofile=coverage.txt -covermode=atomic ./... - name: Codecov uses: codecov/codecov-action@v1 From df47b287d918ca4ab6c6d4e789b921a063753cf3 Mon Sep 17 00:00:00 2001 From: Surya Asriadie Date: Mon, 10 Oct 2022 18:01:05 +0900 Subject: [PATCH 9/9] Update FUNDING.yml --- .github/FUNDING.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 72aba74d..99256130 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,2 +1 @@ github: Fs02 -open_collective: rel