diff --git a/main.go b/cmd/reed/main.go similarity index 100% rename from main.go rename to cmd/reed/main.go diff --git a/driver.go b/driver.go new file mode 100644 index 0000000..1ca0cca --- /dev/null +++ b/driver.go @@ -0,0 +1,322 @@ +package reed + +import ( + "strings" + "time" + + "context" + "fmt" + "reflect" + + "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" +) + +// --------- Tool functions + +func MapMerge[T comparable, S any](ms ...map[T]S) map[T]S { + res := map[T]S{} + for _, m := range ms { + for k, v := range m { + _, exists := res[k] + if !exists { + res[k] = v + } + } + } + return res +} + +func StructToMap(s any) map[string]any { + settings := map[string]any{} + t := reflect.TypeOf(s) + v := reflect.ValueOf(s) + for i := 0; i < t.NumField(); i++ { + field := strings.Split(t.Field(i).Tag.Get("json"), ",")[0] + value := v.Field(i).Interface() + if field == "" { + fieldType := reflect.TypeOf(value) + if fieldType.Kind() == reflect.Struct { + newMap := StructToMap(value) + for k, v := range newMap { + settings[k] = v + } + } + } else { + settings[field] = value + } + } + return settings +} + +// --------- The MongoService Type + +type MongoClient struct { + Client *mongo.Client + DefaultDB *MongoDatabase +} + +func (m *MongoClient) Database(name string) *MongoDatabase { + return &MongoDatabase{ + DB: m.Client.Database(name), + } +} + +func (m *MongoClient) NewQueryOptions() *QueryOptions { + return &QueryOptions{} +} + +func (m *MongoClient) MergeQueryOptions(opts ...*QueryOptions) *QueryOptions { + qOpts := m.NewQueryOptions() + for _, co := range opts { + if co == nil { + continue + } + if co.Filters != nil { + qOpts.Filters = co.Filters + } + if co.Project != nil { + qOpts.Project = co.Project + } + qOpts.WithoutPagination = co.WithoutPagination + } + return qOpts +} + +func (m *MongoClient) MergeFilters(filters ...primitive.M) primitive.M { + var mergedMap primitive.M = make(primitive.M) + for _, f := range filters { + for k, v := range f { + mergedMap[k] = v + } + } + return mergedMap +} + +// --------- The MongoDatabase Type + +type MongoDatabase struct { + DB *mongo.Database +} + +// --------- The MongoCollection Type + +type MongoCollection[T IModel] struct { + Collection mongo.Collection +} + +func Collection[T IModel]() *MongoCollection[T] { + var M T + return &MongoCollection[T]{ + Collection: *Client.DefaultDB.DB.Collection(M.CollectionName()), + } +} + +func (collection *MongoCollection[T]) parseFilter(filter primitive.M) (primitive.M, error) { + for key, value := range filter { + if key == "_id" { + v, err := primitive.ObjectIDFromHex(value.(string)) + if err != nil { + return nil, err + } else { + filter[key] = v + } + } + } + return filter, nil +} + +func (collection *MongoCollection[T]) genInsertSettings(insertInfo interface{}) primitive.M { + settings := primitive.M{} + t := reflect.TypeOf(insertInfo) + v := reflect.ValueOf(insertInfo) + if t.Kind() == reflect.Map { + // map + for _, key := range v.MapKeys() { + settings[key.String()] = v.MapIndex(key).Interface() + } + } else { + // struct + settings = StructToMap(insertInfo) + } + settings["sys_updated_at"] = time.Now().String()[0:19] + delete(settings, "_id") + return settings +} + +// Find ---------------------------------------------------------------------- + +func (collection *MongoCollection[T]) FindOne(filter primitive.M, project primitive.M) (T, error) { + var result T + filter, err := collection.parseFilter(filter) + if err != nil { + return result, err + } + r := collection.Collection.FindOne(context.Background(), filter, options.FindOne().SetProjection(project)) + err = r.Decode(&result) + if err != nil { + if err == mongo.ErrNoDocuments { + return result, nil + } + return result, err + } + return result, nil +} + +func (collection *MongoCollection[T]) Find(filter primitive.M, project primitive.M) ([]T, error) { + var result []T + filter, err := collection.parseFilter(filter) + if err != nil { + return result, err + } + cursor, err := collection.Collection.Find(context.Background(), filter, options.Find().SetProjection(project)) + if err != nil { + return nil, err + } + err = cursor.All(context.Background(), &result) + if err != nil { + return nil, err + } + return result, nil +} + +// Create ---------------------------------------------------------------------- + +func (collection *MongoCollection[T]) InsertOne(document T) (*mongo.InsertOneResult, error) { + doc := collection.genInsertSettings(document) + return collection.Collection.InsertOne(context.Background(), doc) +} + +// Update ---------------------------------------------------------------------- + +func (collection *MongoCollection[T]) UpdateOne(filter primitive.M, insertInfo interface{}, extraSetting primitive.M) (*mongo.UpdateResult, error) { + filter, err := collection.parseFilter(filter) + if err != nil { + return nil, err + } + settings := collection.genInsertSettings(insertInfo) + update := primitive.M{ + "$set": settings, + } + if extraSetting != nil { + update = MapMerge(update, extraSetting) + } + r, err := collection.Collection.UpdateOne(context.Background(), filter, update) + return r, err +} + +func (collection *MongoCollection[T]) UpsertOne(filter primitive.M, insertInfo interface{}, extraSetting primitive.M) (*mongo.UpdateResult, error) { + filter, err := collection.parseFilter(filter) + if err != nil { + return nil, err + } + settings := collection.genInsertSettings(insertInfo) + options := options.Update().SetUpsert(true) + update := primitive.M{ + "$set": settings, + } + if extraSetting != nil { + update = MapMerge(update, extraSetting) + } + r, err := collection.Collection.UpdateOne(context.Background(), filter, update, options) + return r, err +} + +func (collection *MongoCollection[T]) UpsertMany(writeItems *[]UpsertSetting) (*mongo.BulkWriteResult, error) { + var writeModels []mongo.WriteModel + for _, item := range *writeItems { + updateModel := mongo.NewUpdateOneModel().SetFilter(item.Filter).SetUpdate(item.Update).SetUpsert(true) + writeModels = append(writeModels, updateModel) + } + res, err := collection.Collection.BulkWrite(context.Background(), writeModels) + return res, err +} + +func (collection *MongoCollection[T]) FindOneAndUpdate(filter primitive.M, settings interface{}, extraSetting primitive.M) (T, error) { + var result T + filter, err := collection.parseFilter(filter) + if err != nil { + return result, err + } + _settings := collection.genInsertSettings(settings) + update := primitive.M{ + "$set": _settings, + } + if extraSetting != nil { + update = MapMerge(update, extraSetting) + } + r := collection.Collection.FindOneAndUpdate(context.Background(), filter, update) + r.Decode(&result) + return result, nil +} + +// Delete ---------------------------------------------------------------------- + +func (collection *MongoCollection[T]) Delete(oid string) (*mongo.DeleteResult, error) { + filter, err := collection.parseFilter(bson.M{"_id": oid}) + if err != nil { + return nil, err + } + r, err := collection.Collection.DeleteOne(context.Background(), filter) + return r, err +} + +func (collection *MongoCollection[T]) DeleteMany(oidlist []string) (*mongo.DeleteResult, error) { + var ids []primitive.ObjectID + for _, oid := range oidlist { + _id, err := primitive.ObjectIDFromHex(oid) + if err != nil { + return nil, err + } + ids = append(ids, _id) + } + filter := bson.M{"_id": bson.M{"$in": ids}} + r, err := collection.Collection.DeleteMany(context.Background(), filter) + return r, err +} + +// Aggregation ---------------------------------------------------------------------- + +func (collection *MongoCollection[T]) Aggregate(pipeline []bson.M, extraOptions ...*QueryOptions) ([]bson.M, error) { + cursor, err := collection.Collection.Aggregate(context.Background(), pipeline) + if err != nil { + return nil, err + } + result := []bson.M{} + if err = cursor.All(context.Background(), &result); err != nil { + return nil, err + } + return result, nil +} + +// --------- QueryOptions + +type QueryOptions struct { + Filters primitive.M + Project map[string]int + WithoutPagination bool +} + +// --------- Bulk upsert settings + +type UpsertSetting struct { + Filter primitive.M + Update primitive.M +} + +// --------- Initialize singleton + +func NewMongoClient(url string, dbname string) *MongoClient { + options := options.Client().ApplyURI(url) + client, err := mongo.Connect(context.Background(), options) + if err != nil { + panic(err) + } + db := &MongoDatabase{DB: client.Database(dbname)} + fmt.Println("Mongo Client Initialized") + return &MongoClient{Client: client, DefaultDB: db} +} + +var Client *MongoClient diff --git a/go.mod b/go.mod index 95325b4..3952f90 100644 --- a/go.mod +++ b/go.mod @@ -2,10 +2,23 @@ module reed go 1.21.4 -require github.com/urfave/cli/v2 v2.26.0 +require ( + github.com/urfave/cli/v2 v2.26.0 + go.mongodb.org/mongo-driver v1.13.1 +) require ( github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect + 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/russross/blackfriday/v2 v2.1.0 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect + golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect + golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect + golang.org/x/text v0.7.0 // indirect ) diff --git a/go.sum b/go.sum index 1d06da2..4ab2a45 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,62 @@ github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +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/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.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +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/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/urfave/cli/v2 v2.26.0 h1:3f3AMg3HpThFNT4I++TKOejZO8yU55t3JnnSr4S4QEI= github.com/urfave/cli/v2 v2.26.0/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ= +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/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +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/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.13.1 h1:YIc7HTYsKndGK4RFzJ3covLz1byri52x0IoMB0Pt/vk= +go.mongodb.org/mongo-driver v1.13.1/go.mod h1:wcDf1JBCXy2mOW0bWHwO/IOYqdca1MPCwDtFu/Z9+eo= +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.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +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-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +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 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +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-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +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.6/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.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +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/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/model.go b/model.go new file mode 100644 index 0000000..843a8cf --- /dev/null +++ b/model.go @@ -0,0 +1,5 @@ +package reed + +type IModel interface { + CollectionName() string +}