-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprimarykey.go
More file actions
38 lines (32 loc) · 826 Bytes
/
primarykey.go
File metadata and controls
38 lines (32 loc) · 826 Bytes
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
package gorm
import (
"reflect"
)
func (db *DatabaseConnection) getPrimaryKeyValue(obj interface{}) int {
return int(reflect.ValueOf(obj).Elem().FieldByName(db.getPrimaryKey(obj)).Int())
}
func (db *DatabaseConnection) setPrimaryKeyValue(obj DataObject, id int) {
pk := reflect.ValueOf(obj).Elem().FieldByName(db.getPrimaryKey(obj))
asSettableUnexported(pk).SetInt(int64(id))
}
func (db *DatabaseConnection) getPrimaryKey(obj interface{}) string {
t := reflect.ValueOf(obj).Elem().Type()
if val, ok := db.pkCache[t]; ok {
return val
}
hasPk := false
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Tag.Get("primary") == "true" {
if hasPk {
panic("Multiple PKs defined")
}
db.pkCache[t] = f.Name
hasPk = true
}
}
if !hasPk {
panic("No PK defined")
}
return db.pkCache[t]
}