| 1 |
// Copyright (C) 2019 Yasuhiro Matsumoto <[email protected]>. |
| 2 |
// |
| 3 |
// Use of this source code is governed by an MIT-style |
| 4 |
// license that can be found in the LICENSE file. |
| 5 |
|
| 6 |
//go:build cgo |
| 7 |
// +build cgo |
| 8 |
|
| 9 |
package sqlite3 |
| 10 |
|
| 11 |
import ( |
| 12 |
"context" |
| 13 |
"database/sql" |
| 14 |
"database/sql/driver" |
| 15 |
"errors" |
| 16 |
"fmt" |
| 17 |
"math/rand" |
| 18 |
"os" |
| 19 |
"sync" |
| 20 |
"testing" |
| 21 |
"time" |
| 22 |
) |
| 23 |
|
| 24 |
func TestNamedParams(t *testing.T) { |
| 25 |
tempFilename := TempFilename(t) |
| 26 |
defer os.Remove(tempFilename) |
| 27 |
db, err := sql.Open("sqlite3", tempFilename) |
| 28 |
if err != nil { |
| 29 |
t.Fatal("Failed to open database:", err) |
| 30 |
} |
| 31 |
defer db.Close() |
| 32 |
|
| 33 |
_, err = db.Exec(` |
| 34 |
create table foo (id integer, name text, extra text); |
| 35 |
`) |
| 36 |
if err != nil { |
| 37 |
t.Error("Failed to call db.Query:", err) |
| 38 |
} |
| 39 |
|
| 40 |
_, err = db.Exec(`insert into foo(id, name, extra) values(:id, :name, :name)`, sql.Named("name", "foo"), sql.Named("id", 1)) |
| 41 |
if err != nil { |
| 42 |
t.Error("Failed to call db.Exec:", err) |
| 43 |
} |
| 44 |
|
| 45 |
row := db.QueryRow(`select id, extra from foo where id = :id and extra = :extra`, sql.Named("id", 1), sql.Named("extra", "foo")) |
| 46 |
if row == nil { |
| 47 |
t.Error("Failed to call db.QueryRow") |
| 48 |
} |
| 49 |
var id int |
| 50 |
var extra string |
| 51 |
err = row.Scan(&id, &extra) |
| 52 |
if err != nil { |
| 53 |
t.Error("Failed to db.Scan:", err) |
| 54 |
} |
| 55 |
if id != 1 || extra != "foo" { |
| 56 |
t.Error("Failed to db.QueryRow: not matched results") |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
var ( |
| 61 |
testTableStatements = []string{ |
| 62 |
`DROP TABLE IF EXISTS test_table`, |
| 63 |
` |
| 64 |
CREATE TABLE IF NOT EXISTS test_table ( |
| 65 |
key1 VARCHAR(64) PRIMARY KEY, |
| 66 |
key_id VARCHAR(64) NOT NULL, |
| 67 |
key2 VARCHAR(64) NOT NULL, |
| 68 |
key3 VARCHAR(64) NOT NULL, |
| 69 |
key4 VARCHAR(64) NOT NULL, |
| 70 |
key5 VARCHAR(64) NOT NULL, |
| 71 |
key6 VARCHAR(64) NOT NULL, |
| 72 |
data BLOB NOT NULL |
| 73 |
);`, |
| 74 |
} |
| 75 |
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 76 |
) |
| 77 |
|
| 78 |
func randStringBytes(n int) string { |
| 79 |
b := make([]byte, n) |
| 80 |
for i := range b { |
| 81 |
b[i] = letterBytes[rand.Intn(len(letterBytes))] |
| 82 |
} |
| 83 |
return string(b) |
| 84 |
} |
| 85 |
|
| 86 |
func initDatabase(t *testing.T, db *sql.DB, rowCount int64) { |
| 87 |
for _, query := range testTableStatements { |
| 88 |
_, err := db.Exec(query) |
| 89 |
if err != nil { |
| 90 |
t.Fatal(err) |
| 91 |
} |
| 92 |
} |
| 93 |
for i := int64(0); i < rowCount; i++ { |
| 94 |
query := `INSERT INTO test_table |
| 95 |
(key1, key_id, key2, key3, key4, key5, key6, data) |
| 96 |
VALUES |
| 97 |
(?, ?, ?, ?, ?, ?, ?, ?);` |
| 98 |
args := []interface{}{ |
| 99 |
randStringBytes(50), |
| 100 |
fmt.Sprint(i), |
| 101 |
randStringBytes(50), |
| 102 |
randStringBytes(50), |
| 103 |
randStringBytes(50), |
| 104 |
randStringBytes(50), |
| 105 |
randStringBytes(50), |
| 106 |
randStringBytes(50), |
| 107 |
randStringBytes(2048), |
| 108 |
} |
| 109 |
_, err := db.Exec(query, args...) |
| 110 |
if err != nil { |
| 111 |
t.Fatal(err) |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
func TestShortTimeout(t *testing.T) { |
| 117 |
srcTempFilename := TempFilename(t) |
| 118 |
defer os.Remove(srcTempFilename) |
| 119 |
|
| 120 |
db, err := sql.Open("sqlite3", srcTempFilename) |
| 121 |
if err != nil { |
| 122 |
t.Fatal(err) |
| 123 |
} |
| 124 |
defer db.Close() |
| 125 |
initDatabase(t, db, 100) |
| 126 |
|
| 127 |
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Microsecond) |
| 128 |
defer cancel() |
| 129 |
query := `SELECT key1, key_id, key2, key3, key4, key5, key6, data |
| 130 |
FROM test_table |
| 131 |
ORDER BY key2 ASC` |
| 132 |
_, err = db.QueryContext(ctx, query) |
| 133 |
if err != nil && err != context.DeadlineExceeded { |
| 134 |
t.Fatal(err) |
| 135 |
} |
| 136 |
if ctx.Err() != nil && ctx.Err() != context.DeadlineExceeded { |
| 137 |
t.Fatal(ctx.Err()) |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
func TestExecContextCancel(t *testing.T) { |
| 142 |
srcTempFilename := TempFilename(t) |
| 143 |
defer os.Remove(srcTempFilename) |
| 144 |
|
| 145 |
db, err := sql.Open("sqlite3", srcTempFilename) |
| 146 |
if err != nil { |
| 147 |
t.Fatal(err) |
| 148 |
} |
| 149 |
|
| 150 |
defer db.Close() |
| 151 |
|
| 152 |
ts := time.Now() |
| 153 |
initDatabase(t, db, 1000) |
| 154 |
spent := time.Since(ts) |
| 155 |
const minTestTime = 100 * time.Millisecond |
| 156 |
if spent < minTestTime { |
| 157 |
t.Skipf("test will be too racy (spent=%s < min=%s) as ExecContext below will be too fast.", |
| 158 |
spent.String(), minTestTime.String(), |
| 159 |
) |
| 160 |
} |
| 161 |
|
| 162 |
// expected to be extremely slow query |
| 163 |
q := ` |
| 164 |
INSERT INTO test_table (key1, key_id, key2, key3, key4, key5, key6, data) |
| 165 |
SELECT t1.key1 || t2.key1, t1.key_id || t2.key_id, t1.key2 || t2.key2, t1.key3 || t2.key3, t1.key4 || t2.key4, t1.key5 || t2.key5, t1.key6 || t2.key6, t1.data || t2.data |
| 166 |
FROM test_table t1 LEFT OUTER JOIN test_table t2` |
| 167 |
// expect query above take ~ same time as setup above |
| 168 |
// This is racy: the context must be valid so sql/db.ExecContext calls the sqlite3 driver. |
| 169 |
// It starts the query, the context expires, then calls sqlite3_interrupt |
| 170 |
ctx, cancel := context.WithTimeout(context.Background(), minTestTime/2) |
| 171 |
defer cancel() |
| 172 |
ts = time.Now() |
| 173 |
r, err := db.ExecContext(ctx, q) |
| 174 |
// racy check |
| 175 |
if r != nil { |
| 176 |
n, err := r.RowsAffected() |
| 177 |
t.Logf("query should not have succeeded: rows=%d; err=%v; duration=%s", |
| 178 |
n, err, time.Since(ts).String()) |
| 179 |
} |
| 180 |
if err != context.DeadlineExceeded { |
| 181 |
t.Fatal(err, ctx.Err()) |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
func TestQueryRowContextCancel(t *testing.T) { |
| 186 |
srcTempFilename := TempFilename(t) |
| 187 |
defer os.Remove(srcTempFilename) |
| 188 |
|
| 189 |
db, err := sql.Open("sqlite3", srcTempFilename) |
| 190 |
if err != nil { |
| 191 |
t.Fatal(err) |
| 192 |
} |
| 193 |
defer db.Close() |
| 194 |
initDatabase(t, db, 100) |
| 195 |
|
| 196 |
const query = `SELECT key_id FROM test_table ORDER BY key2 ASC` |
| 197 |
var keyID string |
| 198 |
unexpectedErrors := make(map[string]int) |
| 199 |
for i := 0; i < 10000; i++ { |
| 200 |
ctx, cancel := context.WithCancel(context.Background()) |
| 201 |
row := db.QueryRowContext(ctx, query) |
| 202 |
|
| 203 |
cancel() |
| 204 |
// it is fine to get "nil" as context cancellation can be handled with delay |
| 205 |
if err := row.Scan(&keyID); err != nil && err != context.Canceled { |
| 206 |
if err.Error() == "sql: Rows are closed" { |
| 207 |
// see https://github.com/golang/go/issues/24431 |
| 208 |
// fixed in 1.11.1 to properly return context error |
| 209 |
continue |
| 210 |
} |
| 211 |
unexpectedErrors[err.Error()]++ |
| 212 |
} |
| 213 |
} |
| 214 |
for errText, count := range unexpectedErrors { |
| 215 |
t.Error(errText, count) |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
func TestQueryRowContextCancelParallel(t *testing.T) { |
| 220 |
srcTempFilename := TempFilename(t) |
| 221 |
defer os.Remove(srcTempFilename) |
| 222 |
|
| 223 |
db, err := sql.Open("sqlite3", srcTempFilename) |
| 224 |
if err != nil { |
| 225 |
t.Fatal(err) |
| 226 |
} |
| 227 |
defer db.Close() |
| 228 |
initDatabase(t, db, 100) |
| 229 |
|
| 230 |
const query = `SELECT key_id FROM test_table ORDER BY key2 ASC` |
| 231 |
var wg sync.WaitGroup |
| 232 |
for i := 0; i < 100; i++ { |
| 233 |
wg.Add(1) |
| 234 |
go func() { |
| 235 |
defer wg.Done() |
| 236 |
var keyID string |
| 237 |
for j := 0; j < 100; j++ { |
| 238 |
ctx, cancel := context.WithCancel(context.Background()) |
| 239 |
row := db.QueryRowContext(ctx, query) |
| 240 |
cancel() |
| 241 |
_ = row.Scan(&keyID) |
| 242 |
} |
| 243 |
}() |
| 244 |
} |
| 245 |
wg.Wait() |
| 246 |
} |
| 247 |
|
| 248 |
func TestBeginTxCancel(t *testing.T) { |
| 249 |
srcTempFilename := TempFilename(t) |
| 250 |
defer os.Remove(srcTempFilename) |
| 251 |
|
| 252 |
db, err := sql.Open("sqlite3", srcTempFilename) |
| 253 |
if err != nil { |
| 254 |
t.Fatal(err) |
| 255 |
} |
| 256 |
|
| 257 |
db.SetMaxOpenConns(10) |
| 258 |
db.SetMaxIdleConns(5) |
| 259 |
|
| 260 |
defer db.Close() |
| 261 |
initDatabase(t, db, 100) |
| 262 |
|
| 263 |
// create several go-routines to expose racy issue |
| 264 |
for i := 0; i < 1000; i++ { |
| 265 |
func() { |
| 266 |
ctx, cancel := context.WithCancel(context.Background()) |
| 267 |
conn, err := db.Conn(ctx) |
| 268 |
if err != nil { |
| 269 |
t.Fatal(err) |
| 270 |
} |
| 271 |
defer func() { |
| 272 |
if err := conn.Close(); err != nil { |
| 273 |
t.Error(err) |
| 274 |
} |
| 275 |
}() |
| 276 |
|
| 277 |
err = conn.Raw(func(driverConn any) error { |
| 278 |
d, ok := driverConn.(driver.ConnBeginTx) |
| 279 |
if !ok { |
| 280 |
t.Fatal("unexpected: wrong type") |
| 281 |
} |
| 282 |
// checks that conn.Raw can be used to get *SQLiteConn |
| 283 |
if _, ok = driverConn.(*SQLiteConn); !ok { |
| 284 |
t.Fatalf("conn.Raw() driverConn type=%T, expected *SQLiteConn", driverConn) |
| 285 |
} |
| 286 |
|
| 287 |
go cancel() // make it cancel concurrently with exec("BEGIN"); |
| 288 |
tx, err := d.BeginTx(ctx, driver.TxOptions{}) |
| 289 |
switch err { |
| 290 |
case nil: |
| 291 |
switch err := tx.Rollback(); err { |
| 292 |
case nil, sql.ErrTxDone: |
| 293 |
default: |
| 294 |
return err |
| 295 |
} |
| 296 |
case context.Canceled: |
| 297 |
default: |
| 298 |
// must not fail with "cannot start a transaction within a transaction" |
| 299 |
return err |
| 300 |
} |
| 301 |
return nil |
| 302 |
}) |
| 303 |
if err != nil { |
| 304 |
t.Fatal(err) |
| 305 |
} |
| 306 |
}() |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
func TestStmtReadonly(t *testing.T) { |
| 311 |
db, err := sql.Open("sqlite3", ":memory:") |
| 312 |
if err != nil { |
| 313 |
t.Fatal(err) |
| 314 |
} |
| 315 |
|
| 316 |
_, err = db.Exec("CREATE TABLE t (count INT)") |
| 317 |
if err != nil { |
| 318 |
t.Fatal(err) |
| 319 |
} |
| 320 |
|
| 321 |
isRO := func(query string) bool { |
| 322 |
c, err := db.Conn(context.Background()) |
| 323 |
if err != nil { |
| 324 |
return false |
| 325 |
} |
| 326 |
|
| 327 |
var ro bool |
| 328 |
c.Raw(func(dc any) error { |
| 329 |
stmt, err := dc.(*SQLiteConn).Prepare(query) |
| 330 |
if err != nil { |
| 331 |
return err |
| 332 |
} |
| 333 |
if stmt == nil { |
| 334 |
return errors.New("stmt is nil") |
| 335 |
} |
| 336 |
ro = stmt.(*SQLiteStmt).Readonly() |
| 337 |
return nil |
| 338 |
}) |
| 339 |
return ro // On errors ro will remain false. |
| 340 |
} |
| 341 |
|
| 342 |
if !isRO(`select * from t`) { |
| 343 |
t.Error("select not seen as read-only") |
| 344 |
} |
| 345 |
if isRO(`insert into t values (1), (2)`) { |
| 346 |
t.Error("insert seen as read-only") |
| 347 |
} |
| 348 |
} |