2019-05-14 14:11:03 +02:00
|
|
|
package database
|
|
|
|
|
|
|
|
//go:generate sh -c "rm -f *.xo.go"
|
2019-07-26 11:21:56 +02:00
|
|
|
//go:generate xo $DATABASE_DSN --escape-all --template-path templates/ --package database -o .
|
2019-05-14 14:11:03 +02:00
|
|
|
//go:generate sh -c "rm -f schemamigration.xo.go"
|
|
|
|
//go:generate
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"github.com/lib/pq"
|
|
|
|
)
|
|
|
|
|
|
|
|
// New initializes a new postgres database connection pool
|
|
|
|
func New(dsn string) (*sqlx.DB, error) {
|
|
|
|
conn, err := sqlx.Open("postgres", dsn)
|
|
|
|
return conn, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsErrNoRows(err error) bool {
|
|
|
|
return err == sql.ErrNoRows
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsErrUniqueViolation(err error) bool {
|
|
|
|
// see if we can cast the error to a Database error type
|
|
|
|
pqErr, ok := err.(*pq.Error)
|
|
|
|
if !ok {
|
|
|
|
// Wrong error type
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// check if error is "unique constraint violation"
|
|
|
|
if pqErr.Code != "23505" {
|
|
|
|
// if thats NOT the case, it's another error
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsErrForeignKeyViolation(err error) bool {
|
|
|
|
// see if we can cast the error to a Database error type
|
|
|
|
pqErr, ok := err.(*pq.Error)
|
|
|
|
if !ok {
|
|
|
|
// Wrong error type
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// check if error is "foreign key violation"
|
|
|
|
if pqErr.Code != "23503" {
|
|
|
|
// if thats NOT the case, it's another error
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|