fyp/logic/db/db.go

49 lines
1019 B
Go
Raw Normal View History

2024-04-17 17:46:43 +01:00
package db
import (
"context"
"github.com/charmbracelet/log"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
type DbContainer struct {
pool *pgxpool.Pool
}
type Db interface {
Query(query string, args ...any) (pgx.Rows, error)
Exec(query string, args ...any) (pgconn.CommandTag, error)
Begin() (pgx.Tx, error)
}
func StartUp(url string) DbContainer {
dbpool, err := pgxpool.New(context.Background(), url)
if err != nil {
log.Fatal("Cloud not create database pool")
panic(err)
}
return DbContainer{
pool: dbpool,
}
}
func (db DbContainer) Close() {
db.pool.Close()
}
func (db DbContainer) Query(query string, args ...any) (pgx.Rows, error) {
return db.pool.Query(context.Background(), query, args...)
}
func (db DbContainer) Exec(query string, args ...any) (pgconn.CommandTag, error) {
return db.pool.Exec(context.Background(), query, args...)
}
func (db DbContainer) Begin() (pgx.Tx, error) {
return db.pool.Begin(context.Background())
}