github.com/blend/go-sdk@v1.20220411.3/db/finalizers.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package db 9 10 import ( 11 "database/sql" 12 13 "github.com/blend/go-sdk/ex" 14 ) 15 16 // PoolCloseFinalizer is intended to be used in `defer` blocks with a named 17 // `error` return. It ensures a pool is closed after usage in contexts where 18 // a "limited use" pool is created. 19 // 20 // > func queries() (err error) { 21 // > var pool *db.Connection 22 // > defer func() { 23 // > err = db.PoolCloseFinalizer(pool, err) 24 // > }() 25 // > // ... 26 // > } 27 func PoolCloseFinalizer(pool *Connection, err error) error { 28 if pool == nil || pool.Connection == nil { 29 return err 30 } 31 32 closeErr := pool.Close() 33 return ex.Nest(err, closeErr) 34 } 35 36 // TxRollbackFinalizer is intended to be used in `defer` blocks with a named 37 // `error` return. It ensures a transaction is always closed in blocks where 38 // a transaction is created. 39 // 40 // > func queries() (err error) { 41 // > var tx *sql.Tx 42 // > defer func() { 43 // > err = db.TxRollbackFinalizer(tx, err) 44 // > }() 45 // > // ... 46 // > } 47 func TxRollbackFinalizer(tx *sql.Tx, err error) error { 48 if tx == nil { 49 return err 50 } 51 52 rollbackErr := tx.Rollback() 53 if rollbackErr == sql.ErrTxDone { 54 return err 55 } 56 57 return ex.Nest(err, rollbackErr) 58 }