Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/query filter #1

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ var migrateCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Running database migrations")
},
}
}
4 changes: 2 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
var rootCmd = &cobra.Command{
Use: "elemental",
Short: "Your next gen database ODM",
Long: `Elemental is a user database ODM that allows you to interact with your database in a much more user friendly way than standard database drivers`,
Long: `Elemental is a user database ODM that allows you to interact with your database in a much more user friendly way than standard database drivers`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(`

Expand All @@ -29,7 +29,7 @@ If you encounter any issues, please report them at "https://github.com/go-elemen
func init() {
rootCmd.AddCommand(migrateCmd)
rootCmd.AddCommand(seedCmd)
}
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/seed.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ var seedCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Running seeders")
},
}
}
6 changes: 3 additions & 3 deletions connection/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"context"
"elemental/constants"
"elemental/utils"
"time"
"golang.org/x/exp/maps"
"github.com/samber/lo"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
"golang.org/x/exp/maps"
"time"
)

const connectionTimeout = 30 * time.Second
Expand Down Expand Up @@ -89,4 +89,4 @@ func Use(database string, alias ...string) *mongo.Database {
// @param alias - The alias of the connection to use
func UseDefault(alias ...string) *mongo.Database {
return lo.ToPtr(clients[e_utils.Coalesce(e_utils.First(alias), "default")]).Database(e_utils.Coalesce(defaultDatabases[e_utils.Coalesce(e_utils.First(alias), "default")], "test"))
}
}
4 changes: 2 additions & 2 deletions constants/errors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package e_constants

const (
ErrURIRequired = "URI is required"
ErrURIRequired = "URI is required"
ErrMustPairSortArguments = "Sort arguments must be in pairs"
)
)
7 changes: 7 additions & 0 deletions core/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ func (m Model[T]) InsertMany(docs []T) Model[T] {
}

func (m Model[T]) Find(query ...primitive.M) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
var results []T
e_utils.Must(lo.Must(m.Collection().Aggregate(ctx, m.pipeline)).All(ctx, &results))
m.middleware.post.find.run(results)
m.checkConditionsAndPanic(results)
return results
}
m.pipeline = append(m.pipeline, bson.D{{Key: "$match", Value: e_utils.DefaultQuery(query...)}})
return m
}
Expand Down
4 changes: 2 additions & 2 deletions core/model_actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package elemental
import (
"context"
"elemental/connection"
"elemental/utils"
"elemental/utils"
"reflect"

"go.mongodb.org/mongo-driver/mongo"
Expand Down Expand Up @@ -52,4 +52,4 @@ func (m Model[T]) SetDatabase(database string) Model[T] {
func (m Model[T]) SetCollection(collection string) Model[T] {
m.temporaryCollection = &collection
return m
}
}
81 changes: 76 additions & 5 deletions core/model_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package elemental
import (
e_utils "elemental/utils"

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

Expand All @@ -13,13 +14,23 @@ type listener[T any] struct {
}

type pre[T any] struct {
save listener[T]
updateOne listener[T]
save listener[T]
updateOne listener[T]
deleteOne listener[T]
deleteMany listener[T]
findOneAndUpdate listener[T]
findOneAndDelete listener[T]
}

type post[T any] struct {
save listener[T]
updateOne listener[T]
save listener[T]
updateOne listener[T]
deleteOne listener[T]
deleteMany listener[T]
find listener[T]
findOneAndUpdate listener[T]
findOneAndDelete listener[T]
findOneAndReplace listener[T]
}

type middleware[T any] struct {
Expand Down Expand Up @@ -62,4 +73,64 @@ func (m Model[T]) PostUpdateOne(f func(result *mongo.UpdateResult, err error) bo
m.middleware.post.updateOne.functions = append(m.middleware.post.updateOne.functions, func(args ...interface{}) bool {
return f(args[0].(*mongo.UpdateResult), e_utils.Cast[error](args[1]))
})
}
}

func (m Model[T]) PreDeleteOne(f func(filters primitive.M) bool) {
m.middleware.pre.deleteOne.functions = append(m.middleware.pre.deleteOne.functions, func(args ...interface{}) bool {
return f(args[0].(primitive.M))
})
}

func (m Model[T]) PostDeleteOne(f func(result *mongo.DeleteResult, err error) bool) {
m.middleware.post.deleteOne.functions = append(m.middleware.post.deleteOne.functions, func(args ...interface{}) bool {
return f(args[0].(*mongo.DeleteResult), e_utils.Cast[error](args[1]))
})
}

func (m Model[T]) PreDeleteMany(f func(filters primitive.M) bool) {
m.middleware.pre.deleteMany.functions = append(m.middleware.pre.deleteMany.functions, func(args ...interface{}) bool {
return f(args[0].(primitive.M))
})
}

func (m Model[T]) PostDeleteMany(f func(result *mongo.DeleteResult, err error) bool) {
m.middleware.post.deleteMany.functions = append(m.middleware.post.deleteMany.functions, func(args ...interface{}) bool {
return f(args[0].(*mongo.DeleteResult), e_utils.Cast[error](args[1]))
})
}

func (m Model[T]) PostFind(f func(doc []T) bool) {
m.middleware.post.find.functions = append(m.middleware.post.find.functions, func(args ...interface{}) bool {
return f(args[0].([]T))
})
}

func (m Model[T]) PostFindOneAndUpdate(f func(doc *T) bool) {
m.middleware.post.findOneAndUpdate.functions = append(m.middleware.post.findOneAndUpdate.functions, func(args ...interface{}) bool {
return f(args[0].(*T))
})
}

func (m Model[T]) PreFindOneAndUpdate(f func(filters primitive.M) bool) {
m.middleware.pre.findOneAndUpdate.functions = append(m.middleware.pre.findOneAndUpdate.functions, func(args ...interface{}) bool {
return f(args[0].(primitive.M))
})
}

func (m Model[T]) PreFindOneAndDelete(f func(filters primitive.M) bool) {
m.middleware.pre.findOneAndDelete.functions = append(m.middleware.pre.findOneAndDelete.functions, func(args ...interface{}) bool {
return f(args[0].(primitive.M))
})
}

func (m Model[T]) PostFindOneAndDelete(f func(doc *T) bool) {
m.middleware.post.findOneAndDelete.functions = append(m.middleware.post.findOneAndDelete.functions, func(args ...interface{}) bool {
return f(args[0].(*T))
})
}

func (m Model[T]) PostFindOneAndReplace(f func(doc *T) bool) {
m.middleware.post.findOneAndReplace.functions = append(m.middleware.post.findOneAndReplace.functions, func(args ...interface{}) bool {
return f(args[0].(*T))
})
}
3 changes: 1 addition & 2 deletions core/model_ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (m Model[T]) GreaterThanOrEquals(value any) Model[T] {
}

func (m Model[T]) Between(min, max any) Model[T] {
return m.addToFilters( "$gte", min).addToFilters("$lte", max)
return m.addToFilters("$gte", min).addToFilters("$lte", max)
}

func (m Model[T]) Mod(divisor, remainder int) Model[T] {
Expand Down Expand Up @@ -64,4 +64,3 @@ func (m Model[T]) Or() Model[T] {
m.orConditionActive = true
return m
}

4 changes: 2 additions & 2 deletions core/model_populate.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (m Model[T]) populate(value any) Model[T] {
}

func (m Model[T]) Populate(values ...any) Model[T] {
if (len(values) == 1 && reflect.ValueOf(values[0]).Kind() == reflect.String && (strings.Contains(values[0].(string), ",") || strings.Contains(values[0].(string), " "))) {
if len(values) == 1 && reflect.ValueOf(values[0]).Kind() == reflect.String && (strings.Contains(values[0].(string), ",") || strings.Contains(values[0].(string), " ")) {
values := strings.FieldsFunc(values[0].(string), func(r rune) bool {
return r == ',' || r == ' '
})
Expand All @@ -82,4 +82,4 @@ func (m Model[T]) Populate(values ...any) Model[T] {
}
}
return m
}
}
6 changes: 6 additions & 0 deletions core/model_query_delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import (
func (m Model[T]) FindOneAndDelete(query ...primitive.M) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
var doc T
m.middleware.pre.findOneAndDelete.run(query[0])
result := m.Collection().FindOneAndDelete(ctx, e_utils.DefaultQuery(query...))
m.middleware.post.findOneAndDelete.run(&doc)
m.checkConditionsAndPanicForSingleResult(result)
e_utils.Must(result.Decode(&doc))
return doc
Expand All @@ -25,7 +27,9 @@ func (m Model[T]) FindByIdAndDelete(id primitive.ObjectID) Model[T] {

func (m Model[T]) DeleteOne(query ...primitive.M) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
m.middleware.pre.deleteOne.run(query[0])
result, err := m.Collection().DeleteOne(ctx, e_utils.DefaultQuery(query...))
m.middleware.post.deleteOne.run(result, err)
m.checkConditionsAndPanicForErr(err)
return result
}
Expand All @@ -46,8 +50,10 @@ func (m Model[T]) Delete(doc T) Model[T] {

func (m Model[T]) DeleteMany(query ...primitive.M) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
m.middleware.pre.deleteMany.run(query[0])
result, err := m.Collection().DeleteMany(ctx, e_utils.DefaultQuery(query...))
m.checkConditionsAndPanicForErr(err)
m.middleware.post.deleteMany.run(result, err)
return result
}
return m
Expand Down
11 changes: 7 additions & 4 deletions core/model_query_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ import (

func (m Model[T]) FindOneAndUpdate(query *primitive.M, doc any, opts ...*options.FindOneAndUpdateOptions) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
m.middleware.pre.findOneAndUpdate.run(doc)
return (func() any {
var resultDoc T
filters := lo.FromPtr(query)
for k, v := range m.findMatchStage() {
filters[k] = v
}
result := m.Collection().FindOneAndUpdate(ctx, filters, primitive.M{"$set": m.parseDocument(doc)}, parseUpdateOptions(m, opts)...)
m.middleware.post.findOneAndUpdate.run(&resultDoc)
m.checkConditionsAndPanicForSingleResult(result)
e_utils.Must(result.Decode(&resultDoc))
return resultDoc
Expand All @@ -41,7 +43,7 @@ func (m Model[T]) FindByIDAndUpdate(id primitive.ObjectID, doc any, opts ...*opt
func (m Model[T]) UpdateOne(query *primitive.M, doc any, opts ...*options.UpdateOptions) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
filters := make(primitive.M)
if (query != nil) {
if query != nil {
filters = lo.FromPtr(query)
}
for k, v := range m.findMatchStage() {
Expand Down Expand Up @@ -85,7 +87,7 @@ func (m Model[T]) Save(doc T) Model[T] {
func (m Model[T]) UpdateMany(query *primitive.M, doc any, opts ...*options.UpdateOptions) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
filters := make(primitive.M)
if (query != nil) {
if query != nil {
filters = lo.FromPtr(query)
}
for k, v := range m.findMatchStage() {
Expand All @@ -101,7 +103,7 @@ func (m Model[T]) UpdateMany(query *primitive.M, doc any, opts ...*options.Updat
func (m Model[T]) ReplaceOne(query *primitive.M, doc any, opts ...*options.ReplaceOptions) Model[T] {
m.executor = func(m Model[T], ctx context.Context) any {
filters := make(primitive.M)
if (query != nil) {
if query != nil {
filters = lo.FromPtr(query)
}
for k, v := range m.findMatchStage() {
Expand All @@ -127,13 +129,14 @@ func (m Model[T]) FindOneAndReplace(query *primitive.M, doc any, opts ...*option
m.executor = func(m Model[T], ctx context.Context) any {
var resultDoc T
filters := make(primitive.M)
if (query != nil) {
if query != nil {
filters = lo.FromPtr(query)
}
for k, v := range m.findMatchStage() {
filters[k] = v
}
res := m.Collection().FindOneAndReplace(ctx, filters, m.parseDocument(doc), opts...)
m.middleware.post.findOneAndReplace.run(&resultDoc)
m.checkConditionsAndPanicForSingleResult(res)
e_utils.Must(res.Decode(&resultDoc))
return resultDoc
Expand Down
9 changes: 4 additions & 5 deletions core/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"context"
"elemental/connection"
"elemental/utils"
"reflect"
"github.com/creasty/defaults"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"reflect"
)

type Schema struct {
Expand All @@ -20,17 +20,16 @@ func NewSchema(definitions map[string]Field, opts ...SchemaOptions) Schema {
schema := Schema{
Definitions: definitions,
}
if (len(opts) > 0) {
if len(opts) > 0 {
defaults.Set(opts[0])
schema.Options = opts[0]
}
return schema
}


func (s Schema) Field(path string) *Field {
definition := s.Definitions[path]
if (definition != (Field{})) {
if definition != (Field{}) {
return &definition
}
return nil
Expand All @@ -43,7 +42,7 @@ func (s Schema) syncIndexes(reflectedBaseType reflect.Type) {
if (definition.Index != options.IndexOptions{}) {
reflectedField, _ := reflectedBaseType.FieldByName(field)
indexModel := mongo.IndexModel{
Keys: bson.D{{Key: reflectedField.Tag.Get("bson") , Value: e_utils.Coalesce(definition.IndexOrder, 1)}},
Keys: bson.D{{Key: reflectedField.Tag.Get("bson"), Value: e_utils.Coalesce(definition.IndexOrder, 1)}},
Options: &definition.Index,
}
collection.Indexes().CreateOne(context.TODO(), indexModel)
Expand Down
12 changes: 6 additions & 6 deletions core/schema_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ import (

func enforceSchema[T any](schema Schema, doc *T, reflectedEntityType *reflect.Type, defaults ...bool) (bson.M, bson.M) {
var entityToInsert bson.M
if (reflectedEntityType != nil) {
if reflectedEntityType != nil {
entityToInsert = e_utils.Cast[bson.M](doc)
if (entityToInsert == nil) {
if entityToInsert == nil {
entityToInsert = make(bson.M)
}
} else {
Expand All @@ -28,13 +28,13 @@ func enforceSchema[T any](schema Schema, doc *T, reflectedEntityType *reflect.Ty
id, _ := (*reflectedEntityType).FieldByName("ID")
createdAt, _ := (*reflectedEntityType).FieldByName("CreatedAt")
updatedAt, _ := (*reflectedEntityType).FieldByName("UpdatedAt")
if (id.Type != nil) {
if id.Type != nil {
SetDefault(&entityToInsert, id.Tag.Get("bson"), primitive.NewObjectID())
}
if (createdAt.Type != nil) {
if createdAt.Type != nil {
SetDefault(&entityToInsert, createdAt.Tag.Get("bson"), time.Now())
}
if (updatedAt.Type != nil) {
if updatedAt.Type != nil {
SetDefault(&entityToInsert, updatedAt.Tag.Get("bson"), time.Now())
}
}
Expand All @@ -59,7 +59,7 @@ func enforceSchema[T any](schema Schema, doc *T, reflectedEntityType *reflect.Ty
entityToInsert[fieldBsonName], detailedEntity[fieldBsonName] = enforceSchema(*definition.Schema, e_utils.Cast[*bson.M](entityToInsert[fieldBsonName]), &subdocumentField.Type, false)
continue
}
if (definition.Type == reflect.Struct && (definition.Ref != "" || definition.Collection != "") && entityToInsert[fieldBsonName]!= nil) {
if definition.Type == reflect.Struct && (definition.Ref != "" || definition.Collection != "") && entityToInsert[fieldBsonName] != nil {
subdocumentField, _ := (*reflectedEntityType).FieldByName(field)
subdocumentIdField, _ := subdocumentField.Type.FieldByName("ID")
entityToInsert = lo.Assign(
Expand Down
Loading