101 lines
2.1 KiB
Go
101 lines
2.1 KiB
Go
// Copyright (c) 2025 Nikolai Papin
|
|
//
|
|
// This file is part of Easywish
|
|
//
|
|
// This program is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// This program is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
|
// the GNU General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU General Public License
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
package database
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type DbHelperTransaction interface {
|
|
Commit() error
|
|
Rollback() error
|
|
}
|
|
|
|
type DbHelper struct {
|
|
CTX context.Context
|
|
Queries Queries
|
|
}
|
|
|
|
type dbHelperTransactionImpl struct {
|
|
CTX context.Context
|
|
TXlessQueries Queries
|
|
TX pgx.Tx
|
|
TXQueries Queries
|
|
}
|
|
|
|
func NewDbHelper(dbContext DbContext) DbHelper {
|
|
|
|
ctx := context.Background()
|
|
queries := New(dbContext)
|
|
|
|
return DbHelper{
|
|
CTX: ctx,
|
|
Queries: *queries,
|
|
}
|
|
}
|
|
|
|
func NewDbHelperTransaction(dbContext DbContext) (DbHelperTransaction, *dbHelperTransactionImpl, error) {
|
|
|
|
ctx := context.Background()
|
|
queries := New(dbContext)
|
|
tx, err := dbContext.BeginTx(ctx)
|
|
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
txQueries := queries.WithTx(tx)
|
|
|
|
obj := &dbHelperTransactionImpl{
|
|
CTX: ctx,
|
|
TXlessQueries: *queries,
|
|
TX: tx,
|
|
TXQueries: *txQueries,
|
|
}
|
|
|
|
return obj, obj, nil
|
|
}
|
|
|
|
// Commit implements DbHelperTransaction.
|
|
func (d *dbHelperTransactionImpl) Commit() error {
|
|
errCommit := d.TX.Commit(d.CTX)
|
|
|
|
if errCommit != nil {
|
|
errRollback := d.TX.Rollback(d.CTX)
|
|
|
|
if errRollback != nil {
|
|
return errRollback
|
|
}
|
|
|
|
return errCommit
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Rollback implements DbHelperTransaction.
|
|
func (d *dbHelperTransactionImpl) Rollback() error {
|
|
err := d.TX.Rollback(d.CTX)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|