wip
This commit is contained in:
32
mangezmieux-backend/internal/postgres/database_error.go
Executable file
32
mangezmieux-backend/internal/postgres/database_error.go
Executable file
@@ -0,0 +1,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Type int
|
||||
|
||||
const (
|
||||
ErrTypeNotFound Type = iota
|
||||
ErrTypeDuplicate
|
||||
ErrTypeForeignKeyViolation
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
Cause error
|
||||
Type Type
|
||||
}
|
||||
|
||||
func NewDAOError(t Type, cause error) error {
|
||||
return &Error{
|
||||
Type: t,
|
||||
Cause: cause,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e.Cause != nil {
|
||||
return fmt.Sprintf("Type %d: %s", e.Type, e.Cause.Error())
|
||||
}
|
||||
return fmt.Sprintf("Type %d: no cause given", e.Type)
|
||||
}
|
||||
35
mangezmieux-backend/internal/postgres/database_postgresql.go
Normal file
35
mangezmieux-backend/internal/postgres/database_postgresql.go
Normal file
@@ -0,0 +1,35 @@
|
||||
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
|
||||
}
|
||||
11
mangezmieux-backend/internal/postgres/setup.go
Normal file
11
mangezmieux-backend/internal/postgres/setup.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package postgres
|
||||
|
||||
import "mangezmieux-backend/internal/injector"
|
||||
|
||||
const DatabaseKey = "POSTGRES"
|
||||
|
||||
func Setup(inj *injector.Injector, connectionURI string) {
|
||||
client := NewDatabasePostgreSQL(connectionURI)
|
||||
|
||||
inj.Set(DatabaseKey, client)
|
||||
}
|
||||
Reference in New Issue
Block a user