cc-backend/internal/repository/transaction.go

87 lines
1.7 KiB
Go
Raw Normal View History

2024-04-11 23:04:30 +02:00
// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
2023-06-06 10:27:55 +02:00
// All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package repository
import (
"github.com/ClusterCockpit/cc-backend/pkg/log"
"github.com/jmoiron/sqlx"
)
type Transaction struct {
tx *sqlx.Tx
stmt *sqlx.NamedStmt
}
2024-09-03 15:40:02 +02:00
func (r *JobRepository) TransactionInit() (*Transaction, error) {
2023-06-06 10:27:55 +02:00
var err error
t := new(Transaction)
2023-06-06 10:27:55 +02:00
t.tx, err = r.DB.Beginx()
if err != nil {
log.Warn("Error while bundling transactions")
return nil, err
}
return t, nil
}
func (r *JobRepository) TransactionCommit(t *Transaction) error {
var err error
if t.tx != nil {
if err = t.tx.Commit(); err != nil {
log.Warn("Error while committing transactions")
return err
}
}
t.tx, err = r.DB.Beginx()
if err != nil {
log.Warn("Error while bundling transactions")
return err
}
return nil
}
func (r *JobRepository) TransactionEnd(t *Transaction) error {
if err := t.tx.Commit(); err != nil {
log.Warn("Error while committing SQL transactions")
return err
}
return nil
}
2024-09-03 15:40:02 +02:00
func (r *JobRepository) TransactionAddNamed(
t *Transaction,
query string,
args ...interface{},
) (int64, error) {
res, err := t.tx.NamedExec(query, args)
2023-06-06 10:27:55 +02:00
if err != nil {
2024-09-03 15:40:02 +02:00
log.Errorf("Named Exec failed: %v", err)
2023-06-06 10:27:55 +02:00
return 0, err
}
id, err := res.LastInsertId()
if err != nil {
log.Errorf("repository initDB(): %v", err)
return 0, err
}
return id, nil
}
2024-09-03 15:40:02 +02:00
func (r *JobRepository) TransactionAdd(t *Transaction, query string, args ...interface{}) (int64, error) {
res := t.tx.MustExec(query, args)
id, err := res.LastInsertId()
2023-06-06 10:27:55 +02:00
if err != nil {
2024-09-03 15:40:02 +02:00
log.Errorf("repository initDB(): %v", err)
2023-06-06 10:27:55 +02:00
return 0, err
}
2024-09-03 15:40:02 +02:00
return id, nil
2023-06-06 10:27:55 +02:00
}