forked from ravendb/ravendb-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_id.go
67 lines (64 loc) · 1.51 KB
/
generate_id.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 ravendb
import (
"reflect"
)
// tryGetIDFromInstance returns value of ID field on struct if it's of type
// string. Returns empty string if there's no ID field or it's not string
func tryGetIDFromInstance(entity interface{}) (string, bool) {
rv := reflect.ValueOf(entity)
for rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
// TODO: maybe panic?
return "", false
}
structType := rv.Type()
nFields := rv.NumField()
for i := 0; i < nFields; i++ {
structField := structType.Field(i)
name := structField.Name
if name != "ID" {
continue
}
if structField.Type.Kind() != reflect.String {
continue
}
// there is ID field of string type but it's only valid
// if not empty string
s := rv.Field(i).String()
return s, s != ""
}
return "", false
}
// trySetIDOnEnity tries to set value of ID field on struct to id
// returns false if entity has no ID field or if it's not string
func trySetIDOnEntity(entity interface{}, id string) bool {
rv := reflect.ValueOf(entity)
for rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
// TODO: maybe panic?
return false
}
structType := rv.Type()
nFields := rv.NumField()
for i := 0; i < nFields; i++ {
structField := structType.Field(i)
name := structField.Name
if name != "ID" {
continue
}
if structField.Type.Kind() != reflect.String {
continue
}
field := rv.Field(i)
if !field.CanSet() {
return false
}
rv.Field(i).SetString(id)
return true
}
return false
}