feat: db regular and transactional helpers to reduce boilerplate
This commit is contained in:
77
backend/internal/database/helper.go
Normal file
77
backend/internal/database/helper.go
Normal file
@@ -0,0 +1,77 @@
|
||||
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
|
||||
queries 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,
|
||||
queries: *queries,
|
||||
TX: tx,
|
||||
TXQueries: *txQueries,
|
||||
}
|
||||
|
||||
return obj, obj, nil
|
||||
}
|
||||
|
||||
// Commit implements DbHelperTransaction.
|
||||
func (d *dbHelperTransactionImpl) Commit() error {
|
||||
err := d.TX.Commit(d.CTX)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Rollback implements DbHelperTransaction.
|
||||
func (d *dbHelperTransactionImpl) Rollback() error {
|
||||
err := d.TX.Rollback(d.CTX)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user