goext/sq/transaction.go

106 lines
1.9 KiB
Go
Raw Normal View History

2022-12-07 23:21:36 +01:00
package sq
import (
"context"
"database/sql"
"github.com/jmoiron/sqlx"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
)
type Tx interface {
Rollback() error
Commit() error
Exec(ctx context.Context, sql string, prep PP) (sql.Result, error)
Query(ctx context.Context, sql string, prep PP) (*sqlx.Rows, error)
}
type transaction struct {
tx *sqlx.Tx
id uint16
2022-12-21 15:34:59 +01:00
lstr []Listener
2022-12-07 23:21:36 +01:00
}
2022-12-21 15:34:59 +01:00
func NewTransaction(xtx *sqlx.Tx, txid uint16, lstr []Listener) Tx {
2022-12-07 23:21:36 +01:00
return &transaction{
tx: xtx,
id: txid,
lstr: lstr,
}
}
func (tx *transaction) Rollback() error {
2022-12-21 15:34:59 +01:00
for _, v := range tx.lstr {
err := v.PreTxRollback(tx.id)
if err != nil {
return err
}
2022-12-07 23:21:36 +01:00
}
2022-12-21 15:34:59 +01:00
result := tx.tx.Rollback()
for _, v := range tx.lstr {
v.PostTxRollback(tx.id, result)
}
return result
2022-12-07 23:21:36 +01:00
}
func (tx *transaction) Commit() error {
2022-12-21 15:34:59 +01:00
for _, v := range tx.lstr {
err := v.PreTxCommit(tx.id)
if err != nil {
return err
}
}
result := tx.tx.Commit()
for _, v := range tx.lstr {
v.PostTxRollback(tx.id, result)
2022-12-07 23:21:36 +01:00
}
2022-12-21 15:34:59 +01:00
return result
2022-12-07 23:21:36 +01:00
}
2022-12-21 15:34:59 +01:00
func (tx *transaction) Exec(ctx context.Context, sqlstr string, prep PP) (sql.Result, error) {
origsql := sqlstr
for _, v := range tx.lstr {
2022-12-21 15:41:41 +01:00
err := v.PreExec(ctx, langext.Ptr(tx.id), &sqlstr, &prep)
2022-12-21 15:34:59 +01:00
if err != nil {
return nil, err
}
}
res, err := tx.tx.NamedExecContext(ctx, sqlstr, prep)
for _, v := range tx.lstr {
v.PostExec(langext.Ptr(tx.id), origsql, sqlstr, prep)
2022-12-07 23:21:36 +01:00
}
if err != nil {
return nil, err
}
return res, nil
}
2022-12-21 15:34:59 +01:00
func (tx *transaction) Query(ctx context.Context, sqlstr string, prep PP) (*sqlx.Rows, error) {
origsql := sqlstr
for _, v := range tx.lstr {
2022-12-21 15:41:41 +01:00
err := v.PreQuery(ctx, langext.Ptr(tx.id), &sqlstr, &prep)
2022-12-21 15:34:59 +01:00
if err != nil {
return nil, err
}
}
rows, err := sqlx.NamedQueryContext(ctx, tx.tx, sqlstr, prep)
for _, v := range tx.lstr {
v.PostQuery(langext.Ptr(tx.id), origsql, sqlstr, prep)
2022-12-07 23:21:36 +01:00
}
if err != nil {
return nil, err
}
return rows, nil
}