github.com/ncruces/go-sqlite3@v0.15.1-0.20240520133447-53eef1510ff0/driver/savepoint_test.go (about)

     1  package driver_test
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/ncruces/go-sqlite3/driver"
     8  	_ "github.com/ncruces/go-sqlite3/embed"
     9  	_ "github.com/ncruces/go-sqlite3/tests/testcfg"
    10  	_ "github.com/ncruces/go-sqlite3/vfs/memdb"
    11  )
    12  
    13  func ExampleSavepoint() {
    14  	db, err := driver.Open("file:/test.db?vfs=memdb", nil)
    15  	if err != nil {
    16  		log.Fatal(err)
    17  	}
    18  	defer db.Close()
    19  
    20  	_, err = db.Exec(`CREATE TABLE users (id INT, name VARCHAR(10))`)
    21  	if err != nil {
    22  		log.Fatal(err)
    23  	}
    24  
    25  	err = func() error {
    26  		tx, err := db.Begin()
    27  		if err != nil {
    28  			return err
    29  		}
    30  		defer tx.Rollback()
    31  
    32  		stmt, err := tx.Prepare(`INSERT INTO users (id, name) VALUES (?, ?)`)
    33  		if err != nil {
    34  			return err
    35  		}
    36  		defer stmt.Close()
    37  
    38  		_, err = stmt.Exec(0, "go")
    39  		if err != nil {
    40  			return err
    41  		}
    42  
    43  		_, err = stmt.Exec(1, "zig")
    44  		if err != nil {
    45  			return err
    46  		}
    47  
    48  		savept := driver.Savepoint(tx)
    49  
    50  		_, err = stmt.Exec(2, "whatever")
    51  		if err != nil {
    52  			return err
    53  		}
    54  
    55  		err = savept.Rollback()
    56  		if err != nil {
    57  			return err
    58  		}
    59  
    60  		_, err = stmt.Exec(3, "rust")
    61  		if err != nil {
    62  			return err
    63  		}
    64  
    65  		return tx.Commit()
    66  	}()
    67  	if err != nil {
    68  		log.Fatal(err)
    69  	}
    70  
    71  	rows, err := db.Query(`SELECT id, name FROM users`)
    72  	if err != nil {
    73  		log.Fatal(err)
    74  	}
    75  	defer rows.Close()
    76  
    77  	for rows.Next() {
    78  		var id, name string
    79  		err = rows.Scan(&id, &name)
    80  		if err != nil {
    81  			log.Fatal(err)
    82  		}
    83  		fmt.Printf("%s %s\n", id, name)
    84  	}
    85  	// Output:
    86  	// 0 go
    87  	// 1 zig
    88  	// 3 rust
    89  }