github.com/decred/politeia@v1.4.0/politeiawww/sql.go (about) 1 // Copyright (c) 2022 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "context" 9 "database/sql" 10 "time" 11 12 "github.com/pkg/errors" 13 ) 14 15 const ( 16 // timeoutOp is the timeout for a single database operation. 17 timeoutOp = 1 * time.Minute 18 19 // timeoutTx is the timeout for a database transaction. 20 timeoutTx = 3 * time.Minute 21 ) 22 23 // beginTx returns a database transactions and a cancel function for the 24 // transaction. 25 // 26 // The cancel function can be used up until the tx is committed or manually 27 // rolled back. Invoking the cancel function rolls the tx back and releases all 28 // resources associated with it. This allows the caller to defer the cancel 29 // function in order to rollback the tx on unexpected errors. Once the tx is 30 // successfully committed the deferred invocation of the cancel function does 31 // nothing. 32 func (p *politeiawww) beginTx() (*sql.Tx, func(), error) { 33 ctx, cancel := ctxForTx() 34 35 opts := &sql.TxOptions{ 36 Isolation: sql.LevelDefault, 37 } 38 tx, err := p.db.BeginTx(ctx, opts) 39 if err != nil { 40 return nil, nil, errors.WithStack(err) 41 } 42 43 return tx, cancel, nil 44 } 45 46 // ctxForOp returns a context and cancel function for a single database 47 // operation. 48 func ctxForOp() (context.Context, func()) { 49 return context.WithTimeout(context.Background(), timeoutOp) 50 } 51 52 // ctxForTx returns a context and a cancel function for a database transaction. 53 func ctxForTx() (context.Context, func()) { 54 return context.WithTimeout(context.Background(), timeoutTx) 55 }