This commit is contained in:
Jeffrey Duroyon
2019-04-04 14:29:48 +02:00
committed by Jeffrey Duroyon
parent 0df6d64c35
commit 33db360b03
38 changed files with 1476 additions and 1 deletions

View File

@@ -0,0 +1,32 @@
package dao
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)
}

View File

@@ -0,0 +1,43 @@
package postgresql
import (
"database/sql"
"fmt"
"github.com/kratisto/mam-contract/internal/storage/dao"
"github.com/kratisto/mam-contract/internal/utils"
"github.com/lib/pq"
)
const (
pgCodeUniqueViolation = "23505"
pgCodeForeingKeyViolation = "23503"
)
func HandlePgError(e *pq.Error) error {
if e.Code == pgCodeUniqueViolation {
return dao.NewDAOError(dao.ErrTypeDuplicate, e)
}
if e.Code == pgCodeForeingKeyViolation {
return dao.NewDAOError(dao.ErrTypeForeignKeyViolation, e)
}
return e
}
type DatabasePostgreSQL struct {
Session *sql.DB
}
func NewDatabasePostgreSQL(connectionURI string) *DatabasePostgreSQL {
db, err := sql.Open("postgres", connectionURI)
if err != nil {
utils.GetLogger().WithError(err).Fatal("Unable to get a connection to the postgres db")
}
err = db.Ping()
if err != nil {
fmt.Println(err)
utils.GetLogger().WithError(err).Fatal("Unable to ping the postgres db")
}
return &DatabasePostgreSQL{Session: db}
}

View File

@@ -0,0 +1,13 @@
package postgresql
import (
"github.com/kratisto/mam-contract/internal/utils"
)
var DatabaseKey = "POSTGRES"
func Setup(injector *utils.Injector, connectionUri string) {
database := NewDatabasePostgreSQL(connectionUri)
injector.Set(DatabaseKey, database)
}