2025-08-21 13:54:15 +02:00
|
|
|
package db
|
2025-08-04 17:45:44 +02:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"log/slog"
|
|
|
|
|
|
|
|
|
|
pgxuuid "github.com/jackc/pgx-gofrs-uuid"
|
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type DbHandler struct {
|
|
|
|
|
Dbpool *pgxpool.Pool
|
|
|
|
|
Ctx context.Context
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-22 10:11:07 +02:00
|
|
|
type Configs struct {
|
|
|
|
|
Host string
|
|
|
|
|
Dbname string
|
|
|
|
|
Port string
|
|
|
|
|
User string
|
|
|
|
|
Password string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewDbHandler(configs Configs) *DbHandler {
|
2025-08-04 17:45:44 +02:00
|
|
|
fmt.Println("Connecting to db")
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
|
2025-08-22 10:11:07 +02:00
|
|
|
if configs.Host == "" || configs.Dbname == "" || configs.Port == "" || configs.User == "" || configs.Password == "" {
|
|
|
|
|
fmt.Println("Environment variables for database connection are not set")
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2025-08-04 17:45:44 +02:00
|
|
|
|
2025-08-22 10:11:07 +02:00
|
|
|
connStr := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s?sslmode=disable", configs.User, configs.Password, configs.Host, configs.Port, configs.Dbname)
|
2025-08-04 17:45:44 +02:00
|
|
|
fmt.Printf("Connecting to db with connection string: %s", connStr)
|
|
|
|
|
config, err := pgxpool.ParseConfig(connStr)
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
2025-08-21 13:54:15 +02:00
|
|
|
config.ConnConfig.Tracer = NewMultiQueryTracer(NewLoggingQueryTracer(slog.Default()))
|
2025-08-04 17:45:44 +02:00
|
|
|
|
|
|
|
|
config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
|
|
|
|
pgxuuid.Register(conn.TypeMap())
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
dbpool, err := pgxpool.NewWithConfig(ctx, config)
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(err)
|
|
|
|
|
}
|
|
|
|
|
fmt.Println("Connected to db")
|
|
|
|
|
|
|
|
|
|
return &DbHandler{Dbpool: dbpool, Ctx: ctx}
|
|
|
|
|
}
|