From 04b3186ffc1551520c2ffbf2b67ee32dcb30e758 Mon Sep 17 00:00:00 2001 From: Piotr Kowalski Date: Tue, 5 Dec 2023 13:30:03 +0100 Subject: [PATCH] Add transaction support --- connection_handler.go | 12 ++++++++++++ transaction.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 transaction.go diff --git a/connection_handler.go b/connection_handler.go index adceef1..dc33fdd 100644 --- a/connection_handler.go +++ b/connection_handler.go @@ -72,6 +72,18 @@ func GetConnection() Connector { return connection } +func BeginTransaction() (*Transaction, error) { + if connection == nil { + panic("database connection not initialised") + } + + tx, err := connection.database.Begin() + if err != nil { + return nil, err + } + return newTransaction(tx), nil +} + func CloseConnection() error { if connection == nil { return nil diff --git a/transaction.go b/transaction.go new file mode 100644 index 0000000..d193e8f --- /dev/null +++ b/transaction.go @@ -0,0 +1,34 @@ +package gotabase + +import "database/sql" + +type Transaction struct { + tx *sql.Tx +} + +func newTransaction(tx *sql.Tx) *Transaction { + return &Transaction{tx: tx} +} + +var _ Connector = (*Transaction)(nil) + +func (t *Transaction) QueryRow(sql string, args ...interface{}) (Row, error) { + row := t.tx.QueryRow(sql, args...) + return row, nil +} + +func (t *Transaction) QueryRows(sql string, args ...interface{}) (Rows, error) { + return t.tx.Query(sql, args...) +} + +func (t *Transaction) Exec(sql string, args ...interface{}) (Result, error) { + return t.tx.Exec(sql, args...) +} + +func (t *Transaction) Commit() error { + return t.tx.Commit() +} + +func (t *Transaction) Rollback() error { + return t.tx.Rollback() +}