Home >Backend Development >Golang >When will go goose transaction be submitted?

When will go goose transaction be submitted?

王林
王林forward
2024-02-08 21:54:20621browse

go goose 事务什么时候提交?

php editor Yuzai is here to answer a common question: "When will the go goose transaction be submitted?" In the Go language, the submission of the transaction depends on the specific database driver . Generally speaking, when performing a transaction commit operation, the database will submit all modification operations of the current transaction to the database at one time. This ensures the atomicity of the transaction, that is, either all commits succeed or all rollbacks fail. Therefore, the transaction submission time is when the transaction commit operation is performed, not at the beginning or end of the transaction. For specific usage methods, please refer to the relevant database driver documentation.

Question content

  • I have some code that needs to be run in tx as shown below
  • I generated a go sql migration as described in the official documentation of go goose

my question is:

  • When are these transactions actually committed to the database?
  • I force the use of tx.commit() to commit the migration. This is my migration file in go:
func Up00002(tx *sql.Tx) error {
    _, err := tx.Exec("UPDATE users SET username='admin' WHERE username='root';")
    if err != nil {
        return err
    }

    if err = tx.Commit(); err != nil {
        return fmt.Errorf("error during committing the transaction: %w", err)
    }


    return nil
}

I can't run the above migrations after the down part because when I run them I get errtxdone (source). I still want to run go migration up00002 multiple times (for testing). How can I do this? What am I doing wrong here?

Workaround

So just browsing their documentation here will show that the commit has already happened in the AddMigrations call - this is using ofc transactions, handled internally by go goose - very nice :)

The same is true for sql, as we can seehere

pkg also provides the --no-transaction option, which we can use to fully control the db object - awesome!

The above is the detailed content of When will go goose transaction be submitted?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete