I understand how to use squirrel and transactions separately, but I don't understand how to use them together. When should I rollback or commit? Is my attempt correct or not? If not, where am I wrong...
tx, err := db.repo.GetDatabase().Begin()
if err != nil {
return nil, err
}
sb := squirrel.StatementBuilder.
Insert("dependencies").
Columns("correlation_id", "name", "age").
PlaceholderFormat(squirrel.Dollar).
RunWith(db.repo.GetDatabase())
for _, human:= range humans{
sb = sb.Values(
human.CorrelationID,
human.Name,
human.Age,
)
}
_, err = sb.Exec()
if err != nil {
if err := tx.Rollback(); err != nil {
return nil, err
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
As I understand it, I'm trying to rollback or commit after the query is executed in postgresql
Your efforts are great. But
....RunWith(db.repo.GetDatabase())is incorrect in this case. As you should pass the transaction connectiontxinstead. Directing Squirrel to use the transaction object as the query's database connection.If you use the DB connection instead of the transaction connection, the Squirrel queries will not be part of the transaction. Each query will be executed individually and committed to the database instantly.
Also we can update the
RollBackandCommitwithdeferstatement, It will ensure transaction is properly handled and finalised before the function exits.Here is the updated code..
Hope this helps.
Also see