2017-10-31 00:57:57 +00:00
package qgen
import "database/sql"
type transactionStmt struct {
2022-02-21 03:32:53 +00:00
stmt * sql . Stmt
firstErr error // This'll let us chain the methods to reduce boilerplate
2017-10-31 00:57:57 +00:00
}
func newTransactionStmt ( stmt * sql . Stmt , err error ) * transactionStmt {
2022-02-21 03:32:53 +00:00
return & transactionStmt { stmt , err }
2017-10-31 00:57:57 +00:00
}
func ( stmt * transactionStmt ) Exec ( args ... interface { } ) ( * sql . Result , error ) {
2022-02-21 03:32:53 +00:00
if stmt . firstErr != nil {
return nil , stmt . firstErr
}
return stmt . Exec ( args ... )
2017-10-31 00:57:57 +00:00
}
type TransactionBuilder struct {
2022-02-21 03:32:53 +00:00
tx * sql . Tx
adapter Adapter
textToStmt map [ string ] * transactionStmt
2017-10-31 00:57:57 +00:00
}
2019-10-29 01:58:04 +00:00
func ( b * TransactionBuilder ) SimpleDelete ( table string , where string ) ( stmt * sql . Stmt , err error ) {
2022-02-21 03:32:53 +00:00
res , err := b . adapter . SimpleDelete ( "" , table , where )
if err != nil {
return stmt , err
}
return b . tx . Prepare ( res )
2017-10-31 00:57:57 +00:00
}
// 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 :)
2019-10-29 01:58:04 +00:00
func ( b * TransactionBuilder ) QuickDelete ( table string , where string ) * transactionStmt {
2022-02-21 03:32:53 +00:00
res , err := b . adapter . SimpleDelete ( "" , table , where )
if err != nil {
return newTransactionStmt ( nil , err )
}
2017-10-31 00:57:57 +00:00
2022-02-21 03:32:53 +00:00
stmt , ok := b . textToStmt [ res ]
if ok {
return stmt
}
stmt = newTransactionStmt ( b . tx . Prepare ( res ) )
b . textToStmt [ res ] = stmt
return stmt
2017-10-31 00:57:57 +00:00
}
2019-10-29 01:58:04 +00:00
func ( b * TransactionBuilder ) SimpleInsert ( table string , columns string , fields string ) ( stmt * sql . Stmt , err error ) {
2022-02-21 03:32:53 +00:00
res , err := b . adapter . SimpleInsert ( "" , table , columns , fields )
if err != nil {
return stmt , err
}
return b . tx . Prepare ( res )
2017-10-31 00:57:57 +00:00
}
2019-10-29 01:58:04 +00:00
func ( b * TransactionBuilder ) QuickInsert ( table string , where string ) * transactionStmt {
2022-02-21 03:32:53 +00:00
res , err := b . adapter . SimpleDelete ( "" , table , where )
if err != nil {
return newTransactionStmt ( nil , err )
}
2017-10-31 00:57:57 +00:00
2022-02-21 03:32:53 +00:00
stmt , ok := b . textToStmt [ res ]
if ok {
return stmt
}
stmt = newTransactionStmt ( b . tx . Prepare ( res ) )
b . textToStmt [ res ] = stmt
return stmt
2017-10-31 00:57:57 +00:00
}