From c77c62e8e39f814feab9aac9f79401c68c852d6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Carlos=20Nieto?= <jose.carlos@menteslibres.net> Date: Sat, 16 Jul 2016 07:09:27 -0500 Subject: [PATCH] Move Tx logic to sqladapter. --- internal/sqladapter/tx.go | 13 +++++++++++++ postgresql/database.go | 20 +++++--------------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/internal/sqladapter/tx.go b/internal/sqladapter/tx.go index 9b1972ef..c94071ca 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 8f9ff55b..930853f5 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. -- GitLab