I use postgres COPY in my Go backend. Copy is the only operation inside transaction. Should I roll it back if it failed?
func (pc *Postgres) Copy(records [][]interface{}) error {
tx, err := pc.db.Begin()
if err != nil {
return errors.Wrap(err, "can't open transaction")
}
stmt, err := tx.Prepare(pq.CopyIn(pc.table, pc.columns...))
if err != nil {
return errors.Wrap(err, "can't prepare stmt")
}
for _, record := range records {
if _, err := stmt.Exec(record...); err != nil {
return errors.Wrap(err, "error exec record")
}
}
if _, err = stmt.Exec(); err != nil {
return errors.Wrap(err, "error exec stmt")
}
if err = stmt.Close(); err != nil {
return errors.Wrap(err, "error close stmt")
}
if err = tx.Commit(); err != nil {
return errors.Wrap(err, "error commit transaction")
}
return nil
}
As far as I understand if \copy
fails transaction will be aborted(link) and rolled back.
However in officials lib/pq
examples I see they always use rollback(but they have more than one operation).
Could somebody please guide me through these nuances?