This repository has been archived by the owner on May 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal.go
67 lines (53 loc) · 1.39 KB
/
global.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
59
60
61
62
63
64
65
66
67
package goquery
import (
"fmt"
"reflect"
"github.com/uptrace/bun"
)
var globalCallsMap = map[reflect.Type]Calls{}
type Factory[T any] interface {
// New creates new Queryable.
//
// This method accepts optional base select query
// to specify model for example.
New(...*bun.SelectQuery) Queryable[T]
}
func NewFactory[T any](db *bun.DB, helper ...Helper) Factory[T] {
var t T
if tp := reflect.TypeOf(t); tp.Kind() != reflect.Pointer || tp.Elem().Kind() != reflect.Struct {
panic(fmt.Sprintf("input type argument must be a pointer to a struct, but got %T", t))
}
var selectedHelper Helper
if len(helper) > 0 {
selectedHelper = helper[0]
} else {
selectedHelper = NewBunHelper[T](db)
}
return &queryable[T]{
callsMap: getCallMapFromGlobal[T](),
helper: selectedHelper,
db: db,
}
}
// DO NOT USE: this is only for generated code!
func AddToGlobalEntity[T any](callsMap Calls) {
var argType T
typeArg := reflect.TypeOf(argType)
if _, ok := globalCallsMap[typeArg]; !ok {
globalCallsMap[typeArg] = callsMap
return
}
callers := getCallMapFromGlobal[T]()
for caller, queryFunc := range callsMap.Where {
callers.Where[caller] = queryFunc
}
}
func getCallMapFromGlobal[T any]() Calls {
var argType T
typeArg := reflect.TypeOf(argType)
callMap, ok := globalCallsMap[typeArg]
if !ok {
panic("global entity not found for type " + typeArg.String())
}
return callMap
}