Skip to content

Instantly share code, notes, and snippets.

@babarot
Last active June 24, 2023 06:56
Show Gist options
  • Save babarot/f221154ce9a71e90746cbab3d1bfb8fe to your computer and use it in GitHub Desktop.
Save babarot/f221154ce9a71e90746cbab3d1bfb8fe to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sqlx.Open("sqlite3", "file:test.db")
if err != nil {
panic(err)
}
defer db.Close()
if err := dbWrite(db); err != nil {
panic(err)
}
}
func dbWrite(db *sqlx.DB) error {
tx, err := db.Beginx()
if err != nil {
return err
}
defer tx.Rollback()
// db.Exec でトランザクション (tx.Exec) を利用しない
_, err = db.Exec("INSERT INTO authors (name, url) VALUES (?, ?)", "tanaka", "https://tanaka.com")
if err != nil {
return err
}
// DB 操作の途中でエラー、ロールバックされることを期待する
if true {
return errors.New("error!")
}
// db.Exec でトランザクション (tx.Exec) を利用しない
_, err = db.Exec("INSERT INTO authors (name, url) VALUES (?, ?)", "toyoda", "https://toyota.com/")
if err != nil {
return err
}
return tx.Commit()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment