1 // Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
3 // Use of this source code is governed by an MIT-style
4 // license that can be found in the LICENSE file.
20 func TestNamedParams(t *testing.T) {
21 tempFilename := TempFilename(t)
22 defer os.Remove(tempFilename)
23 db, err := sql.Open("sqlite3", tempFilename)
25 t.Fatal("Failed to open database:", err)
30 create table foo (id integer, name text, extra text);
33 t.Error("Failed to call db.Query:", err)
36 _, err = db.Exec(`insert into foo(id, name, extra) values(:id, :name, :name)`, sql.Named("name", "foo"), sql.Named("id", 1))
38 t.Error("Failed to call db.Exec:", err)
41 row := db.QueryRow(`select id, extra from foo where id = :id and extra = :extra`, sql.Named("id", 1), sql.Named("extra", "foo"))
43 t.Error("Failed to call db.QueryRow")
47 err = row.Scan(&id, &extra)
49 t.Error("Failed to db.Scan:", err)
51 if id != 1 || extra != "foo" {
52 t.Error("Failed to db.QueryRow: not matched results")
57 testTableStatements = []string{
58 `DROP TABLE IF EXISTS test_table`,
60 CREATE TABLE IF NOT EXISTS test_table (
61 key1 VARCHAR(64) PRIMARY KEY,
62 key_id VARCHAR(64) NOT NULL,
63 key2 VARCHAR(64) NOT NULL,
64 key3 VARCHAR(64) NOT NULL,
65 key4 VARCHAR(64) NOT NULL,
66 key5 VARCHAR(64) NOT NULL,
67 key6 VARCHAR(64) NOT NULL,
71 letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
74 func randStringBytes(n int) string {
77 b[i] = letterBytes[rand.Intn(len(letterBytes))]
82 func initDatabase(t *testing.T, db *sql.DB, rowCount int64) {
83 for _, query := range testTableStatements {
84 _, err := db.Exec(query)
89 for i := int64(0); i < rowCount; i++ {
90 query := `INSERT INTO test_table
91 (key1, key_id, key2, key3, key4, key5, key6, data)
93 (?, ?, ?, ?, ?, ?, ?, ?);`
94 args := []interface{}{
103 randStringBytes(2048),
105 _, err := db.Exec(query, args...)
112 func TestShortTimeout(t *testing.T) {
113 srcTempFilename := TempFilename(t)
114 defer os.Remove(srcTempFilename)
116 db, err := sql.Open("sqlite3", srcTempFilename)
121 initDatabase(t, db, 100)
123 ctx, cancel := context.WithTimeout(context.Background(), 1*time.Microsecond)
125 query := `SELECT key1, key_id, key2, key3, key4, key5, key6, data
128 _, err = db.QueryContext(ctx, query)
129 if err != nil && err != context.DeadlineExceeded {
132 if ctx.Err() != nil && ctx.Err() != context.DeadlineExceeded {
137 func TestExecCancel(t *testing.T) {
138 db, err := sql.Open("sqlite3", ":memory:")
144 if _, err = db.Exec("create table foo (id integer primary key)"); err != nil {
148 for n := 0; n < 100; n++ {
149 ctx, cancel := context.WithCancel(context.Background())
150 _, err = db.ExecContext(ctx, "insert into foo (id) values (?)", n)