Files
mangezmieux/mangezmieux-backend/internal/postgres/database_postgresql.go
2024-07-19 17:04:42 +02:00

36 lines
769 B
Go

package postgres
import (
"database/sql"
"github.com/lib/pq"
"mangezmieux-backend/internal/logger"
)
const (
pgCodeUniqueViolation = "23505"
pgCodeForeingKeyViolation = "23503"
)
func HandlePgError(e *pq.Error) error {
if e.Code == pgCodeUniqueViolation {
return NewDAOError(ErrTypeDuplicate, e)
}
if e.Code == pgCodeForeingKeyViolation {
return NewDAOError(ErrTypeForeignKeyViolation, e)
}
return e
}
func NewDatabasePostgreSQL(connectionURI string) *sql.DB {
db, err := sql.Open("postgres", connectionURI)
if err != nil {
logger.GetLogger().WithError(err).Fatal("Unable to get a connection to the postgres db")
}
err = db.Ping()
if err != nil {
logger.GetLogger().WithError(err).Fatal("Unable to ping the postgres db")
}
return db
}