/
entity_delete.go
100 lines (85 loc) · 1.59 KB
/
entity_delete.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
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
100
package gorb
import (
"database/sql"
"fmt"
"reflect"
)
func (t *Table) cascadeDelete(txn *sql.Tx, pk interface{}) error {
for _, child := range t.Children {
child.cascadeDelete(txn, pk)
}
stmt := txn.Stmt(t.stmts.stmtDelete)
_, e := stmt.Exec(pk)
return e
}
func (conn *GorbManager) deleteEntity(ent *Entity, pk interface{}) error {
txn, e := conn.db.Begin()
if e != nil {
return e
}
e = ent.cascadeDelete(txn, pk)
if e == nil {
e = txn.Commit()
} else {
txn.Rollback()
}
return e
}
func (conn *GorbManager) EntityDelete(eType reflect.Type, pk interface{}) error {
if conn.db == nil {
return fmt.Errorf("Database connection is not set")
}
if pk == nil {
return fmt.Errorf("EntityGet: parameters cannot be nil")
}
var ent *Entity
if eType.Kind() == reflect.Ptr {
eType = eType.Elem()
}
ent = conn.LookupEntity(eType)
if ent == nil {
return fmt.Errorf("Unsupported entity %s", eType.Name())
}
var e error = nil
var txn *sql.Tx = nil
if len(ent.Children) > 0 {
txn, e = conn.db.Begin()
if e != nil {
return e
}
}
var stmt *sql.Stmt
chldns := ent.FlattenChildren()
for i := len(chldns) - 1; i >= 0; i-- {
child := chldns[i]
stmt = child.stmts.stmtDelete
if txn != nil {
stmt = txn.Stmt(stmt)
}
_, e = stmt.Exec(pk)
if txn != nil {
stmt.Close()
stmt = nil
}
if e != nil {
break
}
}
stmt = ent.stmts.stmtDelete
if txn != nil {
stmt = txn.Stmt(stmt)
}
_, e = stmt.Exec(pk)
if txn != nil {
stmt.Close()
stmt = nil
}
if txn != nil {
if e == nil {
e = txn.Commit()
} else {
txn.Rollback()
}
}
return e
}