@@ -16,7 +16,7 @@ func AddDatabaseMiddleware(handler http.Handler, pool *pgxpool.Pool, logger logg
1616 return http .HandlerFunc (
1717 func (w http.ResponseWriter , r * http.Request ) {
1818 ctx := r .Context ()
19- repository , tx , err := NewRepositoryWithTx (ctx , pool )
19+ repository , commit , rollback , err := NewRepositoryWithTx (ctx , pool )
2020 if err != nil {
2121 http .Error (w , err .Error (), http .StatusInternalServerError )
2222 }
@@ -31,27 +31,29 @@ func AddDatabaseMiddleware(handler http.Handler, pool *pgxpool.Pool, logger logg
3131 status , ok := r .Context ().Value (constants .StatusCodeKey ).(int )
3232 if ! ok {
3333 logger .Err .Println ("No status code found in context, rolling back tx" )
34- _ = tx . Rollback (ctx )
34+ _ = rollback (ctx )
3535 return
3636 }
3737
3838 if status >= http .StatusBadRequest {
39- _ = tx . Rollback (ctx )
40- } else if err := tx . Commit (ctx ); err != nil {
39+ _ = rollback (ctx )
40+ } else if err := commit (ctx ); err != nil {
4141 // Response has already been sent - just log
4242 logger .Err .Printf ("tx commit failed: %v" , err )
4343 }
4444 },
4545 )
4646}
4747
48- func NewRepositoryWithTx (ctx context.Context , pool * pgxpool.Pool ) (* queries.Queries , pgx. Tx , error ) {
48+ func NewRepositoryWithTx (ctx context.Context , pool * pgxpool.Pool ) (q * queries.Queries , commit func (context. Context ) error , rollback func (context. Context ) error , err error ) {
4949 tx , err := pool .BeginTx (ctx , pgx.TxOptions {
5050 IsoLevel : pgx .Serializable ,
5151 AccessMode : pgx .ReadWrite ,
5252 })
5353 if err != nil {
54- return nil , nil , fmt .Errorf ("failed to start transaction: %w" , err )
54+ return nil , nil , nil , fmt .Errorf ("failed to start transaction: %w" , err )
5555 }
56- return queries .New (pool ).WithTx (tx ), tx , nil
56+ commit = func (ctx context.Context ) error { return tx .Commit (ctx ) }
57+ rollback = func (ctx context.Context ) error { return tx .Rollback (ctx ) }
58+ return queries .New (pool ).WithTx (tx ), commit , rollback , nil
5759}
0 commit comments