github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/query_gen/transaction.go (about) 1 package qgen 2 3 import "database/sql" 4 5 type transactionStmt struct { 6 stmt *sql.Stmt 7 firstErr error // This'll let us chain the methods to reduce boilerplate 8 } 9 10 func newTransactionStmt(stmt *sql.Stmt, err error) *transactionStmt { 11 return &transactionStmt{stmt, err} 12 } 13 14 func (stmt *transactionStmt) Exec(args ...interface{}) (*sql.Result, error) { 15 if stmt.firstErr != nil { 16 return nil, stmt.firstErr 17 } 18 return stmt.Exec(args...) 19 } 20 21 type TransactionBuilder struct { 22 tx *sql.Tx 23 adapter Adapter 24 textToStmt map[string]*transactionStmt 25 } 26 27 func (b *TransactionBuilder) SimpleDelete(table string, where string) (stmt *sql.Stmt, err error) { 28 res, err := b.adapter.SimpleDelete("", table, where) 29 if err != nil { 30 return stmt, err 31 } 32 return b.tx.Prepare(res) 33 } 34 35 // Quick* versions refer to it being quick to type not the performance. For performance critical transactions, you might want to use the Simple* methods or the *Tx methods on the main builder. Alternate suggestions for names are welcome :) 36 func (b *TransactionBuilder) QuickDelete(table string, where string) *transactionStmt { 37 res, err := b.adapter.SimpleDelete("", table, where) 38 if err != nil { 39 return newTransactionStmt(nil, err) 40 } 41 42 stmt, ok := b.textToStmt[res] 43 if ok { 44 return stmt 45 } 46 stmt = newTransactionStmt(b.tx.Prepare(res)) 47 b.textToStmt[res] = stmt 48 return stmt 49 } 50 51 func (b *TransactionBuilder) SimpleInsert(table string, columns string, fields string) (stmt *sql.Stmt, err error) { 52 res, err := b.adapter.SimpleInsert("", table, columns, fields) 53 if err != nil { 54 return stmt, err 55 } 56 return b.tx.Prepare(res) 57 } 58 59 func (b *TransactionBuilder) QuickInsert(table string, where string) *transactionStmt { 60 res, err := b.adapter.SimpleDelete("", table, where) 61 if err != nil { 62 return newTransactionStmt(nil, err) 63 } 64 65 stmt, ok := b.textToStmt[res] 66 if ok { 67 return stmt 68 } 69 stmt = newTransactionStmt(b.tx.Prepare(res)) 70 b.textToStmt[res] = stmt 71 return stmt 72 }