sqlc-dev / sqlc

Generate type-safe code from SQL
https://sqlc.dev
MIT License
13.58k stars 812 forks source link

Returning pgErrors option #3570

Closed ahmedabdou14 closed 2 months ago

ahmedabdou14 commented 2 months ago

What do you want to change?

Hi, I am fairly new to sqlc, i like it alot, but I truly struggled with extracting proper data from the errors out of queries. SQLC queries return the normal error which is just a string, while pg error that pgx uses for example has error codes and other very useful attributes having a way to maybe instruct sqlc to generate code that adopts pgError instead of error would be extremely helpful

example usecase:

inserting a duplicate record into a users table would generate a message like this ERROR: duplicate key value violates unique constraint "users_email_key" (SQLSTATE 23505) such error messages cannot be sent to the client, it has to be formatted in a way or another to hide the nature of our database and be more user friendly.

What database engines need to be changed?

PostgreSQL

What programming language backends need to be changed?

Go

ahmedabdou14 commented 2 months ago

Well, turns out I can still parse that error message using pgconn.PgError itself actually

res, err := sqlc.somequery(ctx, ...)
if err != nil {
    var pgErr *pgconn.PgError
    if errors.As(err, &pgErr) {
        return &fiber.Error{
            Code:    fiber.StatusBadRequest,
            Message: pgErr.Message,
        }
    }
}