// Package database contains the database queries. package database // this package uses github.com/kyleconroy/sqlc to generate // code from SQL queries. You only need to put sqlc in PATH, if // the models have to be regenerated. //go:generate sqlc compile //go:generate bash -c "rm -f *.sql.go db.go models.go querier.go" //go:generate sqlc 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 }