Skip to content

Commit dcb41d6

Browse files
Merge pull request #9 from KowalskiPiotr98/transaction-support
Add transaction support
2 parents 6ef84bf + 04b3186 commit dcb41d6

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

connection_handler.go

+12
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,18 @@ func GetConnection() Connector {
7272
return connection
7373
}
7474

75+
func BeginTransaction() (*Transaction, error) {
76+
if connection == nil {
77+
panic("database connection not initialised")
78+
}
79+
80+
tx, err := connection.database.Begin()
81+
if err != nil {
82+
return nil, err
83+
}
84+
return newTransaction(tx), nil
85+
}
86+
7587
func CloseConnection() error {
7688
if connection == nil {
7789
return nil

transaction.go

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package gotabase
2+
3+
import "database/sql"
4+
5+
type Transaction struct {
6+
tx *sql.Tx
7+
}
8+
9+
func newTransaction(tx *sql.Tx) *Transaction {
10+
return &Transaction{tx: tx}
11+
}
12+
13+
var _ Connector = (*Transaction)(nil)
14+
15+
func (t *Transaction) QueryRow(sql string, args ...interface{}) (Row, error) {
16+
row := t.tx.QueryRow(sql, args...)
17+
return row, nil
18+
}
19+
20+
func (t *Transaction) QueryRows(sql string, args ...interface{}) (Rows, error) {
21+
return t.tx.Query(sql, args...)
22+
}
23+
24+
func (t *Transaction) Exec(sql string, args ...interface{}) (Result, error) {
25+
return t.tx.Exec(sql, args...)
26+
}
27+
28+
func (t *Transaction) Commit() error {
29+
return t.tx.Commit()
30+
}
31+
32+
func (t *Transaction) Rollback() error {
33+
return t.tx.Rollback()
34+
}

0 commit comments

Comments
 (0)