- Updated DbHandler to accept configuration parameters instead of using environment variables directly. - Moved database queries from handler.go to a dedicated queries package for better organization and separation of concerns. - Implemented error handling in query functions to provide more informative error messages. - Refactored image handling to utilize the new queries package for database interactions. - Cleaned up unused code and comments across various files. - Improved overall code readability and maintainability.
54 lines
1.3 KiB
Go
54 lines
1.3 KiB
Go
package db
|
|
|
|
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
|
|
}
|
|
|
|
type Configs struct {
|
|
Host string
|
|
Dbname string
|
|
Port string
|
|
User string
|
|
Password string
|
|
}
|
|
|
|
func NewDbHandler(configs Configs) *DbHandler {
|
|
fmt.Println("Connecting to db")
|
|
ctx := context.Background()
|
|
|
|
if configs.Host == "" || configs.Dbname == "" || configs.Port == "" || configs.User == "" || configs.Password == "" {
|
|
fmt.Println("Environment variables for database connection are not set")
|
|
return nil
|
|
}
|
|
|
|
connStr := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s?sslmode=disable", configs.User, configs.Password, configs.Host, configs.Port, configs.Dbname)
|
|
fmt.Printf("Connecting to db with connection string: %s", connStr)
|
|
config, err := pgxpool.ParseConfig(connStr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
config.ConnConfig.Tracer = NewMultiQueryTracer(NewLoggingQueryTracer(slog.Default()))
|
|
|
|
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}
|
|
}
|