Skip to content

Commit

Permalink
Add Scope method features to DBO plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
christianezeani committed Dec 4, 2024
1 parent 9853ce0 commit 8a3ef7e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
17 changes: 16 additions & 1 deletion dbo/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"bytes"
"fmt"
"reflect"
"strings"

"github.com/Cyberpull/gokit/dbo/scopes"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
Expand All @@ -31,8 +33,8 @@ func (x *xPlugin) Initialize(db *gorm.DB) (err error) {
func (x *xPlugin) onBeforeQuery() xPluginCallback {
return func(db *gorm.DB) {
model := reflect.New(db.Statement.Schema.ModelType)
// model := db.Statement.Schema.ModelType

// Process Tags
for _, field := range db.Statement.Schema.Fields {
tag := x.getFieldTag(field)

Expand All @@ -52,6 +54,19 @@ func (x *xPlugin) onBeforeQuery() xPluginCallback {
db = db.Preload(field.Name, args...)
}
}

// Process Scopes
for i := 0; i < model.NumMethod(); i++ {
name := model.Type().Method(i).Name

if strings.HasPrefix(name, "Scope") {
method, ok := model.Method(i).Interface().(scopes.Scope)

if ok {
db = method(db)
}
}
}
}
}

Expand Down
22 changes: 22 additions & 0 deletions tests/dbo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,24 @@ func (x *DBOTestSuite) SetupSuite() {
require.NoError(x.T(), err)

x.ins.AddMigrations(
&models.Actor{},
&models.Person{},
&models.Car{},
&models.Movie{},
)

require.NoError(x.T(), x.ins.Migrate())

x.ins.AddSeeders(func(db *gorm.DB) (err error) {
return db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoNothing: true,
}).Create([]*models.Actor{
{ID: 1, Name: "Christian Ezeani", Age: 25},
{ID: 2, Name: "John Doe", Age: 15},
}).Error
})

x.ins.AddSeeders(func(db *gorm.DB) (err error) {
return db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
Expand Down Expand Up @@ -107,6 +118,17 @@ func (x *DBOTestSuite) TestPluginPreload() {
require.Len(x.T(), entry.Movies, 1)
}

func (x *DBOTestSuite) TestPluginScope() {
db := x.ins.New()

entries := []models.Actor{}

result := db.Find(&entries)
require.NoError(x.T(), result.Error)
require.EqualValues(x.T(), int64(1), result.RowsAffected)
require.EqualValues(x.T(), uint64(1), entries[0].ID)
}

func (x *DBOTestSuite) TestSet() {
var data dbo.Set[string]

Expand Down
15 changes: 15 additions & 0 deletions tests/models/actor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package models

import (
"gorm.io/gorm"
)

type Actor struct {
ID uint64 `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
Name string `gorm:"index;column:name"`
Age int `gorm:"index;column:age"`
}

func (x *Actor) ScopeAdult(db *gorm.DB) *gorm.DB {
return db.Where("age > ?", 18)
}

0 comments on commit 8a3ef7e

Please sign in to comment.