forked from qor/admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
composite_primary_key_callback.go
58 lines (48 loc) · 1.63 KB
/
composite_primary_key_callback.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package admin
import (
"fmt"
"regexp"
"github.com/jinzhu/gorm"
)
var primaryKeyRegexp = regexp.MustCompile(`primary_key\[.+_.+\]`)
func (admin Admin) registerCompositePrimaryKeyCallback() {
if db := admin.DB; db != nil {
// register middleware
router := admin.GetRouter()
router.Use(&Middleware{
Name: "composite primary key filter",
Handler: func(context *Context, middleware *Middleware) {
db := context.GetDB()
for key, value := range context.Request.URL.Query() {
if primaryKeyRegexp.MatchString(key) {
db = db.Set(key, value)
}
}
context.SetDB(db)
middleware.Next(context)
},
})
callbackProc := db.Callback().Query().Before("gorm:query")
callbackName := "qor_admin:composite_primary_key"
if callbackProc.Get(callbackName) == nil {
callbackProc.Register(callbackName, compositePrimaryKeyQueryCallback)
}
callbackProc = db.Callback().RowQuery().Before("gorm:row_query")
if callbackProc.Get(callbackName) == nil {
callbackProc.Register(callbackName, compositePrimaryKeyQueryCallback)
}
}
}
// DisableCompositePrimaryKeyMode disable composite primary key mode
var DisableCompositePrimaryKeyMode = "composite_primary_key:query:disable"
func compositePrimaryKeyQueryCallback(scope *gorm.Scope) {
if value, ok := scope.Get(DisableCompositePrimaryKeyMode); ok && value != "" {
return
}
tableName := scope.TableName()
for _, primaryField := range scope.PrimaryFields() {
if value, ok := scope.Get(fmt.Sprintf("primary_key[%v_%v]", tableName, primaryField.DBName)); ok && value != "" {
scope.Search.Where(fmt.Sprintf("%v = ?", scope.Quote(primaryField.DBName)), value)
}
}
}