skeleton/internal/database/db.go

62 lines
1.5 KiB
Go
Raw Normal View History

2019-05-14 14:11:03 +02:00
package database
//go:generate sh -c "rm -f *.xo.go"
//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
}
2019-08-22 00:48:48 +02:00
// IsErrNoRows returns true if the error indicates that no rows were
// returned from the database.
2019-05-14 14:11:03 +02:00
func IsErrNoRows(err error) bool {
return err == sql.ErrNoRows
}
2019-08-22 00:48:48 +02:00
// IsErrUniqueViolation returns true if the error indicates that a UNIQUE
// constraint violation has occured.
2019-05-14 14:11:03 +02:00
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
}
2019-08-22 00:48:48 +02:00
// IsErrForeignKeyViolation returns true if the error indicates that a
// FOREIGN KEY constraint has been violated due to the requested changes.
2019-05-14 14:11:03 +02:00
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
}