/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package database

import (
	"context"
	"github.com/jackc/pgconn"
	"github.com/jackc/pgx/v4"
)

type Tx struct {
	pgx.Tx
}

func (tx *Tx) MustCommit(ctx context.Context) {
	if err := tx.Tx.Commit(ctx); err != nil {
		panic(err)
	}
}

func (tx *Tx) MustExec(ctx context.Context, sql string, args ...interface{}) pgconn.CommandTag {
	tag, err := tx.Tx.Exec(ctx, sql, args...)
	if err != nil {
		panic(err)
	}
	return tag
}

func (tx *Tx) GetText(ctx context.Context, sql string, args ...interface{}) (string, error) {
	var result string
	err := tx.QueryRow(ctx, sql, args...).Scan(&result)
	return result, err
}

func (tx *Tx) GetInt(ctx context.Context, sql string, args ...interface{}) (int, error) {
	var result int
	err := tx.QueryRow(ctx, sql, args...).Scan(&result)
	return result, err
}

func (tx *Tx) MustGetInt(ctx context.Context, sql string, args ...interface{}) int {
	if result, err := tx.GetInt(ctx, sql, args...); err == nil {
		return result
	} else {
		panic(err)
	}
}
