forked from doug-martin/goqu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
359 lines (326 loc) · 11.2 KB
/
database.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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package goqu
import "database/sql"
type (
database interface {
queryAdapter(builder *Dataset) Adapter
From(cols ...interface{}) *Dataset
Logger(logger Logger)
Exec(query string, args ...interface{}) (sql.Result, error)
Prepare(query string) (*sql.Stmt, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
ScanStructs(i interface{}, query string, args ...interface{}) error
ScanStruct(i interface{}, query string, args ...interface{}) (bool, error)
ScanVals(i interface{}, query string, args ...interface{}) error
ScanVal(i interface{}, query string, args ...interface{}) (bool, error)
}
//This struct is the wrapper for a Db. The struct delegates most calls to either an Exec instance or to the Db passed into the constructor.
Database struct {
logger Logger
Dialect string
Db *sql.DB
}
)
//This is the common entry point into goqu.
//
//dialect: This is the adapter dialect, you should see your database adapter for the string to use. Built in adpaters can be found at https://github.com/doug-martin/goqu/tree/master/adapters
//
//db: A sql.Db to use for querying the database
// import (
// "database/sql"
// "fmt"
// "github.com/doug-martin/goqu"
// _ "github.com/doug-martin/goqu/adapters/postgres"
// _ "github.com/lib/pq"
// )
//
// func main() {
// sqlDb, err := sql.Open("postgres", "user=postgres dbname=goqupostgres sslmode=disable ")
// if err != nil {
// panic(err.Error())
// }
// db := goqu.New("postgres", sqlDb)
// }
//The most commonly used Database method is From, which creates a new Dataset that uses the correct adapter and supports queries.
// var ids []uint32
// if err := db.From("items").Where(goqu.I("id").Gt(10)).Pluck("id", &ids); err != nil {
// panic(err.Error())
// }
// fmt.Printf("%+v", ids)
func New(dialect string, db *sql.DB) *Database {
return &Database{Dialect: dialect, Db: db}
}
//Starts a new Transaction.
func (me *Database) Begin() (*TxDatabase, error) {
tx, err := me.Db.Begin()
if err != nil {
return nil, err
}
return &TxDatabase{Dialect: me.Dialect, Tx: tx, logger: me.logger}, nil
}
//used internally to create a new Adapter for a dataset
func (me *Database) queryAdapter(dataset *Dataset) Adapter {
return NewAdapter(me.Dialect, dataset)
}
//Creates a new Dataset that uses the correct adapter and supports queries.
// var ids []uint32
// if err := db.From("items").Where(goqu.I("id").Gt(10)).Pluck("id", &ids); err != nil {
// panic(err.Error())
// }
// fmt.Printf("%+v", ids)
//
//from...: Sources for you dataset, could be table names (strings), a goqu.Literal or another goqu.Dataset
func (me *Database) From(from ...interface{}) *Dataset {
return withDatabase(me).From(from...)
}
//Sets the logger for to use when logging queries
func (me *Database) Logger(logger Logger) {
me.logger = logger
}
//Logs a given operation with the specified sql and arguments
func (me *Database) Trace(op, sql string, args ...interface{}) {
if me.logger != nil {
if sql != "" {
if len(args) != 0 {
me.logger.Printf("[goqu] %s [query:=`%s` args:=%+v]", op, sql, args)
} else {
me.logger.Printf("[goqu] %s [query:=`%s`]", op, sql)
}
} else {
me.logger.Printf("[goqu] %s", op)
}
}
}
//Uses the db to Execute the query with arguments and return the sql.Result
//
//query: The SQL to execute
//
//args...: for any placeholder parameters in the query
func (me *Database) Exec(query string, args ...interface{}) (sql.Result, error) {
me.Trace("EXEC", query, args...)
return me.Db.Exec(query, args...)
}
//Can be used to prepare a query.
//
//You can use this in tandem with a dataset by doing the following.
// sql, args, err := db.From("items").Where(goqu.I("id").Gt(10)).ToSql(true)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// stmt, err := db.Prepare(sql)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer stmt.Close()
// rows, err := stmt.Query(args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer rows.Close()
// for rows.Next(){
// //scan your rows
// }
// if rows.Err() != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
//
//query: The SQL statement to prepare.
func (me *Database) Prepare(query string) (*sql.Stmt, error) {
me.Trace("PREPARE", query)
return me.Db.Prepare(query)
}
//Used to query for multiple rows.
//
//You can use this in tandem with a dataset by doing the following.
// sql, err := db.From("items").Where(goqu.I("id").Gt(10)).Sql()
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// rows, err := stmt.Query(args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer rows.Close()
// for rows.Next(){
// //scan your rows
// }
// if rows.Err() != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
//
//query: The SQL to execute
//
//args...: for any placeholder parameters in the query
func (me *Database) Query(query string, args ...interface{}) (*sql.Rows, error) {
me.Trace("QUERY", query, args...)
return me.Db.Query(query, args...)
}
//Used to query for a single row.
//
//You can use this in tandem with a dataset by doing the following.
// sql, err := db.From("items").Where(goqu.I("id").Gt(10)).Limit(1).Sql()
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// rows, err := stmt.QueryRow(args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// //scan your row
//
//query: The SQL to execute
//
//args...: for any placeholder parameters in the query
func (me *Database) QueryRow(query string, args ...interface{}) *sql.Row {
me.Trace("QUERY ROW", query, args...)
return me.Db.QueryRow(query, args...)
}
//Queries the database using the supplied query, and args and uses CrudExec.ScanStructs to scan the results into a slice of structs
//
//i: A pointer to a slice of structs
//
//query: The SQL to execute
//
//args...: for any placeholder parameters in the query
func (me *Database) ScanStructs(i interface{}, query string, args ...interface{}) error {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanStructs(i)
}
//Queries the database using the supplied query, and args and uses CrudExec.ScanStruct to scan the results into a struct
//
//i: A pointer to a struct
//
//query: The SQL to execute
//
//args...: for any placeholder parameters in the query
func (me *Database) ScanStruct(i interface{}, query string, args ...interface{}) (bool, error) {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanStruct(i)
}
//Queries the database using the supplied query, and args and uses CrudExec.ScanVals to scan the results into a slice of primitive values
//
//i: A pointer to a slice of primitive values
//
//query: The SQL to execute
//
//args...: for any placeholder parameters in the query
func (me *Database) ScanVals(i interface{}, query string, args ...interface{}) error {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanVals(i)
}
//Queries the database using the supplied query, and args and uses CrudExec.ScanVal to scan the results into a primitive value
//
//i: A pointer to a primitive value
//
//query: The SQL to execute
//
//args...: for any placeholder parameters in the query
func (me *Database) ScanVal(i interface{}, query string, args ...interface{}) (bool, error) {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanVal(i)
}
//A wrapper around a sql.Tx and works the same way as Database
type TxDatabase struct {
logger Logger
Dialect string
Tx *sql.Tx
}
//used internally to create a new query adapter for a Dataset
func (me *TxDatabase) queryAdapter(dataset *Dataset) Adapter {
return NewAdapter(me.Dialect, dataset)
}
//Creates a new Dataset for querying a Database.
func (me *TxDatabase) From(cols ...interface{}) *Dataset {
return withDatabase(me).From(cols...)
}
//Sets the logger
func (me *TxDatabase) Logger(logger Logger) {
me.logger = logger
}
func (me *TxDatabase) Trace(op, sql string, args ...interface{}) {
if me.logger != nil {
if sql != "" {
if len(args) != 0 {
me.logger.Printf("[goqu - transaction] %s [query:=`%s` args:=%+v] ", op, sql, args)
} else {
me.logger.Printf("[goqu - transaction] %s [query:=`%s`] ", op, sql)
}
} else {
me.logger.Printf("[goqu - transaction] %s", op)
}
}
}
//See Database#Exec
func (me *TxDatabase) Exec(query string, args ...interface{}) (sql.Result, error) {
me.Trace("EXEC", query, args...)
return me.Tx.Exec(query, args...)
}
//See Database#Prepare
func (me *TxDatabase) Prepare(query string) (*sql.Stmt, error) {
me.Trace("PREPARE", query)
return me.Tx.Prepare(query)
}
//See Database#Query
func (me *TxDatabase) Query(query string, args ...interface{}) (*sql.Rows, error) {
me.Trace("QUERY", query, args...)
return me.Tx.Query(query, args...)
}
//See Database#QueryRow
func (me *TxDatabase) QueryRow(query string, args ...interface{}) *sql.Row {
me.Trace("QUERY ROW", query, args...)
return me.Tx.QueryRow(query, args...)
}
//See Database#ScanStructs
func (me *TxDatabase) ScanStructs(i interface{}, query string, args ...interface{}) error {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanStructs(i)
}
//See Database#ScanStruct
func (me *TxDatabase) ScanStruct(i interface{}, query string, args ...interface{}) (bool, error) {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanStruct(i)
}
//See Database#ScanVals
func (me *TxDatabase) ScanVals(i interface{}, query string, args ...interface{}) error {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanVals(i)
}
//See Database#ScanVal
func (me *TxDatabase) ScanVal(i interface{}, query string, args ...interface{}) (bool, error) {
exec := newCrudExec(me, nil, query, args...)
return exec.ScanVal(i)
}
//COMMIT the transaction
func (me *TxDatabase) Commit() error {
me.Trace("COMMIT", "")
return me.Tx.Commit()
}
//ROLLBACK the transaction
func (me *TxDatabase) Rollback() error {
me.Trace("ROLLBACK", "")
return me.Tx.Rollback()
}
//A helper method that will automatically COMMIT or ROLLBACK once the supplied function is done executing
//
// tx, err := db.Begin()
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// if err := tx.Wrap(func() error{
// if _, err := tx.From("test").Insert(Record{"a":1, "b": "b"}).Exec(){
// //this error will be the return error from the Wrap call
// return err
// }
// return nil
// }); err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
func (me *TxDatabase) Wrap(fn func() error) error {
if err := fn(); err != nil {
if rollbackErr := me.Rollback(); rollbackErr != nil {
return rollbackErr
}
return err
}
return me.Commit()
}