github.com/0xPolygon/supernets2-node@v0.0.0-20230711153321-2fe574524eaa/jsonrpc/dbtxmanager.go (about) 1 package jsonrpc 2 3 import ( 4 "context" 5 6 "github.com/0xPolygon/supernets2-node/jsonrpc/types" 7 "github.com/jackc/pgx/v4" 8 ) 9 10 // DBTxManager allows to do scopped DB txs 11 type DBTxManager struct{} 12 13 // DBTxScopedFn function to do scopped DB txs 14 type DBTxScopedFn func(ctx context.Context, dbTx pgx.Tx) (interface{}, types.Error) 15 16 // DBTxer interface to begin DB txs 17 type DBTxer interface { 18 BeginStateTransaction(ctx context.Context) (pgx.Tx, error) 19 } 20 21 // NewDbTxScope function to initiate DB scopped txs 22 func (f *DBTxManager) NewDbTxScope(db DBTxer, scopedFn DBTxScopedFn) (interface{}, types.Error) { 23 ctx := context.Background() 24 dbTx, err := db.BeginStateTransaction(ctx) 25 if err != nil { 26 return RPCErrorResponse(types.DefaultErrorCode, "failed to connect to the state", err) 27 } 28 29 v, rpcErr := scopedFn(ctx, dbTx) 30 if rpcErr != nil { 31 if txErr := dbTx.Rollback(context.Background()); txErr != nil { 32 return RPCErrorResponse(types.DefaultErrorCode, "failed to rollback db transaction", txErr) 33 } 34 return v, rpcErr 35 } 36 37 if txErr := dbTx.Commit(context.Background()); txErr != nil { 38 return RPCErrorResponse(types.DefaultErrorCode, "failed to commit db transaction", txErr) 39 } 40 return v, rpcErr 41 }