summaryrefslogtreecommitdiff
path: root/pkg/database/db.go
diff options
context:
space:
mode:
authorJulien Dessaux2024-11-18 00:10:58 +0100
committerJulien Dessaux2024-11-18 00:10:58 +0100
commitbc1493b348e5b30cc5fff8f0b7cbee37b8994290 (patch)
tree2e68e6cc116b387865ea2ceee67d1df1c5f50a7b /pkg/database/db.go
parentchore(tfstated): refactored helpers to their own package (diff)
downloadtfstated-bc1493b348e5b30cc5fff8f0b7cbee37b8994290.tar.gz
tfstated-bc1493b348e5b30cc5fff8f0b7cbee37b8994290.tar.bz2
tfstated-bc1493b348e5b30cc5fff8f0b7cbee37b8994290.zip
chore(tfstated): implement a transaction wrapperHEADmain
Diffstat (limited to '')
-rw-r--r--pkg/database/db.go22
1 files changed, 18 insertions, 4 deletions
diff --git a/pkg/database/db.go b/pkg/database/db.go
index 38265ba..5501a82 100644
--- a/pkg/database/db.go
+++ b/pkg/database/db.go
@@ -3,6 +3,7 @@ package database
import (
"context"
"database/sql"
+ "fmt"
"runtime"
"git.adyxax.org/adyxax/tfstated/pkg/scrypto"
@@ -81,10 +82,6 @@ func NewDB(ctx context.Context, url string) (*DB, error) {
return &db, nil
}
-func (db *DB) Begin() (*sql.Tx, error) {
- return db.writeDB.Begin()
-}
-
func (db *DB) Close() error {
if err := db.readDB.Close(); err != nil {
_ = db.writeDB.Close()
@@ -107,3 +104,20 @@ func (db *DB) SetDataEncryptionKey(s string) error {
func (db *DB) SetVersionsHistoryLimit(n int) {
db.versionsHistoryLimit = n
}
+
+func (db *DB) WithTransaction(f func(tx *sql.Tx) error) error {
+ tx, err := db.writeDB.Begin()
+ if err != nil {
+ return err
+ }
+ err = f(tx)
+ if err == nil {
+ err = tx.Commit()
+ }
+ if err != nil {
+ if err2 := tx.Rollback(); err2 != nil {
+ panic(fmt.Sprintf("failed to rollback transaction: %+v. Reason for rollback: %+v", err2, err))
+ }
+ }
+ return err
+}