...
1<a name="database"></a>
2### Database
3
4The Database also allows you to execute queries but expects raw SQL to execute. The supported methods are
5
6* [`Exec`](http://godoc.org/github.com/doug-martin/goqu#Database.Exec)
7* [`Prepare`](http://godoc.org/github.com/doug-martin/goqu#Database.Prepare)
8* [`Query`](http://godoc.org/github.com/doug-martin/goqu#Database.Query)
9* [`QueryRow`](http://godoc.org/github.com/doug-martin/goqu#Database.QueryRow)
10* [`ScanStructs`](http://godoc.org/github.com/doug-martin/goqu#Database.ScanStructs)
11* [`ScanStruct`](http://godoc.org/github.com/doug-martin/goqu#Database.ScanStruct)
12* [`ScanVals`](http://godoc.org/github.com/doug-martin/goqu#Database.ScanVals)
13* [`ScanVal`](http://godoc.org/github.com/doug-martin/goqu#Database.ScanVal)
14* [`Begin`](http://godoc.org/github.com/doug-martin/goqu#Database.Begin)
15
16<a name="transactions"></a>
17### Transactions
18
19`goqu` has builtin support for transactions to make the use of the Datasets and querying seamless
20
21```go
22tx, err := db.Begin()
23if err != nil{
24 return err
25}
26//use tx.From to get a dataset that will execute within this transaction
27update := tx.From("user").
28 Where(goqu.Ex{"password": nil}).
29 Update(goqu.Record{"status": "inactive"})
30if _, err = update.Exec(); err != nil{
31 if rErr := tx.Rollback(); rErr != nil{
32 return rErr
33 }
34 return err
35}
36if err = tx.Commit(); err != nil{
37 return err
38}
39return
40```
41
42The [`TxDatabase`](http://godoc.org/github.com/doug-martin/goqu/#TxDatabase) also has all methods that the [`Database`](http://godoc.org/github.com/doug-martin/goqu/#Database) has along with
43
44* [`Commit`](http://godoc.org/github.com/doug-martin/goqu#TxDatabase.Commit)
45* [`Rollback`](http://godoc.org/github.com/doug-martin/goqu#TxDatabase.Rollback)
46* [`Wrap`](http://godoc.org/github.com/doug-martin/goqu#TxDatabase.Wrap)
47
48#### Wrap
49
50The [`TxDatabase.Wrap`](http://godoc.org/github.com/doug-martin/goqu/#TxDatabase.Wrap) is a convience method for automatically handling `COMMIT` and `ROLLBACK`
51
52```go
53tx, err := db.Begin()
54if err != nil{
55 return err
56}
57err = tx.Wrap(func() error{
58 update := tx.From("user").
59 Where(goqu.Ex{"password": nil}).
60 Update(goqu.Record{"status": "inactive"})
61 return update.Exec()
62})
63//err will be the original error from the update statement, unless there was an error executing ROLLBACK
64if err != nil{
65 return err
66}
67```
68
69<a name="logging"></a>
70## Logging
71
72To enable trace logging of SQL statements use the [`Database.Logger`](http://godoc.org/github.com/doug-martin/goqu/#Database.Logger) method to set your logger.
73
74**NOTE** The logger must implement the [`Logger`](http://godoc.org/github.com/doug-martin/goqu/#Logger) interface
75
76**NOTE** If you start a transaction using a database your set a logger on the transaction will inherit that logger automatically
77
View as plain text