|
| 1 | +package integration |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/smarty/gunit/v2" |
| 8 | + "github.com/smarty/gunit/v2/better" |
| 9 | + "github.com/smarty/gunit/v2/should" |
| 10 | + "github.com/smarty/sqldb/v3" |
| 11 | + |
| 12 | + _ "github.com/mattn/go-sqlite3" |
| 13 | +) |
| 14 | + |
| 15 | +const CreateInsert = ` |
| 16 | +
|
| 17 | +DROP TABLE IF EXISTS sqldb_integration_test; |
| 18 | +
|
| 19 | +CREATE TABLE sqldb_integration_test ( |
| 20 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 21 | + name TEXT NOT NULL |
| 22 | +); |
| 23 | +
|
| 24 | +INSERT INTO sqldb_integration_test (name) VALUES (?); |
| 25 | +INSERT INTO sqldb_integration_test (name) VALUES (?); |
| 26 | +INSERT INTO sqldb_integration_test (name) VALUES (?); |
| 27 | +INSERT INTO sqldb_integration_test (name) VALUES (?); |
| 28 | +` |
| 29 | +const query = ` |
| 30 | +SELECT id, name |
| 31 | + FROM sqldb_integration_test; |
| 32 | +` |
| 33 | + |
| 34 | +func Test(t *testing.T) { |
| 35 | + db, err := sql.Open("sqlite3", ":memory:") |
| 36 | + gunit.So(t, err, better.BeNil) |
| 37 | + |
| 38 | + tx, err := db.BeginTx(t.Context(), nil) |
| 39 | + gunit.So(t, err, better.BeNil) |
| 40 | + |
| 41 | + count, err := sqldb.ExecuteStatements(t.Context(), tx, CreateInsert, |
| 42 | + "a", |
| 43 | + "b", |
| 44 | + "c", |
| 45 | + "d", |
| 46 | + ) |
| 47 | + gunit.So(t, err, better.BeNil) |
| 48 | + gunit.So(t, count, should.Equal, 4) |
| 49 | + |
| 50 | + rows, err := tx.QueryContext(t.Context(), query) |
| 51 | + gunit.So(t, err, should.BeNil) |
| 52 | + |
| 53 | + records := map[int]string{} |
| 54 | + err = sqldb.BindAll(rows, err, func(scanner sqldb.Scanner) error { |
| 55 | + var id int |
| 56 | + var name string |
| 57 | + defer func() { records[id] = name }() |
| 58 | + return scanner.Scan(&id, &name) |
| 59 | + }) |
| 60 | + gunit.So(t, err, better.BeNil) |
| 61 | + gunit.So(t, records, should.Equal, map[int]string{ |
| 62 | + 1: "a", |
| 63 | + 2: "b", |
| 64 | + 3: "c", |
| 65 | + 4: "d", |
| 66 | + }) |
| 67 | + |
| 68 | + err = tx.Rollback() |
| 69 | + gunit.So(t, err, better.BeNil) |
| 70 | +} |
0 commit comments