From f2d6f9eaa20ce5141d1983baa9538d9d509b2ee7 Mon Sep 17 00:00:00 2001 From: Surawich Laprattanatrai Date: Sun, 8 Feb 2026 16:16:17 +0700 Subject: [PATCH] Upgrade mongo-driver to v2 --- .golangci.yml | 11 +- README.md | 14 +-- examples/complex-query/main.go | 21 +++- examples/complex-query/user.go | 16 +-- .../complex-query/user_comparator_repo.go | 109 ++++++++++-------- examples/complex-query/user_other_repo.go | 40 ++++--- .../interf/user.go | 10 +- .../repo/user_repo.go | 20 ++-- examples/cross-package/user.go | 11 ++ examples/cross_package/user.go | 11 -- examples/getting-started/main.go | 12 +- examples/getting-started/user.go | 12 +- examples/getting-started/user_repo.go | 62 +++++----- go.mod | 24 ++-- go.sum | 40 +++---- internal/codegen/builder_test.go | 14 +-- internal/codegen/struct_test.go | 2 +- internal/mongo/common.go | 4 +- internal/mongo/generator.go | 7 +- internal/mongo/generator_test.go | 9 +- internal/teststub/user.go | 66 +++++------ internal/teststub/user_repo_integration.go | 4 +- internal/testutils/stub_provider.go | 6 +- main.go | 6 +- test/generator_test_expected.txt | 9 +- 25 files changed, 282 insertions(+), 258 deletions(-) rename examples/{cross_package => cross-package}/interf/user.go (82%) rename examples/{cross_package => cross-package}/repo/user_repo.go (73%) create mode 100644 examples/cross-package/user.go delete mode 100644 examples/cross_package/user.go diff --git a/.golangci.yml b/.golangci.yml index d1d63d8..d0d9255 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,10 +1,11 @@ +version: "2" linters: enable: + - err113 - errname - errorlint - - err113 - lll - - stylecheck -linters-settings: - lll: - tab-width: 4 + - staticcheck + settings: + lll: + tab-width: 4 diff --git a/README.md b/README.md index 0f8f44e..6af0231 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ type UserRepository interface { // display name. If there is a user matches the query, it will return true. // Error will be returned only when error occurs while accessing the // database. - UpdateDisplayNameByID(ctx context.Context, displayName string, id primitive.ObjectID) (bool, error) + UpdateDisplayNameByID(ctx context.Context, displayName string, id bson.ObjectID) (bool, error) // DeleteByCity deletes users that have `city` value match the parameter // and returns the match count. The error will be returned only when an @@ -123,7 +123,7 @@ A `Find` operation also has two modes like `Insert` operation: single-entity and ```go // FindByID gets a single document by ID -FindByID(ctx context.Context, id primitive.ObjectID) (*Model, error) +FindByID(ctx context.Context, id bson.ObjectID) (*Model, error) // FindByCity gets all documents that match city parameter FindByCity(ctx context.Context, city string) ([]*Model, error) @@ -169,7 +169,7 @@ This type of update is for changing the whole model, replacing all the fields ex ```go // UpdateByID updates a single document by ID -UpdateByID(ctx context.Context, model *Model, id primitive.ObjectID) (bool, error) +UpdateByID(ctx context.Context, model *Model, id bson.ObjectID) (bool, error) ``` 2. Fields-type update @@ -180,7 +180,7 @@ This type of update is for changing only some fields in the model. To write this // UpdateDisplayNameAndCityByID updates a single document with a new display name and // city by ID UpdateDisplayNameAndCityByID(ctx context.Context, displayName string, city string, - id primitive.ObjectID) (bool, error) + id bson.ObjectID) (bool, error) // UpdateGenderByCity updates Gender field of documents with matching city parameter UpdateGenderByCity(ctx context.Context, gender Gender, city string) (int, error) @@ -191,10 +191,10 @@ The update operator will be default to `$set` operator. In case that you want to ```go // UpdateConsentHistoryPushByID appends consentHistory to the ConsentHistory field UpdateConsentHistoryPushByID(ctx context.Context, consentHistory ConsentHistory, - id primitive.ObjectID) (bool, error) + id bson.ObjectID) (bool, error) // UpdateAgeIncByID increments age value by `incAge` -UpdateAgeIncByID(ctx context.Context, incAge int, id primitive.ObjectID) (bool, error) +UpdateAgeIncByID(ctx context.Context, incAge int, id bson.ObjectID) (bool, error) ``` For all types of updates, repogen determines a single-entity operation or a multiple-entity by checking the first return value. If it is of type `bool`, the method will be single-entity operation. If it is of type `int`, the method will be multiple-entity operation. For single-entity operation, the method returns true if there is a matching document. For multiple-entity operation, the integer return shows the number of matched documents. @@ -207,7 +207,7 @@ A `Delete` operation is the very similar to `Find` operation. It has two modes. ```go // DeleteByID deletes a single document by ID -DeleteByID(ctx context.Context, id primitive.ObjectID) (bool, error) +DeleteByID(ctx context.Context, id bson.ObjectID) (bool, error) // DeleteByCity deletes all documents that match city parameter DeleteByCity(ctx context.Context, city string) (int, error) diff --git a/examples/complex-query/main.go b/examples/complex-query/main.go index 2f69028..be3c6c5 100644 --- a/examples/complex-query/main.go +++ b/examples/complex-query/main.go @@ -4,8 +4,8 @@ import ( "context" "fmt" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Replace these values with your own connection option. This connection option is hard-coded for easy @@ -23,7 +23,7 @@ var ( func init() { // create a connection to the database - client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(connectionString)) + client, err := mongo.Connect(options.Client().ApplyURI(connectionString)) if err != nil { panic(err) } @@ -37,10 +37,11 @@ func init() { func main() { demonstrateFindByExists() demonstrateFindByNotExists() + demonstrateFindByContactEmail() } // demonstrateFindByExists shows how find method in repogen works. It receives -// query parameters through method arguments and returns matched result +// query parameters through method arguments and returns matched result. func demonstrateFindByExists() { users, err := userComparatorRepository.FindByContactExists(context.Background()) if err != nil { @@ -61,3 +62,15 @@ func demonstrateFindByNotExists() { fmt.Printf("FindByNotExists: found users = %+v\n", users) } + +// demonstrateFindByContactEmail shows how find method in repogen works. It +// receives query parameters through method arguments and returns matched +// result. +func demonstrateFindByContactEmail() { + users, err := userOtherRepository.FindByContactEmail(context.Background(), "sunboyy@gmail.com") + if err != nil { + panic(err) + } + + fmt.Printf("FindByContactEmail: found users = %+v\n", users) +} diff --git a/examples/complex-query/user.go b/examples/complex-query/user.go index 5b80fcf..627a71d 100644 --- a/examples/complex-query/user.go +++ b/examples/complex-query/user.go @@ -3,7 +3,7 @@ package main import ( "context" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/v2/bson" ) type Gender string @@ -14,13 +14,13 @@ const ( ) type UserModel struct { - ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` - Username string `bson:"username" json:"username"` - Gender Gender `bson:"gender" json:"gender"` - Age int `bson:"age" json:"age"` - City string `bson:"city" json:"city"` - Contact *UserContactModel `bson:"contact,omitempty" json:"contact"` - Banned bool `bson:"banned" json:"banned"` + ID bson.ObjectID `bson:"_id,omitempty" json:"id"` + Username string `bson:"username" json:"username"` + Gender Gender `bson:"gender" json:"gender"` + Age int `bson:"age" json:"age"` + City string `bson:"city" json:"city"` + Contact *UserContactModel `bson:"contact,omitempty" json:"contact"` + Banned bool `bson:"banned" json:"banned"` } type UserContactModel struct { diff --git a/examples/complex-query/user_comparator_repo.go b/examples/complex-query/user_comparator_repo.go index 56ca6bf..440881f 100644 --- a/examples/complex-query/user_comparator_repo.go +++ b/examples/complex-query/user_comparator_repo.go @@ -4,12 +4,12 @@ package main import ( "context" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" ) -func NewUserComparatorRepository(collection *mongo.Collection) UserComparatorRepository { +func NewUserComparatorRepository(collection *mongo.Collection) *UserComparatorRepositoryMongo { return &UserComparatorRepositoryMongo{ collection: collection, } @@ -19,22 +19,31 @@ type UserComparatorRepositoryMongo struct { collection *mongo.Collection } -func (r *UserComparatorRepositoryMongo) FindByUsername(arg0 context.Context, arg1 string) (*UserModel, error) { - var entity UserModel - if err := r.collection.FindOne(arg0, bson.M{ - "username": arg1, - }, options.FindOne().SetSort(bson.M{})).Decode(&entity); err != nil { +func (r *UserComparatorRepositoryMongo) FindByAgeBetween(arg0 context.Context, arg1 int, arg2 int) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) + cursor, err := r.collection.Find(arg0, bson.M{ + "age": bson.M{ + "$gte": arg1, + "$lte": arg2, + }, + }, findOptions) + if err != nil { return nil, err } - return &entity, nil + entities := []*UserModel{} + if err := cursor.All(arg0, &entities); err != nil { + return nil, err + } + return entities, nil } func (r *UserComparatorRepositoryMongo) FindByAgeGreaterThan(arg0 context.Context, arg1 int) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "age": bson.M{ "$gt": arg1, }, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -46,11 +55,12 @@ func (r *UserComparatorRepositoryMongo) FindByAgeGreaterThan(arg0 context.Contex } func (r *UserComparatorRepositoryMongo) FindByAgeGreaterThanEqual(arg0 context.Context, arg1 int) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "age": bson.M{ "$gte": arg1, }, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -62,11 +72,12 @@ func (r *UserComparatorRepositoryMongo) FindByAgeGreaterThanEqual(arg0 context.C } func (r *UserComparatorRepositoryMongo) FindByAgeLessThan(arg0 context.Context, arg1 int) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "age": bson.M{ "$lt": arg1, }, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -78,11 +89,12 @@ func (r *UserComparatorRepositoryMongo) FindByAgeLessThan(arg0 context.Context, } func (r *UserComparatorRepositoryMongo) FindByAgeLessThanEqual(arg0 context.Context, arg1 int) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "age": bson.M{ "$lte": arg1, }, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -93,13 +105,11 @@ func (r *UserComparatorRepositoryMongo) FindByAgeLessThanEqual(arg0 context.Cont return entities, nil } -func (r *UserComparatorRepositoryMongo) FindByAgeBetween(arg0 context.Context, arg1 int, arg2 int) ([]*UserModel, error) { +func (r *UserComparatorRepositoryMongo) FindByBannedFalse(arg0 context.Context) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ - "age": bson.M{ - "$gte": arg1, - "$lte": arg2, - }, - }, options.Find().SetSort(bson.M{})) + "banned": false, + }, findOptions) if err != nil { return nil, err } @@ -110,12 +120,11 @@ func (r *UserComparatorRepositoryMongo) FindByAgeBetween(arg0 context.Context, a return entities, nil } -func (r *UserComparatorRepositoryMongo) FindByCityNot(arg0 context.Context, arg1 string) ([]*UserModel, error) { +func (r *UserComparatorRepositoryMongo) FindByBannedTrue(arg0 context.Context) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ - "city": bson.M{ - "$ne": arg1, - }, - }, options.Find().SetSort(bson.M{})) + "banned": true, + }, findOptions) if err != nil { return nil, err } @@ -127,11 +136,12 @@ func (r *UserComparatorRepositoryMongo) FindByCityNot(arg0 context.Context, arg1 } func (r *UserComparatorRepositoryMongo) FindByCityIn(arg0 context.Context, arg1 []string) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "city": bson.M{ "$in": arg1, }, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -142,26 +152,13 @@ func (r *UserComparatorRepositoryMongo) FindByCityIn(arg0 context.Context, arg1 return entities, nil } -func (r *UserComparatorRepositoryMongo) FindByCityNotIn(arg0 context.Context, arg1 []string) ([]*UserModel, error) { +func (r *UserComparatorRepositoryMongo) FindByCityNot(arg0 context.Context, arg1 string) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "city": bson.M{ - "$nin": arg1, + "$ne": arg1, }, - }, options.Find().SetSort(bson.M{})) - if err != nil { - return nil, err - } - entities := []*UserModel{} - if err := cursor.All(arg0, &entities); err != nil { - return nil, err - } - return entities, nil -} - -func (r *UserComparatorRepositoryMongo) FindByBannedTrue(arg0 context.Context) ([]*UserModel, error) { - cursor, err := r.collection.Find(arg0, bson.M{ - "banned": true, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -172,10 +169,13 @@ func (r *UserComparatorRepositoryMongo) FindByBannedTrue(arg0 context.Context) ( return entities, nil } -func (r *UserComparatorRepositoryMongo) FindByBannedFalse(arg0 context.Context) ([]*UserModel, error) { +func (r *UserComparatorRepositoryMongo) FindByCityNotIn(arg0 context.Context, arg1 []string) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ - "banned": false, - }, options.Find().SetSort(bson.M{})) + "city": bson.M{ + "$nin": arg1, + }, + }, findOptions) if err != nil { return nil, err } @@ -187,24 +187,37 @@ func (r *UserComparatorRepositoryMongo) FindByBannedFalse(arg0 context.Context) } func (r *UserComparatorRepositoryMongo) FindByContactExists(arg0 context.Context) (*UserModel, error) { + findOptions := options.FindOne().SetSort(bson.M{}) var entity UserModel if err := r.collection.FindOne(arg0, bson.M{ "contact": bson.M{ "$exists": 1, }, - }, options.FindOne().SetSort(bson.M{})).Decode(&entity); err != nil { + }, findOptions).Decode(&entity); err != nil { return nil, err } return &entity, nil } func (r *UserComparatorRepositoryMongo) FindByContactNotExists(arg0 context.Context) (*UserModel, error) { + findOptions := options.FindOne().SetSort(bson.M{}) var entity UserModel if err := r.collection.FindOne(arg0, bson.M{ "contact": bson.M{ "$exists": 0, }, - }, options.FindOne().SetSort(bson.M{})).Decode(&entity); err != nil { + }, findOptions).Decode(&entity); err != nil { + return nil, err + } + return &entity, nil +} + +func (r *UserComparatorRepositoryMongo) FindByUsername(arg0 context.Context, arg1 string) (*UserModel, error) { + findOptions := options.FindOne().SetSort(bson.M{}) + var entity UserModel + if err := r.collection.FindOne(arg0, bson.M{ + "username": arg1, + }, findOptions).Decode(&entity); err != nil { return nil, err } return &entity, nil diff --git a/examples/complex-query/user_other_repo.go b/examples/complex-query/user_other_repo.go index 69f1e18..a11766f 100644 --- a/examples/complex-query/user_other_repo.go +++ b/examples/complex-query/user_other_repo.go @@ -4,12 +4,12 @@ package main import ( "context" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" ) -func NewUserOtherRepository(collection *mongo.Collection) UserOtherRepository { +func NewUserOtherRepository(collection *mongo.Collection) *UserOtherRepositoryMongo { return &UserOtherRepositoryMongo{ collection: collection, } @@ -19,17 +19,8 @@ type UserOtherRepositoryMongo struct { collection *mongo.Collection } -func (r *UserOtherRepositoryMongo) FindByContactEmail(arg0 context.Context, arg1 string) (*UserModel, error) { - var entity UserModel - if err := r.collection.FindOne(arg0, bson.M{ - "contact.email": arg1, - }, options.FindOne().SetSort(bson.M{})).Decode(&entity); err != nil { - return nil, err - } - return &entity, nil -} - func (r *UserOtherRepositoryMongo) FindByAgeAndCity(arg0 context.Context, arg1 int, arg2 string) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "$and": []bson.M{ { @@ -39,7 +30,7 @@ func (r *UserOtherRepositoryMongo) FindByAgeAndCity(arg0 context.Context, arg1 i "city": arg2, }, }, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -50,7 +41,19 @@ func (r *UserOtherRepositoryMongo) FindByAgeAndCity(arg0 context.Context, arg1 i return entities, nil } +func (r *UserOtherRepositoryMongo) FindByContactEmail(arg0 context.Context, arg1 string) (*UserModel, error) { + findOptions := options.FindOne().SetSort(bson.M{}) + var entity UserModel + if err := r.collection.FindOne(arg0, bson.M{ + "contact.email": arg1, + }, findOptions).Decode(&entity); err != nil { + return nil, err + } + return &entity, nil +} + func (r *UserOtherRepositoryMongo) FindByGenderOrAgeGreaterThan(arg0 context.Context, arg1 Gender, arg2 int) ([]*UserModel, error) { + findOptions := options.Find().SetSort(bson.M{}) cursor, err := r.collection.Find(arg0, bson.M{ "$or": []bson.M{ { @@ -62,7 +65,7 @@ func (r *UserOtherRepositoryMongo) FindByGenderOrAgeGreaterThan(arg0 context.Con }, }, }, - }, options.Find().SetSort(bson.M{})) + }, findOptions) if err != nil { return nil, err } @@ -74,9 +77,10 @@ func (r *UserOtherRepositoryMongo) FindByGenderOrAgeGreaterThan(arg0 context.Con } func (r *UserOtherRepositoryMongo) FindTop5AllOrderByAge(arg0 context.Context) ([]*UserModel, error) { - cursor, err := r.collection.Find(arg0, bson.M{}, options.Find().SetSort(bson.M{ + findOptions := options.Find().SetSort(bson.M{ "age": 1, - }).SetLimit(5)) + }).SetLimit(5) + cursor, err := r.collection.Find(arg0, bson.M{}, findOptions) if err != nil { return nil, err } diff --git a/examples/cross_package/interf/user.go b/examples/cross-package/interf/user.go similarity index 82% rename from examples/cross_package/interf/user.go rename to examples/cross-package/interf/user.go index 460953e..3759a77 100644 --- a/examples/cross_package/interf/user.go +++ b/examples/cross-package/interf/user.go @@ -3,8 +3,8 @@ package interf import ( "context" - "github.com/sunboyy/repogen/examples/cross_package" - "go.mongodb.org/mongo-driver/bson/primitive" + crosspackage "github.com/sunboyy/repogen/examples/cross-package" + "go.mongodb.org/mongo-driver/v2/bson" ) //go:generate repogen -model-pkg=../ -model=UserModel -repo=UserRepository -dest=../repo/user_repo.go -dest-pkg=../repo @@ -14,18 +14,18 @@ import ( type UserRepository interface { // InsertOne stores userModel into the database and returns inserted ID // if insertion succeeds and returns error if insertion fails. - InsertOne(ctx context.Context, userModel *cross_package.UserModel) (interface{}, error) + InsertOne(ctx context.Context, userModel *crosspackage.UserModel) (interface{}, error) // FindByUsername queries user by username. If a user with specified // username exists, the user will be returned. Otherwise, error will be // returned. - FindByUsername(ctx context.Context, username string) (*cross_package.UserModel, error) + FindByUsername(ctx context.Context, username string) (*crosspackage.UserModel, error) // UpdateDisplayNameByID updates a user with the specified ID with a new // display name. If there is a user matches the query, it will return // true. Error will be returned only when error occurs while accessing // the database. - UpdateDisplayNameByID(ctx context.Context, displayName string, id primitive.ObjectID) (bool, error) + UpdateDisplayNameByID(ctx context.Context, displayName string, id bson.ObjectID) (bool, error) // DeleteByCity deletes users that have `city` value match the parameter // and returns the match count. The error will be returned only when diff --git a/examples/cross_package/repo/user_repo.go b/examples/cross-package/repo/user_repo.go similarity index 73% rename from examples/cross_package/repo/user_repo.go rename to examples/cross-package/repo/user_repo.go index 5cbd168..a8cfea7 100644 --- a/examples/cross_package/repo/user_repo.go +++ b/examples/cross-package/repo/user_repo.go @@ -4,11 +4,10 @@ package repo import ( "context" - "github.com/sunboyy/repogen/examples/cross_package" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + crosspackage "github.com/sunboyy/repogen/examples/cross-package" + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" ) func NewUserRepository(collection *mongo.Collection) *UserRepositoryMongo { @@ -41,17 +40,18 @@ func (r *UserRepositoryMongo) DeleteByCity(arg0 context.Context, arg1 string) (i return int(result.DeletedCount), nil } -func (r *UserRepositoryMongo) FindByUsername(arg0 context.Context, arg1 string) (*cross_package.UserModel, error) { - var entity cross_package.UserModel +func (r *UserRepositoryMongo) FindByUsername(arg0 context.Context, arg1 string) (*crosspackage.UserModel, error) { + findOptions := options.FindOne().SetSort(bson.M{}) + var entity crosspackage.UserModel if err := r.collection.FindOne(arg0, bson.M{ "username": arg1, - }, options.FindOne().SetSort(bson.M{})).Decode(&entity); err != nil { + }, findOptions).Decode(&entity); err != nil { return nil, err } return &entity, nil } -func (r *UserRepositoryMongo) InsertOne(arg0 context.Context, arg1 *cross_package.UserModel) (interface{}, error) { +func (r *UserRepositoryMongo) InsertOne(arg0 context.Context, arg1 *crosspackage.UserModel) (interface{}, error) { result, err := r.collection.InsertOne(arg0, arg1) if err != nil { return nil, err @@ -59,7 +59,7 @@ func (r *UserRepositoryMongo) InsertOne(arg0 context.Context, arg1 *cross_packag return result.InsertedID, nil } -func (r *UserRepositoryMongo) UpdateDisplayNameByID(arg0 context.Context, arg1 string, arg2 primitive.ObjectID) (bool, error) { +func (r *UserRepositoryMongo) UpdateDisplayNameByID(arg0 context.Context, arg1 string, arg2 bson.ObjectID) (bool, error) { result, err := r.collection.UpdateOne(arg0, bson.M{ "_id": arg2, }, bson.M{ diff --git a/examples/cross-package/user.go b/examples/cross-package/user.go new file mode 100644 index 0000000..cbf8099 --- /dev/null +++ b/examples/cross-package/user.go @@ -0,0 +1,11 @@ +package crosspackage + +import "go.mongodb.org/mongo-driver/v2/bson" + +// UserModel is a model of user that is stored in the database +type UserModel struct { + ID bson.ObjectID `bson:"_id,omitempty" json:"id"` + Username string `bson:"username" json:"username"` + DisplayName string `bson:"display_name" json:"displayName"` + City string `bson:"city" json:"city"` +} diff --git a/examples/cross_package/user.go b/examples/cross_package/user.go deleted file mode 100644 index c8c1aba..0000000 --- a/examples/cross_package/user.go +++ /dev/null @@ -1,11 +0,0 @@ -package cross_package - -import "go.mongodb.org/mongo-driver/bson/primitive" - -// UserModel is a model of user that is stored in the database -type UserModel struct { - ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` - Username string `bson:"username" json:"username"` - DisplayName string `bson:"display_name" json:"displayName"` - City string `bson:"city" json:"city"` -} diff --git a/examples/getting-started/main.go b/examples/getting-started/main.go index 5c56414..6d3a0fd 100644 --- a/examples/getting-started/main.go +++ b/examples/getting-started/main.go @@ -4,9 +4,9 @@ import ( "context" "fmt" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Replace these values with your own connection option. This connection option is hard-coded for easy @@ -19,12 +19,12 @@ const ( var ( userRepository UserRepository - userID primitive.ObjectID + userID bson.ObjectID ) func init() { // create a connection to the database - client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(connectionString)) + client, err := mongo.Connect(options.Client().ApplyURI(connectionString)) if err != nil { panic(err) } @@ -53,7 +53,7 @@ func demonstrateInsertion() { if err != nil { panic(err) } - userID = insertedID.(primitive.ObjectID) + userID = insertedID.(bson.ObjectID) fmt.Printf("Insert (one): inserted id = %v\n", insertedID) } diff --git a/examples/getting-started/user.go b/examples/getting-started/user.go index 4b6ac9d..336b9d5 100644 --- a/examples/getting-started/user.go +++ b/examples/getting-started/user.go @@ -3,15 +3,15 @@ package main import ( "context" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/v2/bson" ) // UserModel is a model of user that is stored in the database type UserModel struct { - ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` - Username string `bson:"username" json:"username"` - DisplayName string `bson:"display_name" json:"displayName"` - City string `bson:"city" json:"city"` + ID bson.ObjectID `bson:"_id,omitempty" json:"id"` + Username string `bson:"username" json:"username"` + DisplayName string `bson:"display_name" json:"displayName"` + City string `bson:"city" json:"city"` } //go:generate repogen -dest=user_repo.go -model=UserModel -repo=UserRepository @@ -32,7 +32,7 @@ type UserRepository interface { // display name. If there is a user matches the query, it will return // true. Error will be returned only when error occurs while accessing // the database. - UpdateDisplayNameByID(ctx context.Context, displayName string, id primitive.ObjectID) (bool, error) + UpdateDisplayNameByID(ctx context.Context, displayName string, id bson.ObjectID) (bool, error) // DeleteByCity deletes users that have `city` value match the parameter // and returns the match count. The error will be returned only when diff --git a/examples/getting-started/user_repo.go b/examples/getting-started/user_repo.go index 91e9d9f..90ec7a3 100644 --- a/examples/getting-started/user_repo.go +++ b/examples/getting-started/user_repo.go @@ -4,13 +4,12 @@ package main import ( "context" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" ) -func NewUserRepository(collection *mongo.Collection) UserRepository { +func NewUserRepository(collection *mongo.Collection) *UserRepositoryMongo { return &UserRepositoryMongo{ collection: collection, } @@ -20,25 +19,46 @@ type UserRepositoryMongo struct { collection *mongo.Collection } -func (r *UserRepositoryMongo) InsertOne(arg0 context.Context, arg1 *UserModel) (interface{}, error) { - result, err := r.collection.InsertOne(arg0, arg1) +func (r *UserRepositoryMongo) CountByCity(arg0 context.Context, arg1 string) (int, error) { + count, err := r.collection.CountDocuments(arg0, bson.M{ + "city": arg1, + }) if err != nil { - return nil, err + return 0, err } - return result.InsertedID, nil + return int(count), nil +} + +func (r *UserRepositoryMongo) DeleteByCity(arg0 context.Context, arg1 string) (int, error) { + result, err := r.collection.DeleteMany(arg0, bson.M{ + "city": arg1, + }) + if err != nil { + return 0, err + } + return int(result.DeletedCount), nil } func (r *UserRepositoryMongo) FindByUsername(arg0 context.Context, arg1 string) (*UserModel, error) { + findOptions := options.FindOne().SetSort(bson.M{}) var entity UserModel if err := r.collection.FindOne(arg0, bson.M{ "username": arg1, - }, options.FindOne().SetSort(bson.M{})).Decode(&entity); err != nil { + }, findOptions).Decode(&entity); err != nil { return nil, err } return &entity, nil } -func (r *UserRepositoryMongo) UpdateDisplayNameByID(arg0 context.Context, arg1 string, arg2 primitive.ObjectID) (bool, error) { +func (r *UserRepositoryMongo) InsertOne(arg0 context.Context, arg1 *UserModel) (interface{}, error) { + result, err := r.collection.InsertOne(arg0, arg1) + if err != nil { + return nil, err + } + return result.InsertedID, nil +} + +func (r *UserRepositoryMongo) UpdateDisplayNameByID(arg0 context.Context, arg1 string, arg2 bson.ObjectID) (bool, error) { result, err := r.collection.UpdateOne(arg0, bson.M{ "_id": arg2, }, bson.M{ @@ -51,23 +71,3 @@ func (r *UserRepositoryMongo) UpdateDisplayNameByID(arg0 context.Context, arg1 s } return result.MatchedCount > 0, nil } - -func (r *UserRepositoryMongo) DeleteByCity(arg0 context.Context, arg1 string) (int, error) { - result, err := r.collection.DeleteMany(arg0, bson.M{ - "city": arg1, - }) - if err != nil { - return 0, err - } - return int(result.DeletedCount), nil -} - -func (r *UserRepositoryMongo) CountByCity(arg0 context.Context, arg1 string) (int, error) { - count, err := r.collection.CountDocuments(arg0, bson.M{ - "city": arg1, - }) - if err != nil { - return 0, err - } - return int(count), nil -} diff --git a/go.mod b/go.mod index 663fd0b..697f9f3 100644 --- a/go.mod +++ b/go.mod @@ -1,25 +1,21 @@ module github.com/sunboyy/repogen -go 1.22 - -toolchain go1.22.3 +go 1.24.0 require ( github.com/fatih/camelcase v1.0.0 - go.mongodb.org/mongo-driver v1.15.0 - golang.org/x/tools v0.21.0 + go.mongodb.org/mongo-driver/v2 v2.5.0 + golang.org/x/tools v0.41.0 ) require ( - github.com/golang/snappy v0.0.1 // indirect - github.com/klauspost/compress v1.13.6 // indirect - github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect + github.com/klauspost/compress v1.17.6 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect - github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/scram v1.2.0 // indirect github.com/xdg-go/stringprep v1.0.4 // indirect - github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect - golang.org/x/crypto v0.17.0 // indirect - golang.org/x/mod v0.17.0 // indirect - golang.org/x/sync v0.7.0 // indirect - golang.org/x/text v0.14.0 // indirect + github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect + golang.org/x/crypto v0.33.0 // indirect + golang.org/x/mod v0.32.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/text v0.22.0 // indirect ) diff --git a/go.sum b/go.sum index ef7cd8f..a7e2df2 100644 --- a/go.sum +++ b/go.sum @@ -2,39 +2,35 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= -github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= -github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= -github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0= -github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/klauspost/compress v1.17.6 h1:60eq2E/jlfwQXtvZEeBUYADs+BwKBWURIY+Gj2eRGjI= +github.com/klauspost/compress v1.17.6/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= -github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= -github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs= +github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8= github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= -github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA= -github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.mongodb.org/mongo-driver v1.15.0 h1:rJCKC8eEliewXjZGf0ddURtl7tTVy1TK3bfl0gkUSLc= -go.mongodb.org/mongo-driver v1.15.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= -golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= +golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= -golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= +golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= -golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -46,11 +42,11 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.21.0 h1:qc0xYgIbsSDt9EyWz05J5wfa7LOVW0YTLOXrqdLAWIw= -golang.org/x/tools v0.21.0/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/internal/codegen/builder_test.go b/internal/codegen/builder_test.go index 3f98505..4e6302e 100644 --- a/internal/codegen/builder_test.go +++ b/internal/codegen/builder_test.go @@ -16,18 +16,18 @@ package user import ( _ "context" - "go.mongodb.org/mongo-driver/bson/primitive" - _ "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/v2/bson" + _ "go.mongodb.org/mongo-driver/v2/mongo/options" ) type User struct { - ID primitive.ObjectID ` + "`bson:\"id\" json:\"id,omitempty\"`" + ` + ID bson.ObjectID ` + "`bson:\"id\" json:\"id,omitempty\"`" + ` Username string } func NewUser(username string) User { return User{ - ID: primitive.NewObjectID(), + ID: bson.NewObjectID(), Username: username, } } @@ -47,11 +47,11 @@ func TestBuilderBuild(t *testing.T) { }, { { - Path: "go.mongodb.org/mongo-driver/bson/primitive", + Path: "go.mongodb.org/mongo-driver/v2/bson", }, { Name: "_", - Path: "go.mongodb.org/mongo-driver/mongo/options", + Path: "go.mongodb.org/mongo-driver/v2/mongo/options", }, }, }) @@ -85,7 +85,7 @@ func TestBuilderBuild(t *testing.T) { { Key: "ID", Value: codegen.ChainStatement{ - codegen.Identifier("primitive"), + codegen.Identifier("bson"), codegen.CallStatement{ FuncName: "NewObjectID", }, diff --git a/internal/codegen/struct_test.go b/internal/codegen/struct_test.go index 45d70fa..588a109 100644 --- a/internal/codegen/struct_test.go +++ b/internal/codegen/struct_test.go @@ -13,7 +13,7 @@ import ( const expectedStructBuilderCode = ` type User struct { - ID primitive.ObjectID ` + "`bson:\"id,omitempty\" json:\"id,omitempty\"`" + ` + ID bson.ObjectID ` + "`bson:\"id,omitempty\" json:\"id,omitempty\"`" + ` Username string ` + "`bson:\"username\" json:\"username\"`" + ` Age int ` + "`bson:\"age\"`" + ` orderCount *int diff --git a/internal/mongo/common.go b/internal/mongo/common.go index 8ddcc84..4f51c86 100644 --- a/internal/mongo/common.go +++ b/internal/mongo/common.go @@ -16,10 +16,10 @@ var ( ) func init() { - bareMongoPkg := types.NewPackage("go.mongodb.org/mongo-driver/mongo", "mongo") + bareMongoPkg := types.NewPackage("go.mongodb.org/mongo-driver/v2/mongo", "mongo") mongoCollectionType = types.NewNamed(types.NewTypeName(token.NoPos, bareMongoPkg, "Collection", nil), nil, nil) - bareBsonPkg := types.NewPackage("go.mongodb.org/mongo-driver/bson", "bson") + bareBsonPkg := types.NewPackage("go.mongodb.org/mongo-driver/v2/bson", "bson") bsonMType = types.NewNamed(types.NewTypeName(token.NoPos, bareBsonPkg, "M", nil), nil, nil) } diff --git a/internal/mongo/generator.go b/internal/mongo/generator.go index 372404a..f76f08b 100644 --- a/internal/mongo/generator.go +++ b/internal/mongo/generator.go @@ -35,10 +35,9 @@ func (g RepositoryGenerator) Imports() [][]codegen.Import { {Path: "context"}, }, { - {Path: "go.mongodb.org/mongo-driver/bson"}, - {Path: "go.mongodb.org/mongo-driver/bson/primitive"}, - {Path: "go.mongodb.org/mongo-driver/mongo"}, - {Path: "go.mongodb.org/mongo-driver/mongo/options"}, + {Path: "go.mongodb.org/mongo-driver/v2/bson"}, + {Path: "go.mongodb.org/mongo-driver/v2/mongo"}, + {Path: "go.mongodb.org/mongo-driver/v2/mongo/options"}, }, } } diff --git a/internal/mongo/generator_test.go b/internal/mongo/generator_test.go index b1812c3..46942b4 100644 --- a/internal/mongo/generator_test.go +++ b/internal/mongo/generator_test.go @@ -21,10 +21,9 @@ func TestImports(t *testing.T) { {Path: "context"}, }, { - {Path: "go.mongodb.org/mongo-driver/bson"}, - {Path: "go.mongodb.org/mongo-driver/bson/primitive"}, - {Path: "go.mongodb.org/mongo-driver/mongo"}, - {Path: "go.mongodb.org/mongo-driver/mongo/options"}, + {Path: "go.mongodb.org/mongo-driver/v2/bson"}, + {Path: "go.mongodb.org/mongo-driver/v2/mongo"}, + {Path: "go.mongodb.org/mongo-driver/v2/mongo/options"}, }, } @@ -36,7 +35,7 @@ func TestImports(t *testing.T) { } func TestGenerateStruct(t *testing.T) { - bareMongoPkg := types.NewPackage("go.mongodb.org/mongo-driver/mongo", "mongo") + bareMongoPkg := types.NewPackage("go.mongodb.org/mongo-driver/v2/mongo", "mongo") bareCollectionType := types.NewNamed(types.NewTypeName(token.NoPos, bareMongoPkg, "Collection", nil), nil, nil) generator := mongo.NewGenerator(testutils.Pkg, testutils.TypeUserNamed, "UserRepository") expected := codegen.StructBuilder{ diff --git a/internal/teststub/user.go b/internal/teststub/user.go index 48adec2..d578992 100644 --- a/internal/teststub/user.go +++ b/internal/teststub/user.go @@ -3,22 +3,22 @@ package teststub import ( "context" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/v2/bson" ) type Gender string type User struct { - ID primitive.ObjectID `bson:"_id,omitempty"` - PhoneNumber string `bson:"phone_number"` - Gender Gender `bson:"gender"` - City string `bson:"city"` - Age int `bson:"age"` - Name Name `bson:"name"` - Contact Contact `bson:"contact"` - Referrer *User `bson:"referrer"` - Enabled bool `bson:"enabled"` - ConsentHistory []ConsentHistory `bson:"consent_history"` + ID bson.ObjectID `bson:"_id,omitempty"` + PhoneNumber string `bson:"phone_number"` + Gender Gender `bson:"gender"` + City string `bson:"city"` + Age int `bson:"age"` + Name Name `bson:"name"` + Contact Contact `bson:"contact"` + Referrer *User `bson:"referrer"` + Enabled bool `bson:"enabled"` + ConsentHistory []ConsentHistory `bson:"consent_history"` AccessToken string } @@ -32,7 +32,7 @@ type Contact struct { } type ConsentHistory struct { - ID primitive.ObjectID + ID bson.ObjectID Value bool } @@ -81,7 +81,7 @@ type UserRepositoryFind interface { // Test find with True operator FindByEnabledTrue(ctx context.Context) ([]*User, error) // Test find ONE mode - FindByID(ctx context.Context, id primitive.ObjectID) (*User, error) + FindByID(ctx context.Context, id bson.ObjectID) (*User, error) // Test find with deep referencing FindByNameFirst(ctx context.Context, firstName string) ([]*User, error) // Test find with multi-word arg @@ -89,7 +89,7 @@ type UserRepositoryFind interface { // Test find with Exists operator FindByReferrerExists(ctx context.Context) ([]*User, error) // Test find with deep pointer referencing - FindByReferrerID(ctx context.Context, id primitive.ObjectID) ([]*User, error) + FindByReferrerID(ctx context.Context, id bson.ObjectID) ([]*User, error) // Test find with NotExists operator FindByReferrerNotExists(ctx context.Context) ([]*User, error) // Test find Top N @@ -98,23 +98,23 @@ type UserRepositoryFind interface { type UserRepositoryUpdate interface { // Test update inc operator - UpdateAgeIncByID(ctx context.Context, age int, id primitive.ObjectID) (bool, error) + UpdateAgeIncByID(ctx context.Context, age int, id bson.ObjectID) (bool, error) // Test update model ONE mode - UpdateByID(ctx context.Context, user *User, id primitive.ObjectID) (bool, error) + UpdateByID(ctx context.Context, user *User, id bson.ObjectID) (bool, error) // Test update push operator UpdateConsentHistoryPushByID(ctx context.Context, consentHistoryItem ConsentHistory, - id primitive.ObjectID) (int, error) + id bson.ObjectID) (int, error) // Test update multiple fields with push operator UpdateEnabledAndConsentHistoryPushByID(ctx context.Context, enabled bool, - consentHistoryItem ConsentHistory, id primitive.ObjectID) (int, error) + consentHistoryItem ConsentHistory, id bson.ObjectID) (int, error) // Test update multiple fields - UpdateGenderAndCityByID(ctx context.Context, gender Gender, city string, id primitive.ObjectID) (int, error) + UpdateGenderAndCityByID(ctx context.Context, gender Gender, city string, id bson.ObjectID) (int, error) // Test update field MANY mode UpdateGenderByAge(ctx context.Context, gender Gender, age int) (int, error) // Test update field ONE mode - UpdateGenderByID(ctx context.Context, gender Gender, id primitive.ObjectID) (bool, error) + UpdateGenderByID(ctx context.Context, gender Gender, id bson.ObjectID) (bool, error) // Test update deep reference field - UpdateNameFirstByID(ctx context.Context, firstName string, id primitive.ObjectID) (bool, error) + UpdateNameFirstByID(ctx context.Context, firstName string, id bson.ObjectID) (bool, error) } type UserRepositoryDelete interface { @@ -141,7 +141,7 @@ type UserRepositoryDelete interface { // Test delete with Or operator DeleteByCityOrGender(ctx context.Context, city string, gender Gender) (int, error) // Test delete ONE mode - DeleteByID(ctx context.Context, id primitive.ObjectID) (bool, error) + DeleteByID(ctx context.Context, id bson.ObjectID) (bool, error) // Test delete with deep reference DeleteByNameFirst(ctx context.Context, firstName string) (int, error) // Test delete multi-word arg @@ -158,7 +158,7 @@ type UserRepositoryCount interface { } type UserRepositoryInvalidOperation interface { - SearchByID(ctx context.Context, id primitive.ObjectID) (*User, error) + SearchByID(ctx context.Context, id bson.ObjectID) (*User, error) } type UserRepositoryInvalidInsert interface { @@ -214,7 +214,7 @@ type UserRepositoryInvalidFind interface { // Test find with incompatible struct field for True comparator FindByGenderTrue(ctx context.Context) ([]*User, error) // Test find with invalid return type - FindByID(ctx context.Context, id primitive.ObjectID) (User, error) + FindByID(ctx context.Context, id bson.ObjectID) (User, error) // Test find with deep reference field not found FindByNameMiddle(ctx context.Context, middleName string) ([]*User, error) // Test find top with no number and query @@ -230,27 +230,27 @@ type UserRepositoryInvalidFind interface { type UserRepositoryInvalidUpdate interface { // Test update with mismatched And token in update fields UpdateAgeAndAndGenderByID(ctx context.Context, age int, gender Gender, - id primitive.ObjectID) (bool, error) + id bson.ObjectID) (bool, error) // Test update without context parameter UpdateAgeByGender(age int, gender Gender) (int, error) // Test update with invalid number of returns - UpdateAgeByID(ctx context.Context, age int, id primitive.ObjectID) (bool, int, error) + UpdateAgeByID(ctx context.Context, age int, id bson.ObjectID) (bool, int, error) // Test update with ambiguous query - UpdateAgeByIDAndUsernameOrGender(ctx context.Context, age int, id primitive.ObjectID, + UpdateAgeByIDAndUsernameOrGender(ctx context.Context, age int, id bson.ObjectID, username string, gender Gender) (bool, error) // Test update model with invalid parameter type UpdateByGender(ctx context.Context, gender Gender) (bool, error) // Test update with no update parameter provided - UpdateByID(ctx context.Context, id primitive.ObjectID) (bool, error) + UpdateByID(ctx context.Context, id bson.ObjectID) (bool, error) // Test update without query UpdateCity(ctx context.Context, city string) (bool, error) // Test update with invalid return type - UpdateCityByID(ctx context.Context, city string, id primitive.ObjectID) (float64, error) + UpdateCityByID(ctx context.Context, city string, id bson.ObjectID) (float64, error) // Test update with inc operator in non-number field - UpdateCityIncByID(ctx context.Context, city string, id primitive.ObjectID) (bool, error) + UpdateCityIncByID(ctx context.Context, city string, id bson.ObjectID) (bool, error) // Test update with push operator with incorrect parameter type UpdateConsentHistoryPushByID(ctx context.Context, consentHistoryItem []ConsentHistory, - id primitive.ObjectID) (int, error) + id bson.ObjectID) (int, error) // Test update field not found in struct UpdateCountryByGender(ctx context.Context, country string, gender Gender) (int, error) // Test update with insufficient function parameters @@ -260,9 +260,9 @@ type UserRepositoryInvalidUpdate interface { // Test update with incorrect parameter type for update field UpdateEnabledByGender(ctx context.Context, enabled int, gender Gender) (bool, error) // Test update with no error return - UpdateEnabledByID(ctx context.Context, enabled bool, id primitive.ObjectID) (bool, bool) + UpdateEnabledByID(ctx context.Context, enabled bool, id bson.ObjectID) (bool, bool) // Test update with push operator in non-array field - UpdateGenderPushByID(ctx context.Context, gender Gender, id primitive.ObjectID) (bool, error) + UpdateGenderPushByID(ctx context.Context, gender Gender, id bson.ObjectID) (bool, error) } type UserRepositoryInvalidDelete interface { diff --git a/internal/teststub/user_repo_integration.go b/internal/teststub/user_repo_integration.go index b20ae70..18383eb 100644 --- a/internal/teststub/user_repo_integration.go +++ b/internal/teststub/user_repo_integration.go @@ -3,7 +3,7 @@ package teststub import ( "context" - "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/v2/bson" ) type UserRepositoryIntegration interface { @@ -14,7 +14,7 @@ type UserRepositoryIntegration interface { FindByAgeBetween(ctx context.Context, ageFrom int, ageTo int) ([]*User, error) FindByGenderNotAndAgeLessThan(ctx context.Context, gender Gender, age int) ([]*User, error) FindByGenderOrAge(ctx context.Context, gender Gender, age int) ([]*User, error) - FindByID(ctx context.Context, id primitive.ObjectID) (*User, error) + FindByID(ctx context.Context, id bson.ObjectID) (*User, error) InsertMany(ctx context.Context, users []*User) ([]interface{}, error) InsertOne(ctx context.Context, user *User) (interface{}, error) } diff --git a/internal/testutils/stub_provider.go b/internal/testutils/stub_provider.go index 7feeae9..2a83d90 100644 --- a/internal/testutils/stub_provider.go +++ b/internal/testutils/stub_provider.go @@ -30,13 +30,13 @@ func init() { } TypeContextNamed = contextPkgs[0].Types.Scope().Lookup("Context").Type().(*types.Named) - primitivePkgs, err := packages.Load(cfg, "go.mongodb.org/mongo-driver/bson/primitive") + bsonPkgs, err := packages.Load(cfg, "go.mongodb.org/mongo-driver/v2/bson") if err != nil { panic(err) } - TypeObjectIDNamed = primitivePkgs[0].Types.Scope().Lookup("ObjectID").Type().(*types.Named) + TypeObjectIDNamed = bsonPkgs[0].Types.Scope().Lookup("ObjectID").Type().(*types.Named) - mongoPkgs, err := packages.Load(cfg, "go.mongodb.org/mongo-driver/mongo") + mongoPkgs, err := packages.Load(cfg, "go.mongodb.org/mongo-driver/v2/mongo") if err != nil { panic(err) } diff --git a/main.go b/main.go index 0c7c0d8..41da719 100644 --- a/main.go +++ b/main.go @@ -81,7 +81,11 @@ func main() { if err != nil { panic(err) } - defer file.Close() + defer func() { + if err := file.Close(); err != nil { + panic(err) + } + }() dest = file } diff --git a/test/generator_test_expected.txt b/test/generator_test_expected.txt index 1ad4993..0e25f7c 100644 --- a/test/generator_test_expected.txt +++ b/test/generator_test_expected.txt @@ -4,10 +4,9 @@ package teststub import ( "context" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" ) func NewUserRepositoryIntegration(collection *mongo.Collection) *UserRepositoryIntegrationMongo { @@ -156,7 +155,7 @@ func (r *UserRepositoryIntegrationMongo) FindByGenderOrAge(arg0 context.Context, return entities, nil } -func (r *UserRepositoryIntegrationMongo) FindByID(arg0 context.Context, arg1 primitive.ObjectID) (*User, error) { +func (r *UserRepositoryIntegrationMongo) FindByID(arg0 context.Context, arg1 bson.ObjectID) (*User, error) { findOptions := options.FindOne().SetSort(bson.M{}) var entity User if err := r.collection.FindOne(arg0, bson.M{