Skip to content
This repository has been archived by the owner on Mar 3, 2023. It is now read-only.

Commit

Permalink
fix bug after test
Browse files Browse the repository at this point in the history
  • Loading branch information
hongshengjie committed Mar 3, 2023
1 parent af3a492 commit 0b3c0a8
Show file tree
Hide file tree
Showing 4 changed files with 301 additions and 23 deletions.
184 changes: 184 additions & 0 deletions internal/mgo/test/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package mgo

import (
"context"

"time"

"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

type User struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Name string
Age int
Sex bool
Mtime time.Time
}

const (
tableName = "user"
ID = "_id"
Name = "name"
Age = "age"
Sex = "sex"
Mtime = "mtime"
)

func Collection(db *mongo.Database) *mongo.Collection {
return db.Collection(tableName)
}

type FinderBuilder struct {
col *mongo.Collection
filters primitive.D
opts *options.FindOptions
}

func Find(col *mongo.Collection) *FinderBuilder {
return &FinderBuilder{col: col, opts: options.Find()}
}

func (f *FinderBuilder) Filter(filter ...primitive.E) *FinderBuilder {
f.filters = append(f.filters, filter...)
return f
}
func (f *FinderBuilder) Limit(l int64) *FinderBuilder {
f.opts.SetLimit(l)
return f
}

func (f *FinderBuilder) Sort(field string, desc bool) *FinderBuilder {
i := 1
if desc {
i = -1
}
f.opts.SetSort(primitive.E{Key: field, Value: i})
return f
}

func (f *FinderBuilder) Skip(s int64) *FinderBuilder {
f.opts.SetSkip(s)
return f
}
func (f *FinderBuilder) One(ctx context.Context) (*User, error) {
f.opts = f.opts.SetLimit(1)
ret, err := f.All(ctx)
if err != nil {
return nil, err
}
if len(ret) == 1 {
return ret[0], nil
}
return nil, mongo.ErrNoDocuments
}

func (f *FinderBuilder) All(ctx context.Context) ([]*User, error) {
cursor, err := f.col.Find(ctx, f.filters, f.opts)
if err != nil {
return nil, err
}
var results []*User
if err := cursor.All(ctx, &results); err != nil {
return nil, err
}
return results, nil
}

type InsertBuilder struct {
col *mongo.Collection
a []interface{}
}

func Create(col *mongo.Collection) *InsertBuilder {
return &InsertBuilder{col: col}
}
func (i *InsertBuilder) SetUsers(u ...*User) *InsertBuilder {
for _, v := range u {
i.a = append(i.a, v)
}
return i
}

func (i *InsertBuilder) Save(ctx context.Context) error {
ret, err := i.col.InsertMany(ctx, i.a)
if err != nil {
return err
}
for idx, v := range ret.InsertedIDs {
item := i.a[idx].(*User)
id := v.(primitive.ObjectID)
item.ID = id
}
return nil
}

type UpdateBuilder struct {
col *mongo.Collection
a primitive.D
}

func Update(col *mongo.Collection) *UpdateBuilder {
return &UpdateBuilder{col: col}
}
func (u *UpdateBuilder) SetID(a primitive.ObjectID) *UpdateBuilder {
u.a = append(u.a, primitive.E{
Key: ID,
Value: a,
})
return u
}
func (u *UpdateBuilder) SetName(a string) *UpdateBuilder {
u.a = append(u.a, primitive.E{
Key: Name,
Value: a,
})
return u
}
func (u *UpdateBuilder) SetAge(a int) *UpdateBuilder {
u.a = append(u.a, primitive.E{
Key: Age,
Value: a,
})
return u
}
func (u *UpdateBuilder) SetSex(a bool) *UpdateBuilder {
u.a = append(u.a, primitive.E{
Key: Sex,
Value: a,
})
return u
}
func (u *UpdateBuilder) SetMtime(a time.Time) *UpdateBuilder {
u.a = append(u.a, primitive.E{
Key: Mtime,
Value: a,
})
return u
}

func (u *UpdateBuilder) ByID(ctx context.Context, a primitive.ObjectID) (int64, error) {
ret, err := u.col.UpdateByID(ctx, a, primitive.D{primitive.E{Key: "$set", Value: u.a}})
if err != nil {
return 0, err
}
return ret.ModifiedCount, nil
}

type DeleteBuilder struct {
col *mongo.Collection
}

func Delete(col *mongo.Collection) *DeleteBuilder {
return &DeleteBuilder{col: col}
}

func (d *DeleteBuilder) ByID(ctx context.Context, a primitive.ObjectID) (int64, error) {
ret, err := d.col.DeleteOne(ctx, primitive.D{primitive.E{Key: "_id", Value: a}})
if err != nil {
return 0, err
}
return ret.DeletedCount, nil
}
90 changes: 90 additions & 0 deletions internal/mgo/test/user_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package mgo

