首頁  >  文章  >  後端開發  >  使用事務和 squirrel 進行 Golang postgresql 查詢

使用事務和 squirrel 進行 Golang postgresql 查詢

WBOY
WBOY轉載
2024-02-06 09:54:08986瀏覽

使用事务和 squirrel 进行 Golang postgresql 查询

問題內容

我了解如何單獨使用松鼠和事務,但我不了解如何一起使用它們。我什麼時候應該回滾或提交? 我的嘗試正確與否?如果不是,我錯在哪裡......

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
}

據我了解,我正在嘗試在 postgresql 中執行查詢後回滾或提交


#正確答案


你的努力是偉大的。但是 ....runwith(db.repo.getdatabase()) 在這種情況下是不正確的。因為您應該傳遞交易連線 tx 。指示 squirrel 使用交易物件作為查詢的資料庫連線。

如果您使用資料庫連接而不是交易連接,squirrel 查詢將不會成為交易的一部分。每個查詢將單獨執行並立即提交到資料庫。

我們也可以使用 defer 語句更新 rollbackcommit 語句,這將確保在函數退出之前正確處理並完成交易。

這是更新後的程式碼..

tx, err := db.repo.GetDatabase().Begin()
if err != nil {
    return nil, err
}

// added defer rollback and commit
defer func() {
    if err != nil {
        fmt.Println("An error happened while executing the queries - ", err)
        tx.Rollback()
        return
    }
    err = tx.Commit()
}()

response := make([]storage.URLStorage, 0, len(urls))

sb := squirrel.StatementBuilder.
    Insert("dependencies").
    Columns("correlation_id", "name", "age").
    PlaceholderFormat(squirrel.Dollar).
    RunWith(tx)

for _, human := range humans {
    sb = sb.Values(
        human.CorrelationID,
        human.Name,
        human.Age,
    )
}

// the error will be handled by the defer
_, err = sb.Exec()

// you can execute multiple queries with the transaction
for _, human := range someOtheSlice {
    sb = sb.Values(
        human.CorrelationID,
        human.Name,
        human.Age,
    )
}

_, err = sb.Exec()

// If any error happened this query executions, all will be roll backed with the defer

希望這有幫助。

另請參閱

#

以上是使用事務和 squirrel 進行 Golang postgresql 查詢的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除