-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathstruct_delete.go
74 lines (62 loc) · 2.05 KB
/
struct_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
package godb
import "fmt"
// StructDelete builds a DELETE statement for the given object.
//
// Example (book is a struct instance):
//
// count, err := db.Delete(&book).Do()
//
type StructDelete struct {
error error
deleteStatement *DeleteStatement
recordDescription *recordDescription
}
// Delete initializes a DELETE sql statement for the given object.
func (db *DB) Delete(record interface{}) *StructDelete {
var err error
sd := &StructDelete{}
sd.recordDescription, err = buildRecordDescription(record)
if err != nil {
sd.error = err
return sd
}
if sd.recordDescription.isSlice {
sd.error = fmt.Errorf("Delete accept only a single instance, got a slice")
return sd
}
quotedTableName := db.quote(db.defaultTableNamer(sd.recordDescription.getTableName()))
sd.deleteStatement = db.DeleteFrom(quotedTableName)
return sd
}
// Do executes the DELETE statement for the struct given to the Delete method,
// and returns the count of deleted rows and an error.
func (sd *StructDelete) Do() (int64, error) {
if sd.error != nil {
return 0, sd.error
}
// Keys
keyColumns := sd.recordDescription.structMapping.GetKeyColumnsNames()
keyValues := sd.recordDescription.structMapping.GetKeyFieldsValues(sd.recordDescription.record)
if len(keyColumns) == 0 {
return 0, fmt.Errorf("the object of type %T has no key : ", sd.recordDescription.record)
}
for i, column := range keyColumns {
quotedColumn := sd.deleteStatement.db.quote(column)
sd.deleteStatement = sd.deleteStatement.Where(quotedColumn+" = ?", keyValues[i])
}
// Optimistic Locking
opLockColumn := sd.recordDescription.structMapping.GetOpLockSQLFieldName()
if opLockColumn != "" {
opLockValue, err := sd.recordDescription.structMapping.GetAndUpdateOpLockFieldValue(sd.recordDescription.record)
if err != nil {
return 0, err
}
sd.deleteStatement = sd.deleteStatement.Where(opLockColumn+" = ?", opLockValue)
}
// Executes the query
rowsAffected, err := sd.deleteStatement.Do()
if opLockColumn != "" && rowsAffected == 0 {
err = ErrOpLock
}
return rowsAffected, err
}