Skip to content

Commit

Permalink
Fix ExampleExec_withTx
Browse files Browse the repository at this point in the history
Run all queries of ExampleExec_withTx on a single connection. This is
enforced using db.Conn().
  • Loading branch information
dolmen committed Nov 5, 2023
1 parent 4822ba8 commit 104c6c0
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions stmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,16 @@ func ExampleExec_withTx() {
check("Open", err)
defer db.Close()

conn, err := db.Conn(ctx)
check("Conn", err)

// POI = Point of Interest
_, err = db.ExecContext(ctx, `CREATE TABLE poi (lat DECIMAL, lon DECIMAL, name VARCHAR(255))`)
_, err = conn.ExecContext(ctx, `CREATE TABLE poi (lat DECIMAL, lon DECIMAL, name VARCHAR(255))`)
check("Create table", err)

var countPOI func(ctx context.Context) (int64, error)
closeCountPOI, err := sqlfunc.QueryRow(
ctx, db,
ctx, conn,
`SELECT COUNT(*) FROM poi`,
&countPOI,
)
Expand All @@ -135,7 +138,7 @@ func ExampleExec_withTx() {
check("Prepare insertPOI", err)
defer closeInsertPOI()

tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
tx, err := conn.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
check("BeginTx", err)
defer tx.Rollback()

Expand All @@ -144,18 +147,18 @@ func ExampleExec_withTx() {

nbRows, err := res.RowsAffected()
check("RowsAffected", err)
fmt.Println("Rows inserted:", nbRows)

res, err = insertPOI(ctx, tx, 47.2009, 0.6317, "Villeperdue")
check("newPOI", err)

nbRows, err = res.RowsAffected()
check("RowsAffected", err)
fmt.Println("Rows inserted:", nbRows)

/*
// FIXME count here too
nbPOI, err = countPOI(ctx)
if err != nil {
log.Println("countPOI after insert:", err)
return
}
fmt.Println("countPOI after insert:", nbPOI)
*/
nbPOI, err = countPOI(ctx)
check("countPOI", err)
fmt.Println("countPOI after inserts:", nbPOI)

tx.Rollback()

Expand All @@ -167,5 +170,7 @@ func ExampleExec_withTx() {
// Output:
// countPOI before insert: 0
// Rows inserted: 1
// Rows inserted: 1
// countPOI after inserts: 2
// countPOI after rollback: 0
}

0 comments on commit 104c6c0

Please sign in to comment.