Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get error details for a SQL Insert done in Go?

Tags:

postgresql

go

I'm trying to insert some data into a Database with Go. Due to the nature of the data (large export from another tool), I hit sometimes some of my models constraints.

With the following Go code

_, err := db.Exec(query, params...)
if err != nil {
    log.Print(err)
}

I simply get an output like that

2023/03/10 09:40:26 pq: insert or update on table "table" violates foreign key constraint "table_constraint"
exit status 1

When I do the same Insert from pgAdmin, I get the same error but also some DETAIL information.

DETAIL:  Key (id)=(abc) is not present in table "table_2".

Is there a way to get this DETAIL information in Go as well? I checked the Documentation and couldn't find anything, but maybe there is a way?

like image 252
Richy Avatar asked Feb 02 '26 11:02

Richy


1 Answers

Generally the db driver that you're using will have a custom error type. You can assert the err value to this error type and then, depending on the driver's implementation, you should be able to glean more details about the issue. For example, when using github.com/lib/pq, you can assert to *pq.Error and read its Detail field:

_, err := db.Exec(query, params...)
if err != nil {
    if e, ok := err.(*pq.Error); ok {
        log.Print(e.Detail)
    }
}
like image 81
mkopriva Avatar answered Feb 05 '26 02:02

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!