package datasql

import (
	"context"

	"github.com/jackc/pgx/v5/pgxpool"
)

type SqlInstance struct {
	connectionPool *pgxpool.Pool
}

func NewSqlInstance(pool *pgxpool.Pool) *SqlInstance {
	return &SqlInstance{connectionPool: pool}
}

func (s *SqlInstance) AcquireLock(lockId int) (bool, error) {
	var locked bool
	err := s.connectionPool.QueryRow(context.Background(), "SELECT pg_try_advisory_lock($1)", lockId).Scan(&locked)
	return locked, err
}

func (s *SqlInstance) ReleaseLock(lockId int) error {
	_, err := s.connectionPool.Exec(context.Background(), "SELECT pg_advisory_unlock($1)", lockId)
	return err
}
