package postgres import ( "errors" "strconv" "strings" "github.com/jackc/pgx/v5/pgconn" ) // uniqueViolation is the SQLSTATE class PostgreSQL raises for a duplicate // key, whichever constraint caught it. const uniqueViolation = "23505" // isUniqueViolation reports whether err is PostgreSQL complaining about a // duplicate key. func isUniqueViolation(err error) bool { var pgErr *pgconn.PgError return errors.As(err, &pgErr) && pgErr.Code == uniqueViolation } // rebind turns the `?` placeholders the shared component stores are written // with into PostgreSQL's numbered form. It is a straight scan rather than a // SQL parser, which is safe because the statements it sees are constants in // this repository: none of them contains a `?` inside a string literal, and // none is built from user input beyond a run of placeholders. func rebind(query string) string { if !strings.Contains(query, "?") { return query } var b strings.Builder b.Grow(len(query) + 8) n := 0 for i := range len(query) { if query[i] != '?' { b.WriteByte(query[i]) continue } n++ b.WriteByte('$') b.WriteString(strconv.Itoa(n)) } return b.String() }