From 62f348a714be83941325b22460fcba0a55c15d0f Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 4 Feb 2023 15:09:35 +0800 Subject: [PATCH] sqlx: optimize transacation process logic --- internal/dao/sakila/sqlx.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/internal/dao/sakila/sqlx.go b/internal/dao/sakila/sqlx.go index 95275a8f..2c4731d0 100644 --- a/internal/dao/sakila/sqlx.go +++ b/internal/dao/sakila/sqlx.go @@ -29,22 +29,23 @@ func (s *sqlxServant) with(handle func(tx *sqlx.Tx) error) error { if err != nil { return err } - if err = handle(tx); err == nil { - return tx.Commit() + defer tx.Rollback() + if err = handle(tx); err != nil { + return err } - return tx.Rollback() + return tx.Commit() } func (s *sqlxServant) withTx(ctx context.Context, opts *sql.TxOptions, handle func(*sqlx.Tx) error) error { tx, err := s.db.BeginTxx(ctx, opts) if err != nil { return err - } + defer tx.Rollback() if err = handle(tx); err == nil { - return tx.Commit() + return err } - return tx.Rollback() + return tx.Commit() } func newSqlxServant(db *sqlx.DB) *sqlxServant {