-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathentity.go
More file actions
99 lines (83 loc) · 1.74 KB
/
entity.go
File metadata and controls
99 lines (83 loc) · 1.74 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package gormup
import (
"context"
"fmt"
"reflect"
"gorm.io/gorm/schema"
)
type entity struct {
schema *schema.Schema
reflectValue reflect.Value
primaryKey string
otherPrimaryKeys []string
id string
fields map[string]string
}
func createEntity(
ctx context.Context,
sch *schema.Schema,
otherPrimaryKeys []string,
v reflect.Value,
) *entity {
if v.Kind() == reflect.Interface {
v = v.Elem()
}
if !isValidStruct(v) {
return nil
}
if len(sch.PrimaryFields) != 1 {
return nil
}
e := &entity{
schema: sch,
primaryKey: sch.PrioritizedPrimaryField.DBName,
otherPrimaryKeys: otherPrimaryKeys,
reflectValue: v,
}
value, isZero := sch.PrioritizedPrimaryField.ValueOf(ctx, v)
if !isZero {
e.id = toString(value)
} else {
// с пустыми идентификаторами не создаем
return nil
}
return e
}
func (e *entity) GetKey() string {
return getEntityKey(e.schema.Table, e.primaryKey, e.id)
}
func (e *entity) GetOtherKeys() (keys []string) {
for _, pk := range e.otherPrimaryKeys {
if pk == e.primaryKey {
continue
}
v, ok := e.fields[pk]
if ok {
keys = append(keys, getEntityKey(e.schema.Table, pk, v))
}
}
return
}
func (e *entity) Value() any {
return e.reflectValue.Interface()
}
func (e *entity) Sync(ctx context.Context) *entity {
if e == nil {
return nil
}
e.fields = make(map[string]string)
for _, f := range e.schema.Fields {
if f.DBName == "" ||
!f.Updatable ||
f.AutoUpdateTime > 0 ||
f.PrimaryKey {
continue
}
value, _ := f.ValueOf(ctx, e.reflectValue)
e.fields[f.DBName] = toString(value)
}
return e
}
func getEntityKey(table, column, value string) string {
return fmt.Sprintf("%s.%s=%s", table, column, value)
}