-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoperation.go
More file actions
261 lines (225 loc) · 6.97 KB
/
Copy pathoperation.go
File metadata and controls
261 lines (225 loc) · 6.97 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package magicsql
import (
"database/sql"
"errors"
"fmt"
"log"
"strconv"
"time"
)
// Querier defines an interface for top-level sql types that can run SQL and
// prepare statements
type Querier interface {
Query(string, ...interface{}) (*sql.Rows, error)
Exec(string, ...interface{}) (sql.Result, error)
Prepare(string) (*sql.Stmt, error)
}
// Operation represents a short-lived single-purpose combination of database
// calls. On the first failure, its internal error is set, which all
// "children" (statements, transactions, etc) will see. All children will
// refuse to perform any functions once an error has occurred, making it safe
// to perform a chain of related database calls and only check for an error
// when it makes sense.
//
// When a transaction is started, the operation will route all database calls
// through the transaction instead of the global database handler. At this
// time, only one transaction at a time is supported (i.e., no nesting
// transactions).
type Operation struct {
parent *DB
err error
tx *sql.Tx
q Querier
Dbg bool
}
// NewOperation creates an operation in its default state: its parent is the
// passed-in DB instance, and it defaults to using direct database calls until
// a transaction is started.
func NewOperation(db *DB) *Operation {
var o = &Operation{parent: db}
o.q = o.parent.db
return o
}
// Err returns the *first* error which occurred on any database call owned by the Operation
func (op *Operation) Err() error {
return op.err
}
// SetErr tells the Operation to stop handling any more queries. It shouldn't
// usually be called directly, but it can be if you need to tell the object
// "here's a thing that may be an error; don't do any more work if it is".
func (op *Operation) SetErr(err error) {
if op.Err() != nil {
return
}
op.err = err
}
// Query wraps sql's Query, returning a wrapped Rows object
func (op *Operation) Query(query string, args ...interface{}) *Rows {
if op.Err() != nil {
return &Rows{nil, op}
}
if op.Dbg {
log.Printf("DEBUG - Querying: %s, %#v", query, stringifyArgs(args))
}
var r, err = op.q.Query(query, args...)
op.SetErr(err)
return &Rows{r, op}
}
// Exec wraps sql's DB.Exec, returning a wrapped Result
func (op *Operation) Exec(query string, args ...interface{}) *Result {
if op.Err() != nil {
return &Result{nil, op}
}
if op.Dbg {
log.Printf("DEBUG - Executing: %s, %#v", query, stringifyArgs(args))
}
var r, err = op.q.Exec(query, args...)
op.SetErr(err)
return &Result{r, op}
}
func stringifyArgs(args ...interface{}) []string {
var sArgs []string
for _, arg := range args {
if v, ok := arg.([]interface{}); ok {
sArgs = append(sArgs, stringifyArgs(v...)...)
} else {
sArgs = append(sArgs, stringify(arg))
}
}
return sArgs
}
func stringify(arg interface{}) string {
switch v := arg.(type) {
case *int:
return strconv.FormatInt(int64(*v), 10)
case *int8:
return strconv.FormatInt(int64(*v), 10)
case *int16:
return strconv.FormatInt(int64(*v), 10)
case *int32:
return strconv.FormatInt(int64(*v), 10)
case *int64:
return strconv.FormatInt(*v, 10)
case *uint:
return strconv.FormatUint(uint64(*v), 10)
case *uint8:
return strconv.FormatUint(uint64(*v), 10)
case *uint16:
return strconv.FormatUint(uint64(*v), 10)
case *uint32:
return strconv.FormatUint(uint64(*v), 10)
case *uint64:
return strconv.FormatUint(*v, 10)
case *float32:
return strconv.FormatFloat(float64(*v), 'g', -1, 32)
case *float64:
return strconv.FormatFloat(*v, 'g', -1, 64)
case *bool:
return strconv.FormatBool(*v)
case *string:
return *v
case *time.Time:
return (*v).Format(time.RFC3339Nano)
default:
return fmt.Sprintf("<<%s>>", v)
}
}
// Prepare wrap's sql's DB.Prepare, returning a wrapped Stmt. The statement
// must be closed by the caller or eventually MySQL will run out of prepared
// statements.
func (op *Operation) Prepare(query string) *Stmt {
if op.Err() != nil {
return &Stmt{nil, op}
}
if op.Dbg {
log.Printf("DEBUG - Preparing: %s", query)
}
var st, err = op.q.Prepare(query)
op.SetErr(err)
return &Stmt{st, op}
}
// Reset clears the error if any is present
func (op *Operation) Reset() {
op.err = nil
}
// BeginTransaction wraps sql's Begin and uses a wrapped sql.Tx to dispatch
// Query, Exec, and Prepare calls. When the transaction is complete, instead
// of manually rolling back or committing, simply call op.EndTransaction() and
// it will rollback / commit based on the error state. If you need to force a
// rollback, set an error manually with Operation.SetErr().
//
// If a transaction is started while one is already in progress, the operation
// gets into an error state (i.e., nested transactions are not supported).
func (op *Operation) BeginTransaction() {
if op.Err() != nil {
return
}
if op.tx != nil {
op.SetErr(errors.New("cannot nest transactions"))
return
}
var tx, err = op.parent.db.Begin()
op.tx = tx
op.SetErr(err)
op.q = tx
}
// Rollback tries to roll back the transaction even if there is no error
func (op *Operation) Rollback() {
// If there was never a transaction due to errors, this could happen and we
// don't want a panic
if op.tx == nil {
return
}
op.tx.Rollback()
op.tx = nil
op.q = op.parent.db
}
// EndTransaction commits the transaction if no errors occurred, or rolls back
// if there was an error
func (op *Operation) EndTransaction() {
// If there was never a transaction due to errors, this could happen and we
// don't want a panic
if op.tx == nil {
return
}
if op.Err() != nil {
op.tx.Rollback()
} else {
op.SetErr(op.tx.Commit())
}
op.tx = nil
op.q = op.parent.db
}
// Table creates an OperationTable tied to the given table name and reflecting
// on obj's type to auto-build certain SQL statements
func (op *Operation) Table(tableName string, obj interface{}) *OperationTable {
var mt = &MagicTable{Object: obj, Name: tableName}
mt.Configure(nil)
return &OperationTable{op: op, t: mt}
}
// OperationTable allows tying a stored MagicTable to this specific operation,
// rather than passing table name and an empty interface to Select() and Save()
func (op *Operation) OperationTable(mt *MagicTable) *OperationTable {
return &OperationTable{op: op, t: mt}
}
// Save wraps Operation.Table() and Table.Save(). It creates an INSERT or
// UPDATE statement for the given object based on whether its primary key is
// zero. Stores any errors the database returns, and fails if obj isn't tagged
// with a primary key field.
func (op *Operation) Save(tableName string, obj interface{}) *Result {
var emptyResult = &Result{nil, op}
if op.Err() != nil {
return emptyResult
}
var ot = op.Table(tableName, obj)
if ot.t.primaryKey == nil {
op.SetErr(fmt.Errorf("no primary key tagged for structure %s", ot.t.RType.Name()))
return emptyResult
}
return ot.Save(obj)
}
// Select wraps Operation.Table() and Table.Select(). It creates a Select
// object for further refining.
func (op *Operation) Select(tableName string, obj interface{}) Select {
return op.Table(tableName, obj).Select()
}