import (
"context"
"encoding/json"
"fmt"
"testing"
"time"

"github.com/hongshengjie/crud/mgo"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func TestMgo(t *testing.T) {
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
panic(err)
}
defer func() {
if err := client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("example").Collection("user")
//DeleteUser(coll)
//UpdateUser(coll)
FindUser(coll)
//Insert(coll)
}

func FindUser(coll *mongo.Collection) {
//id, _ := primitive.ObjectIDFromHex("63ff2f14983bef62a8c881c0")
q := mgo.And(mgo.In(Name, "aa"))
qq, _ := json.Marshal(q.Query())
fmt.Println(string(qq))
u, err := Find(coll).Filter(q.Query()...).All(context.Background())
b, _ := json.Marshal(u)
fmt.Println(string(b), err)
}

func UpdateUser(coll *mongo.Collection) {
//id, _ := primitive.ObjectIDFromHex("63ff2f14983bef62a8c881c0")
//Update(coll).SetName("woqu").SetAge(100).ByID(context.Background(), id)
}

func DeleteUser(coll *mongo.Collection) {
//id, _ := primitive.ObjectIDFromHex("63ff2f14983bef62a8c881c1")
//Delete(coll).ByID(context.Background(), id)
}

func Insert(coll *mongo.Collection) {

var list []*User
for i := 0; i < 10; i++ {
u := &User{
Name: "aa",
Age: i,
Sex: false,
Mtime: time.Now(),
}
list = append(list, u)
}

err := Create(coll).SetUsers(list...).Save(context.TODO())
b, _ := json.Marshal(list)
fmt.Println(err, string(b))
}

func TestPredicatt(t *testing.T) {
//d := NEQ(Name, "dxxx")
//x := In(Age, []int{1, 2, 3})
//p := Nor(d, x).Query()
//b, _ := json.Marshal(p)
//fmt.Println(string(b))
}

func TestParse(t *testing.T) {
//temp, _ := os.ReadFile("../templates/builder_mgo.tmpl")
//r, _ := template.New("").Parse(string(temp))
//x := mgo.ParseMongoStruct("./user.go", "User")

// f, err := os.Create("user.go")
// if err != nil {
// panic(err)
// }
// r.Execute(f, x)
// f.Close()

}
17 changes: 8 additions & 9 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,6 @@ func main() {
if path == "" {
path = defaultDir
}

tableObjs, isDir := tableFromSql(path)
for _, v := range tableObjs {
generateFiles(v)
}
if isDir && path == defaultDir {
generateFile(filepath.Join(defaultDir, "aa_client.go"), string(clientTmpl), f, tableObjs)
}
if mgo != "" {
pathName := strings.Split(mgo, ":")
if len(pathName) != 2 {
Expand All @@ -113,7 +105,14 @@ func main() {
structName := pathName[1]
doc := mgopkg.ParseMongoStruct(filePath, structName)
generateFile(filePath, string(crudMgo), nil, doc)

return
}
tableObjs, isDir := tableFromSql(path)
for _, v := range tableObjs {
generateFiles(v)
}
if isDir && path == defaultDir {
generateFile(filepath.Join(defaultDir, "aa_client.go"), string(clientTmpl), f, tableObjs)
}

}
Expand Down
33 changes: 19 additions & 14 deletions mgo/mgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,10 @@ type Predicate struct {
func (p *Predicate) EQ(field string, value interface{}) *Predicate {
p.fns = append(p.fns, func(b *Builder) {
b.filter = append(b.filter, bson.E{
Key: field,
Value: value,
Key: field,
Value: bson.D{
{Key: ops[OpEQ], Value: value},
},
})
})
return p
Expand Down Expand Up @@ -127,12 +129,12 @@ func (p *Predicate) LTE(field string, value interface{}) *Predicate {
return p
}

func (p *Predicate) In(field string, value interface{}) *Predicate {
func (p *Predicate) In(field string, value ...interface{}) *Predicate {
p.fns = append(p.fns, func(b *Builder) {
b.filter = append(b.filter, bson.E{
Key: field,
Value: bson.D{
{Key: ops[OpIn], Value: value},
{Key: ops[OpIn], Value: bson.A(value)},
},
})
})
Expand All @@ -151,12 +153,12 @@ func (p *Predicate) NEQ(field string, value interface{}) *Predicate {
return p
}

func (p *Predicate) NotIn(field string, value interface{}) *Predicate {
func (p *Predicate) NotIn(field string, value ...interface{}) *Predicate {
p.fns = append(p.fns, func(b *Builder) {
b.filter = append(b.filter, bson.E{
Key: field,
Value: bson.D{
{Key: ops[OpNotIn], Value: value},
{Key: ops[OpNotIn], Value: bson.A(value)},
},
})
})
Expand Down Expand Up @@ -195,15 +197,18 @@ func And(pp ...*Predicate) *Predicate {
func logic(op Op, pp ...*Predicate) *Predicate {
p := P()
p.fns = append(p.fns, func(b *Builder) {
var conds bson.D
var conds bson.A
for _, v := range pp {
conds = append(conds, v.Query()...)
c := v.Query()
conds = append(conds, c)

}
item := bson.E{
item := bson.D{{
Key: ops[op],
Value: conds,
},
}
b.filter = append(b.filter, item)
b.filter = append(b.filter, item...)
})
return p
}
Expand All @@ -230,10 +235,10 @@ func GT(field string, value interface{}) *Predicate {
func GTE(field string, value interface{}) *Predicate {
return P().GTE(field, value)
}
func In(field string, value interface{}) *Predicate {
return P().In(field, value)
func In(field string, value ...interface{}) *Predicate {
return P().In(field, value...)
}

func NotIn(field string, value interface{}) *Predicate {
return P().NotIn(field, value)
func NotIn(field string, value ...interface{}) *Predicate {
return P().NotIn(field, value...)
}

0 comments on commit 0b3c0a8

Please sign in to comment.