diff --git a/internal/sqladapter/tx.go b/internal/sqladapter/tx.go index 9b1972ef265f4df19b2f7ad77b0a3d169cb1dfa4..c94071ca07005522aa1e55b2e4a8b7d9cf5fc0fa 100644 --- a/internal/sqladapter/tx.go +++ b/internal/sqladapter/tx.go @@ -94,6 +94,19 @@ func (t *txWrapper) Rollback() error { return t.BaseTx.Rollback() } +func RunTx(d db.SQLDatabase, fn func(tx db.SQLTx) error) error { + tx, err := d.NewTx() + if err != nil { + return err + } + defer tx.Close() + if err := fn(tx); err != nil { + tx.Rollback() + return err + } + return tx.Commit() +} + var ( _ = BaseTx(&sqlTx{}) ) diff --git a/postgresql/database.go b/postgresql/database.go index 8f9ff55be9c513d33ee551d2b95a35c082e6ae5b..930853f569c093fa4a991eec386be46f4c060667 100644 --- a/postgresql/database.go +++ b/postgresql/database.go @@ -38,9 +38,8 @@ type database struct { sqladapter.BaseDatabase // Leveraged by sqladapter db.SQLBuilder - txMu sync.Mutex - connURL db.ConnectionURL + txMu sync.Mutex } var ( @@ -55,7 +54,7 @@ func newDatabase(settings db.ConnectionURL) (*database, error) { return d, nil } -// Open stablishes a new connection to a SQL server. +// Open stablishes a new connection with the SQL server. func Open(settings db.ConnectionURL) (db.SQLDatabase, error) { d, err := newDatabase(settings) if err != nil { @@ -219,19 +218,10 @@ func (d *database) NewLocalCollection(name string) db.Collection { return newTable(d, name) } -// Transaction creates a transaction and passes it to the given function, if -// if the function returns no error then the transaction is commited. +// Tx creates a transaction and passes it to the given function, if if the +// function returns no error then the transaction is commited. func (d *database) Tx(fn func(tx db.SQLTx) error) error { - tx, err := d.NewTx() - if err != nil { - return err - } - defer tx.Close() - if err := fn(tx); err != nil { - tx.Rollback() - return err - } - return tx.Commit() + return sqladapter.RunTx(d, fn) } // NewLocalTransaction allows sqladapter start a transaction block.