package database //go:generate sh -c "rm -f *.xo.go" //go:generate xo $DATABASE_DSN --escape-all --template-path templates/ --package database -o . //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 } // IsErrNoRows returns true if the error indicates that no rows were // returned from the database. func IsErrNoRows(err error) bool { return err == sql.ErrNoRows } // IsErrUniqueViolation returns true if the error indicates that a UNIQUE // constraint violation has occured. 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 } // IsErrForeignKeyViolation returns true if the error indicates that a // FOREIGN KEY constraint has been violated due to the requested changes. 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 }