@@ -88,3 +88,67 @@ func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner {
88
88
func (sp * stmtCacheProxy ) Begin () (* sql.Tx , error ) {
89
89
return sp .db .Begin ()
90
90
}
91
+
92
+ // DBTransactionProxy wraps transaction and includes DBProxy interface
93
+ type DBTransactionProxy interface {
94
+ DBProxy
95
+ Begin () error
96
+ Commit () error
97
+ Rollback () error
98
+ }
99
+
100
+ type stmtCacheTransactionProxy struct {
101
+ DBProxy
102
+ db * sql.DB
103
+ transaction * sql.Tx
104
+ }
105
+
106
+ // NewStmtCacheTransactionProxy returns a DBTransactionProxy
107
+ // wrapping an open transaction in stmtCacher.
108
+ // You should use Begin() each time you want a new transaction and
109
+ // cache will be valid only for that transaction.
110
+ // By default without calling Begin proxy will use simple stmtCacher
111
+ //
112
+ // Usage example:
113
+ // proxy := sq.NewStmtCacheTransactionProxy(db)
114
+ // mydb := sq.StatementBuilder.RunWith(proxy)
115
+ // insertUsers := mydb.Insert("users").Columns("name")
116
+ // insertUsers.Values("username1").Exec()
117
+ // insertUsers.Values("username2").Exec()
118
+ // proxy.Commit()
119
+ //
120
+ // proxy.Begin()
121
+ // insertPets := mydb.Insert("pets").Columns("name", "username")
122
+ // insertPets.Values("petname1", "username1").Exec()
123
+ // insertPets.Values("petname2", "username1").Exec()
124
+ // proxy.Commit()
125
+ func NewStmtCacheTransactionProxy (db * sql.DB ) (proxy DBTransactionProxy ) {
126
+ return & stmtCacheTransactionProxy {DBProxy : NewStmtCacher (db ), db : db }
127
+ }
128
+
129
+ func (s * stmtCacheTransactionProxy ) Begin () (err error ) {
130
+ tr , err := s .db .Begin ()
131
+
132
+ if err != nil {
133
+ return
134
+ }
135
+
136
+ s .DBProxy = NewStmtCacher (tr )
137
+ s .transaction = tr
138
+
139
+ return
140
+ }
141
+
142
+ func (s * stmtCacheTransactionProxy ) Commit () error {
143
+ defer s .resetProxy ()
144
+ return s .transaction .Commit ()
145
+ }
146
+
147
+ func (s * stmtCacheTransactionProxy ) Rollback () error {
148
+ defer s .resetProxy ()
149
+ return s .transaction .Rollback ()
150
+ }
151
+
152
+ func (s * stmtCacheTransactionProxy ) resetProxy () {
153
+ s .DBProxy = NewStmtCacher (s .db )
154
+ }
0 commit comments