sqlite.go 28.4 KB
Newer Older
cznic's avatar
cznic committed
1 2 3 4
// Copyright 2017 The Sqlite Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

cznic's avatar
cznic committed
5
//go:generate go run generator.go
cznic's avatar
cznic committed
6
//go:generate go fmt ./...
cznic's avatar
cznic committed
7

cznic's avatar
cznic committed
8
package sqlite // import "modernc.org/sqlite"
cznic's avatar
cznic committed
9 10

import (
cznic's avatar
cznic committed
11
	"context"
cznic's avatar
cznic committed
12 13 14 15 16 17 18
	"database/sql"
	"database/sql/driver"
	"fmt"
	"io"
	"time"
	"unsafe"

cznic's avatar
cznic committed
19 20
	"modernc.org/libc"
	"modernc.org/libc/sys/types"
cznic's avatar
cznic committed
21
	"modernc.org/sqlite/lib"
cznic's avatar
cznic committed
22 23 24
)

var (
cznic's avatar
cznic committed
25 26 27 28 29
	_ driver.Conn   = (*conn)(nil)
	_ driver.Driver = (*Driver)(nil)
	//lint:ignore SA1019 TODO implement ExecerContext
	_ driver.Execer = (*conn)(nil)
	//lint:ignore SA1019 TODO implement QueryerContext
cznic's avatar
cznic committed
30 31 32 33 34
	_ driver.Queryer = (*conn)(nil)
	_ driver.Result  = (*result)(nil)
	_ driver.Rows    = (*rows)(nil)
	_ driver.Stmt    = (*stmt)(nil)
	_ driver.Tx      = (*tx)(nil)
cznic's avatar
cznic committed
35
	_ error          = (*Error)(nil)
cznic's avatar
cznic committed
36 37 38
)

const (
cznic's avatar
cznic committed
39
	driverName              = "sqlite"
cznic's avatar
cznic committed
40 41
	ptrSize                 = unsafe.Sizeof(uintptr(0))
	sqliteLockedSharedcache = sqlite3.SQLITE_LOCKED | (1 << 8)
cznic's avatar
cznic committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
)

// Error represents sqlite library error code.
type Error struct {
	msg  string
	code int
}

// Error implements error.
func (e *Error) Error() string { return e.msg }

// Code returns the sqlite result code for this error.
func (e *Error) Code() int { return e.code }

var (
	// ErrorCodeString maps Error.Code() to its string representation.
	ErrorCodeString = map[int]string{
cznic's avatar
cznic committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
		sqlite3.SQLITE_ABORT:             "Callback routine requested an abort (SQLITE_ABORT)",
		sqlite3.SQLITE_AUTH:              "Authorization denied (SQLITE_AUTH)",
		sqlite3.SQLITE_BUSY:              "The database file is locked (SQLITE_BUSY)",
		sqlite3.SQLITE_CANTOPEN:          "Unable to open the database file (SQLITE_CANTOPEN)",
		sqlite3.SQLITE_CONSTRAINT:        "Abort due to constraint violation (SQLITE_CONSTRAINT)",
		sqlite3.SQLITE_CORRUPT:           "The database disk image is malformed (SQLITE_CORRUPT)",
		sqlite3.SQLITE_DONE:              "sqlite3_step() has finished executing (SQLITE_DONE)",
		sqlite3.SQLITE_EMPTY:             "Internal use only (SQLITE_EMPTY)",
		sqlite3.SQLITE_ERROR:             "Generic error (SQLITE_ERROR)",
		sqlite3.SQLITE_FORMAT:            "Not used (SQLITE_FORMAT)",
		sqlite3.SQLITE_FULL:              "Insertion failed because database is full (SQLITE_FULL)",
		sqlite3.SQLITE_INTERNAL:          "Internal logic error in SQLite (SQLITE_INTERNAL)",
		sqlite3.SQLITE_INTERRUPT:         "Operation terminated by sqlite3_interrupt()(SQLITE_INTERRUPT)",
		sqlite3.SQLITE_IOERR | (1 << 8):  "(SQLITE_IOERR_READ)",
		sqlite3.SQLITE_IOERR | (10 << 8): "(SQLITE_IOERR_DELETE)",
		sqlite3.SQLITE_IOERR | (11 << 8): "(SQLITE_IOERR_BLOCKED)",
		sqlite3.SQLITE_IOERR | (12 << 8): "(SQLITE_IOERR_NOMEM)",
		sqlite3.SQLITE_IOERR | (13 << 8): "(SQLITE_IOERR_ACCESS)",
		sqlite3.SQLITE_IOERR | (14 << 8): "(SQLITE_IOERR_CHECKRESERVEDLOCK)",
		sqlite3.SQLITE_IOERR | (15 << 8): "(SQLITE_IOERR_LOCK)",
		sqlite3.SQLITE_IOERR | (16 << 8): "(SQLITE_IOERR_CLOSE)",
		sqlite3.SQLITE_IOERR | (17 << 8): "(SQLITE_IOERR_DIR_CLOSE)",
		sqlite3.SQLITE_IOERR | (2 << 8):  "(SQLITE_IOERR_SHORT_READ)",
		sqlite3.SQLITE_IOERR | (3 << 8):  "(SQLITE_IOERR_WRITE)",
		sqlite3.SQLITE_IOERR | (4 << 8):  "(SQLITE_IOERR_FSYNC)",
		sqlite3.SQLITE_IOERR | (5 << 8):  "(SQLITE_IOERR_DIR_FSYNC)",
		sqlite3.SQLITE_IOERR | (6 << 8):  "(SQLITE_IOERR_TRUNCATE)",
		sqlite3.SQLITE_IOERR | (7 << 8):  "(SQLITE_IOERR_FSTAT)",
		sqlite3.SQLITE_IOERR | (8 << 8):  "(SQLITE_IOERR_UNLOCK)",
		sqlite3.SQLITE_IOERR | (9 << 8):  "(SQLITE_IOERR_RDLOCK)",
		sqlite3.SQLITE_IOERR:             "Some kind of disk I/O error occurred (SQLITE_IOERR)",
		sqlite3.SQLITE_LOCKED | (1 << 8): "(SQLITE_LOCKED_SHAREDCACHE)",
		sqlite3.SQLITE_LOCKED:            "A table in the database is locked (SQLITE_LOCKED)",
		sqlite3.SQLITE_MISMATCH:          "Data type mismatch (SQLITE_MISMATCH)",
		sqlite3.SQLITE_MISUSE:            "Library used incorrectly (SQLITE_MISUSE)",
		sqlite3.SQLITE_NOLFS:             "Uses OS features not supported on host (SQLITE_NOLFS)",
		sqlite3.SQLITE_NOMEM:             "A malloc() failed (SQLITE_NOMEM)",
		sqlite3.SQLITE_NOTADB:            "File opened that is not a database file (SQLITE_NOTADB)",
		sqlite3.SQLITE_NOTFOUND:          "Unknown opcode in sqlite3_file_control() (SQLITE_NOTFOUND)",
		sqlite3.SQLITE_NOTICE:            "Notifications from sqlite3_log() (SQLITE_NOTICE)",
		sqlite3.SQLITE_PERM:              "Access permission denied (SQLITE_PERM)",
		sqlite3.SQLITE_PROTOCOL:          "Database lock protocol error (SQLITE_PROTOCOL)",
		sqlite3.SQLITE_RANGE:             "2nd parameter to sqlite3_bind out of range (SQLITE_RANGE)",
		sqlite3.SQLITE_READONLY:          "Attempt to write a readonly database (SQLITE_READONLY)",
		sqlite3.SQLITE_ROW:               "sqlite3_step() has another row ready (SQLITE_ROW)",
		sqlite3.SQLITE_SCHEMA:            "The database schema changed (SQLITE_SCHEMA)",
		sqlite3.SQLITE_TOOBIG:            "String or BLOB exceeds size limit (SQLITE_TOOBIG)",
		sqlite3.SQLITE_WARNING:           "Warnings from sqlite3_log() (SQLITE_WARNING)",
cznic's avatar
cznic committed
107
	}
cznic's avatar
cznic committed
108 109 110
)

func init() {
cznic's avatar
cznic committed
111 112
	//TODO configure page size to 4096
	tls := libc.NewTLS()
cznic's avatar
cznic committed
113
	if sqlite3.Xsqlite3_threadsafe(tls) == 0 {
114 115 116
		panic(fmt.Errorf("sqlite: thread safety configuration error"))
	}

cznic's avatar
cznic committed
117
	varArgs := libc.Xmalloc(tls, types.Size_t(ptrSize))
cznic's avatar
cznic committed
118 119 120 121 122
	if varArgs == 0 {
		panic(fmt.Errorf("cannot allocate memory"))
	}

	// int sqlite3_config(int, ...);
cznic's avatar
cznic committed
123
	if rc := sqlite3.Xsqlite3_config(tls, sqlite3.SQLITE_CONFIG_MUTEX, libc.VaList(varArgs, uintptr(unsafe.Pointer(&mutexMethods)))); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
124
		p := sqlite3.Xsqlite3_errstr(tls, rc)
cznic's avatar
cznic committed
125
		str := libc.GoString(p)
cznic's avatar
cznic committed
126 127 128
		panic(fmt.Errorf("sqlite: failed to configure mutex methods: %v", str))
	}

cznic's avatar
cznic committed
129
	libc.Xfree(tls, varArgs)
cznic's avatar
cznic committed
130
	tls.Close()
cznic's avatar
cznic committed
131
	sql.Register(driverName, newDriver())
cznic's avatar
cznic committed
132 133 134
}

type result struct {
135
	lastInsertID int64
cznic's avatar
cznic committed
136 137 138
	rowsAffected int
}

cznic's avatar
cznic committed
139 140 141
func newResult(c *conn) (_ *result, err error) {
	r := &result{}
	if r.rowsAffected, err = c.changes(); err != nil {
cznic's avatar
cznic committed
142 143 144
		return nil, err
	}

cznic's avatar
cznic committed
145
	if r.lastInsertID, err = c.lastInsertRowID(); err != nil {
cznic's avatar
cznic committed
146 147 148 149 150 151 152 153 154 155 156 157 158
		return nil, err
	}

	return r, nil
}

// LastInsertId returns the database's auto-generated ID after, for example, an
// INSERT into a table with primary key.
func (r *result) LastInsertId() (int64, error) {
	if r == nil {
		return 0, nil
	}

159
	return r.lastInsertID, nil
cznic's avatar
cznic committed
160 161 162 163 164 165 166 167 168 169 170 171
}

// RowsAffected returns the number of rows affected by the query.
func (r *result) RowsAffected() (int64, error) {
	if r == nil {
		return 0, nil
	}

	return int64(r.rowsAffected), nil
}

type rows struct {
cznic's avatar
cznic committed
172
	allocs  []uintptr
cznic's avatar
cznic committed
173
	c       *conn
cznic's avatar
cznic committed
174
	columns []string
cznic's avatar
cznic committed
175
	pstmt   uintptr
cznic's avatar
cznic committed
176 177

	doStep bool
cznic's avatar
cznic committed
178
	empty  bool
cznic's avatar
cznic committed
179 180
}

cznic's avatar
cznic committed
181
func newRows(c *conn, pstmt uintptr, allocs []uintptr, empty bool) (r *rows, err error) {
cznic's avatar
cznic committed
182 183 184 185 186 187
	defer func() {
		if err != nil {
			c.finalize(pstmt)
			r = nil
		}
	}()
cznic's avatar
cznic committed
188

cznic's avatar
cznic committed
189 190
	r = &rows{c: c, pstmt: pstmt, allocs: allocs}
	n, err := c.columnCount(pstmt)
cznic's avatar
cznic committed
191 192 193 194 195 196
	if err != nil {
		return nil, err
	}

	r.columns = make([]string, n)
	for i := range r.columns {
cznic's avatar
cznic committed
197
		if r.columns[i], err = r.c.columnName(pstmt, i); err != nil {
cznic's avatar
cznic committed
198 199 200 201 202 203 204
			return nil, err
		}
	}

	return r, nil
}

cznic's avatar
cznic committed
205 206 207 208 209 210 211 212 213
// Close closes the rows iterator.
func (r *rows) Close() (err error) {
	for _, v := range r.allocs {
		r.c.free(v)
	}
	r.allocs = nil
	return r.c.finalize(r.pstmt)
}

cznic's avatar
cznic committed
214 215 216 217 218 219 220 221 222 223 224 225
// Columns returns the names of the columns. The number of columns of the
// result is inferred from the length of the slice. If a particular column name
// isn't known, an empty string should be returned for that entry.
func (r *rows) Columns() (c []string) {
	return r.columns
}

// Next is called to populate the next row of data into the provided slice. The
// provided slice will be the same size as the Columns() are wide.
//
// Next should return io.EOF when there are no more rows.
func (r *rows) Next(dest []driver.Value) (err error) {
cznic's avatar
cznic committed
226 227 228 229
	if r.empty {
		return io.EOF
	}

cznic's avatar
cznic committed
230
	rc := sqlite3.SQLITE_ROW
231
	if r.doStep {
cznic's avatar
cznic committed
232
		if rc, err = r.c.step(r.pstmt); err != nil {
cznic's avatar
cznic committed
233 234 235 236
			return err
		}
	}

237
	r.doStep = true
cznic's avatar
cznic committed
238
	switch rc {
cznic's avatar
cznic committed
239
	case sqlite3.SQLITE_ROW:
cznic's avatar
cznic committed
240
		if g, e := len(dest), len(r.columns); g != e {
cznic's avatar
cznic committed
241
			return fmt.Errorf("sqlite: Next: have %v destination values, expected %v", g, e)
cznic's avatar
cznic committed
242 243 244
		}

		for i := range dest {
cznic's avatar
cznic committed
245
			ct, err := r.c.columnType(r.pstmt, i)
cznic's avatar
cznic committed
246 247 248 249 250
			if err != nil {
				return err
			}

			switch ct {
cznic's avatar
cznic committed
251
			case sqlite3.SQLITE_INTEGER:
cznic's avatar
cznic committed
252
				v, err := r.c.columnInt64(r.pstmt, i)
cznic's avatar
cznic committed
253 254 255 256 257
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
258
			case sqlite3.SQLITE_FLOAT:
cznic's avatar
cznic committed
259
				v, err := r.c.columnDouble(r.pstmt, i)
cznic's avatar
cznic committed
260 261 262 263 264
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
265
			case sqlite3.SQLITE_TEXT:
cznic's avatar
cznic committed
266
				v, err := r.c.columnText(r.pstmt, i)
cznic's avatar
cznic committed
267 268 269 270 271
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
272
			case sqlite3.SQLITE_BLOB:
cznic's avatar
cznic committed
273
				v, err := r.c.columnBlob(r.pstmt, i)
cznic's avatar
cznic committed
274 275 276 277 278
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
279
			case sqlite3.SQLITE_NULL:
cznic's avatar
cznic committed
280 281
				dest[i] = nil
			default:
cznic's avatar
cznic committed
282
				return fmt.Errorf("internal error: rc %d", rc)
cznic's avatar
cznic committed
283 284 285
			}
		}
		return nil
cznic's avatar
cznic committed
286
	case sqlite3.SQLITE_DONE:
cznic's avatar
cznic committed
287 288
		return io.EOF
	default:
cznic's avatar
cznic committed
289
		return r.c.errstr(int32(rc))
cznic's avatar
cznic committed
290 291 292 293
	}
}

type stmt struct {
cznic's avatar
cznic committed
294
	c    *conn
cznic's avatar
cznic committed
295
	psql uintptr
cznic's avatar
cznic committed
296 297
}

298
func newStmt(c *conn, sql string) (*stmt, error) {
cznic's avatar
cznic committed
299
	p, err := libc.CString(sql)
cznic's avatar
cznic committed
300 301 302 303
	if err != nil {
		return nil, err
	}

cznic's avatar
cznic committed
304
	return &stmt{c: c, psql: p}, nil
cznic's avatar
cznic committed
305 306 307 308 309 310
}

// Close closes the statement.
//
// As of Go 1.1, a Stmt will not be closed if it's in use by any queries.
func (s *stmt) Close() (err error) {
cznic's avatar
cznic committed
311 312 313
	s.c.free(s.psql)
	s.psql = 0
	return nil
cznic's avatar
cznic committed
314 315
}

cznic's avatar
cznic committed
316
// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
cznic's avatar
cznic committed
317 318
//
//
cznic's avatar
cznic committed
319 320 321 322
// Deprecated: Drivers should implement StmtExecContext instead (or
// additionally).
func (s *stmt) Exec(args []driver.Value) (driver.Result, error) { //TODO StmtExecContext
	return s.exec(context.Background(), toNamedValues(args))
cznic's avatar
cznic committed
323 324
}

cznic's avatar
cznic committed
325 326 327 328 329 330 331
// toNamedValues converts []driver.Value to []driver.NamedValue
func toNamedValues(vals []driver.Value) (r []driver.NamedValue) {
	r = make([]driver.NamedValue, len(vals))
	for i, val := range vals {
		r[i] = driver.NamedValue{Value: val, Ordinal: i + 1}
	}
	return r
332 333
}

cznic's avatar
cznic committed
334
func (s *stmt) exec(ctx context.Context, args []driver.NamedValue) (r driver.Result, err error) {
cznic's avatar
cznic committed
335
	var pstmt uintptr
336 337

	donech := make(chan struct{})
cznic's avatar
cznic committed
338

339 340 341
	go func() {
		select {
		case <-ctx.Done():
cznic's avatar
cznic committed
342
			if pstmt != 0 {
cznic's avatar
cznic committed
343
				s.c.interrupt(s.c.db)
344 345 346 347 348
			}
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
349 350 351 352 353
	defer func() {
		pstmt = 0
		close(donech)
	}()

cznic's avatar
cznic committed
354
	for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0; {
cznic's avatar
cznic committed
355
		if pstmt, err = s.c.prepareV2(&psql); err != nil {
cznic's avatar
cznic committed
356 357 358
			return nil, err
		}

cznic's avatar
cznic committed
359
		if pstmt == 0 {
cznic's avatar
cznic committed
360 361 362
			continue
		}

cznic's avatar
cznic committed
363 364 365 366 367 368
		if err := func() (err error) {
			defer func() {
				if e := s.c.finalize(pstmt); e != nil && err == nil {
					err = e
				}
			}()
cznic's avatar
cznic committed
369

cznic's avatar
cznic committed
370 371 372
			n, err := s.c.bindParameterCount(pstmt)
			if err != nil {
				return err
cznic's avatar
cznic committed
373
			}
374

cznic's avatar
cznic committed
375 376 377 378 379
			if n != 0 {
				allocs, err := s.c.bind(pstmt, n, args)
				if err != nil {
					return err
				}
cznic's avatar
cznic committed
380

cznic's avatar
cznic committed
381 382 383 384 385 386 387
				if len(allocs) != 0 {
					defer func() {
						for _, v := range allocs {
							s.c.free(v)
						}
					}()
				}
cznic's avatar
cznic committed
388
			}
cznic's avatar
cznic committed
389 390 391 392 393 394 395

			rc, err := s.c.step(pstmt)
			if err != nil {
				return err
			}

			switch rc & 0xff {
cznic's avatar
cznic committed
396
			case sqlite3.SQLITE_DONE, sqlite3.SQLITE_ROW:
cznic's avatar
cznic committed
397 398 399 400 401 402 403
				// nop
			default:
				return s.c.errstr(int32(rc))
			}

			return nil
		}(); err != nil {
cznic's avatar
cznic committed
404 405 406
			return nil, err
		}
	}
cznic's avatar
cznic committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420
	return newResult(s.c)
}

// NumInput returns the number of placeholder parameters.
//
// If NumInput returns >= 0, the sql package will sanity check argument counts
// from callers and return errors to the caller before the statement's Exec or
// Query methods are called.
//
// NumInput may also return -1, if the driver doesn't know its number of
// placeholders. In that case, the sql package will not sanity check Exec or
// Query argument counts.
func (s *stmt) NumInput() (n int) {
	return -1
cznic's avatar
cznic committed
421 422
}

cznic's avatar
cznic committed
423 424 425 426 427 428
// Query executes a query that may return rows, such as a
// SELECT.
//
// Deprecated: Drivers should implement StmtQueryContext instead (or
// additionally).
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) { //TODO StmtQueryContext
429 430 431
	return s.query(context.Background(), toNamedValues(args))
}

cznic's avatar
cznic committed
432
func (s *stmt) query(ctx context.Context, args []driver.NamedValue) (r driver.Rows, err error) {
cznic's avatar
cznic committed
433
	var pstmt uintptr
434 435

	donech := make(chan struct{})
cznic's avatar
cznic committed
436

437 438 439
	go func() {
		select {
		case <-ctx.Done():
cznic's avatar
cznic committed
440
			if pstmt != 0 {
cznic's avatar
cznic committed
441
				s.c.interrupt(s.c.db)
442 443 444 445 446
			}
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
447 448 449 450 451
	defer func() {
		pstmt = 0
		close(donech)
	}()

cznic's avatar
cznic committed
452 453
	var allocs []uintptr
	for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0; {
cznic's avatar
cznic committed
454
		if pstmt, err = s.c.prepareV2(&psql); err != nil {
cznic's avatar
cznic committed
455 456 457
			return nil, err
		}

cznic's avatar
cznic committed
458
		if pstmt == 0 {
cznic's avatar
cznic committed
459 460 461
			continue
		}

cznic's avatar
cznic committed
462 463 464 465 466 467
		if err = func() (err error) {
			defer func() {
				if e := s.c.finalize(pstmt); e != nil && err == nil {
					err = e
				}
			}()
cznic's avatar
cznic committed
468

cznic's avatar
cznic committed
469 470 471
			n, err := s.c.bindParameterCount(pstmt)
			if err != nil {
				return err
cznic's avatar
cznic committed
472
			}
473

cznic's avatar
cznic committed
474 475 476 477 478
			if n != 0 {
				a, err := s.c.bind(pstmt, n, args)
				if err != nil {
					return err
				}
cznic's avatar
cznic committed
479

cznic's avatar
cznic committed
480 481
				if len(a) != 0 {
					allocs = append(allocs, a...)
cznic's avatar
cznic committed
482
				}
cznic's avatar
cznic committed
483
			}
cznic's avatar
cznic committed
484

cznic's avatar
cznic committed
485 486 487
			rc, err := s.c.step(pstmt)
			if err != nil {
				return err
cznic's avatar
cznic committed
488 489
			}

cznic's avatar
cznic committed
490
			switch rc & 0xff {
cznic's avatar
cznic committed
491
			case sqlite3.SQLITE_ROW:
cznic's avatar
cznic committed
492
				if r, err = newRows(s.c, pstmt, allocs, false); err != nil {
cznic's avatar
cznic committed
493 494 495 496 497
					return err
				}

				pstmt = 0
				return nil
cznic's avatar
cznic committed
498
			case sqlite3.SQLITE_DONE:
cznic's avatar
cznic committed
499 500 501
				// nop
			default:
				return s.c.errstr(int32(rc))
cznic's avatar
cznic committed
502
			}
cznic's avatar
cznic committed
503

cznic's avatar
cznic committed
504
			if *(*byte)(unsafe.Pointer(psql)) == 0 {
cznic's avatar
cznic committed
505 506 507 508 509 510
				if r, err = newRows(s.c, pstmt, allocs, true); err != nil {
					return err
				}

				pstmt = 0
			}
cznic's avatar
cznic committed
511 512
			return nil
		}(); err != nil {
cznic's avatar
cznic committed
513 514 515
			return nil, err
		}
	}
cznic's avatar
cznic committed
516
	return r, err
cznic's avatar
cznic committed
517 518
}

cznic's avatar
cznic committed
519 520 521 522 523 524 525 526
type tx struct {
	c *conn
}

func newTx(c *conn) (*tx, error) {
	r := &tx{c: c}
	if err := r.exec(context.Background(), "begin"); err != nil {
		return nil, err
cznic's avatar
cznic committed
527 528
	}

cznic's avatar
cznic committed
529
	return r, nil
cznic's avatar
cznic committed
530 531
}

cznic's avatar
cznic committed
532 533 534 535
// Commit implements driver.Tx.
func (t *tx) Commit() (err error) {
	return t.exec(context.Background(), "commit")
}
cznic's avatar
cznic committed
536

cznic's avatar
cznic committed
537 538 539
// Rollback implements driver.Tx.
func (t *tx) Rollback() (err error) {
	return t.exec(context.Background(), "rollback")
cznic's avatar
cznic committed
540 541
}

cznic's avatar
cznic committed
542
func (t *tx) exec(ctx context.Context, sql string) (err error) {
cznic's avatar
cznic committed
543
	psql, err := libc.CString(sql)
cznic's avatar
cznic committed
544 545 546 547
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
	defer t.c.free(psql)

	//TODO use t.conn.ExecContext() instead
	donech := make(chan struct{})

	defer close(donech)

	go func() {
		select {
		case <-ctx.Done():
			t.c.interrupt(t.c.db)
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
563
	if rc := sqlite3.Xsqlite3_exec(t.c.tls, t.c.db, psql, 0, 0, 0); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
564
		return t.c.errstr(rc)
cznic's avatar
cznic committed
565 566 567 568 569
	}

	return nil
}

cznic's avatar
cznic committed
570
type conn struct {
cznic's avatar
cznic committed
571
	db  uintptr // *sqlite3.Xsqlite3
cznic's avatar
cznic committed
572
	tls *libc.TLS
cznic's avatar
cznic committed
573 574 575
}

func newConn(name string) (*conn, error) {
cznic's avatar
cznic committed
576
	c := &conn{tls: libc.NewTLS()}
cznic's avatar
cznic committed
577 578
	db, err := c.openV2(
		name,
cznic's avatar
cznic committed
579 580 581
		sqlite3.SQLITE_OPEN_READWRITE|sqlite3.SQLITE_OPEN_CREATE|
			sqlite3.SQLITE_OPEN_FULLMUTEX|
			sqlite3.SQLITE_OPEN_URI,
cznic's avatar
cznic committed
582
	)
cznic's avatar
cznic committed
583
	if err != nil {
cznic's avatar
cznic committed
584
		return nil, err
cznic's avatar
cznic committed
585 586
	}

cznic's avatar
cznic committed
587 588 589
	c.db = db
	if err = c.extendedResultCodes(true); err != nil {
		return nil, err
cznic's avatar
cznic committed
590 591
	}

592 593 594
	// Default is set at compile time to 1024 because testfixture hard codes that value, fix it at runtime.
	_, err = c.Exec("PRAGMA page_size = 4096;", nil)
	return c, err
cznic's avatar
cznic committed
595 596
}

cznic's avatar
cznic committed
597
// const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
598 599
func (c *conn) columnBlob(pstmt uintptr, iCol int) (v []byte, err error) {
	p := sqlite3.Xsqlite3_column_blob(c.tls, pstmt, int32(iCol))
cznic's avatar
cznic committed
600 601 602 603
	len, err := c.columnBytes(pstmt, iCol)
	if err != nil {
		return nil, err
	}
604

cznic's avatar
cznic committed
605 606 607 608 609
	if p == 0 || len == 0 {
		return nil, nil
	}

	v = make([]byte, len)
cznic's avatar
cznic committed
610
	copy(v, (*libc.RawMem)(unsafe.Pointer(p))[:len:len])
cznic's avatar
cznic committed
611 612 613 614
	return v, nil
}

// int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
615 616
func (c *conn) columnBytes(pstmt uintptr, iCol int) (_ int, err error) {
	v := sqlite3.Xsqlite3_column_bytes(c.tls, pstmt, int32(iCol))
cznic's avatar
cznic committed
617 618 619 620
	return int(v), nil
}

// const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
621 622
func (c *conn) columnText(pstmt uintptr, iCol int) (v string, err error) {
	p := sqlite3.Xsqlite3_column_text(c.tls, pstmt, int32(iCol))
cznic's avatar
cznic committed
623 624 625 626 627 628 629 630 631 632
	len, err := c.columnBytes(pstmt, iCol)
	if err != nil {
		return "", err
	}

	if p == 0 || len == 0 {
		return "", nil
	}

	b := make([]byte, len)
cznic's avatar
cznic committed
633
	copy(b, (*libc.RawMem)(unsafe.Pointer(p))[:len:len])
cznic's avatar
cznic committed
634 635 636 637
	return string(b), nil
}

// double sqlite3_column_double(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
638 639
func (c *conn) columnDouble(pstmt uintptr, iCol int) (v float64, err error) {
	v = sqlite3.Xsqlite3_column_double(c.tls, pstmt, int32(iCol))
cznic's avatar
cznic committed
640 641 642 643
	return v, nil
}

// sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
644 645
func (c *conn) columnInt64(pstmt uintptr, iCol int) (v int64, err error) {
	v = sqlite3.Xsqlite3_column_int64(c.tls, pstmt, int32(iCol))
cznic's avatar
cznic committed
646 647 648 649
	return v, nil
}

// int sqlite3_column_type(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
650 651
func (c *conn) columnType(pstmt uintptr, iCol int) (_ int, err error) {
	v := sqlite3.Xsqlite3_column_type(c.tls, pstmt, int32(iCol))
cznic's avatar
cznic committed
652 653 654 655
	return int(v), nil
}

// const char *sqlite3_column_name(sqlite3_stmt*, int N);
cznic's avatar
cznic committed
656 657
func (c *conn) columnName(pstmt uintptr, n int) (string, error) {
	p := sqlite3.Xsqlite3_column_name(c.tls, pstmt, int32(n))
cznic's avatar
cznic committed
658
	return libc.GoString(p), nil
cznic's avatar
cznic committed
659 660 661
}

// int sqlite3_column_count(sqlite3_stmt *pStmt);
cznic's avatar
cznic committed
662 663
func (c *conn) columnCount(pstmt uintptr) (_ int, err error) {
	v := sqlite3.Xsqlite3_column_count(c.tls, pstmt)
cznic's avatar
cznic committed
664 665 666 667 668
	return int(v), nil
}

// sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
func (c *conn) lastInsertRowID() (v int64, _ error) {
cznic's avatar
cznic committed
669
	return sqlite3.Xsqlite3_last_insert_rowid(c.tls, c.db), nil
cznic's avatar
cznic committed
670 671 672 673
}

// int sqlite3_changes(sqlite3*);
func (c *conn) changes() (int, error) {
cznic's avatar
cznic committed
674
	v := sqlite3.Xsqlite3_changes(c.tls, c.db)
cznic's avatar
cznic committed
675 676 677 678
	return int(v), nil
}

// int sqlite3_step(sqlite3_stmt*);
cznic's avatar
cznic committed
679
func (c *conn) step(pstmt uintptr) (int, error) {
cznic's avatar
cznic committed
680
	for {
cznic's avatar
cznic committed
681 682
		switch rc := sqlite3.Xsqlite3_step(c.tls, pstmt); rc {
		case sqliteLockedSharedcache, sqlite3.SQLITE_BUSY:
cznic's avatar
cznic committed
683
			if err := c.retry(pstmt); err != nil {
cznic's avatar
cznic committed
684
				return sqlite3.SQLITE_LOCKED, err
cznic's avatar
cznic committed
685 686 687 688 689 690 691
			}
		default:
			return int(rc), nil
		}
	}
}

cznic's avatar
cznic committed
692 693
func (c *conn) retry(pstmt uintptr) error {
	mu := mutexAlloc(c.tls, sqlite3.SQLITE_MUTEX_FAST)
cznic's avatar
cznic committed
694
	(*mutex)(unsafe.Pointer(mu)).enter(c.tls.ID) // Block
cznic's avatar
cznic committed
695
	rc := sqlite3.Xsqlite3_unlock_notify(
cznic's avatar
cznic committed
696 697
		c.tls,
		c.db,
cznic's avatar
cznic committed
698
		*(*uintptr)(unsafe.Pointer(&struct {
cznic's avatar
cznic committed
699
			f func(*libc.TLS, uintptr, int32)
cznic's avatar
cznic committed
700 701 702
		}{unlockNotify})),
		mu,
	)
cznic's avatar
cznic committed
703
	if rc == sqlite3.SQLITE_LOCKED { // Deadlock, see https://www.sqlite.org/c3ref/unlock_notify.html
cznic's avatar
cznic committed
704
		(*mutex)(unsafe.Pointer(mu)).leave(c.tls.ID) // Clear
cznic's avatar
cznic committed
705 706 707 708
		mutexFree(c.tls, mu)
		return c.errstr(rc)
	}

cznic's avatar
cznic committed
709 710
	(*mutex)(unsafe.Pointer(mu)).enter(c.tls.ID) // Wait
	(*mutex)(unsafe.Pointer(mu)).leave(c.tls.ID) // Clear
cznic's avatar
cznic committed
711 712
	mutexFree(c.tls, mu)
	if pstmt != 0 {
cznic's avatar
cznic committed
713
		sqlite3.Xsqlite3_reset(c.tls, pstmt)
cznic's avatar
cznic committed
714 715 716 717
	}
	return nil
}

cznic's avatar
cznic committed
718
func unlockNotify(t *libc.TLS, ppArg uintptr, nArg int32) {
cznic's avatar
cznic committed
719
	for i := int32(0); i < nArg; i++ {
cznic's avatar
cznic committed
720 721 722
		mu := *(*uintptr)(unsafe.Pointer(ppArg))
		(*mutex)(unsafe.Pointer(mu)).leave(t.ID) // Signal
		ppArg += ptrSize
cznic's avatar
cznic committed
723 724 725
	}
}

cznic's avatar
cznic committed
726
func (c *conn) bind(pstmt uintptr, n int, args []driver.NamedValue) (allocs []uintptr, err error) {
cznic's avatar
cznic committed
727 728 729 730 731 732 733 734 735 736 737 738
	defer func() {
		if err == nil {
			return
		}

		for _, v := range allocs {
			c.free(v)
		}
		allocs = nil
	}()

	for i := 1; i <= n; i++ {
cznic's avatar
cznic committed
739
		var p uintptr
cznic's avatar
cznic committed
740 741 742 743 744 745 746 747 748 749 750
		name, err := c.bindParameterName(pstmt, i)
		if err != nil {
			return allocs, err
		}

		var v driver.NamedValue
		for _, v = range args {
			if name != "" {
				// sqlite supports '$', '@' and ':' prefixes for string
				// identifiers and '?' for numeric, so we cannot
				// combine different prefixes with the same name
751 752 753 754 755 756 757 758 759 760 761 762 763 764
				// because `database/sql` requires variable names
				// to start with a letter
				if name[1:] == v.Name[:] {
					break
				}
			} else {
				if v.Ordinal == i {
					break
				}
			}
		}

		if v.Ordinal == 0 {
			if name != "" {
cznic's avatar
cznic committed
765
				return allocs, fmt.Errorf("missing named argument %q", name[1:])
766
			}
767

cznic's avatar
cznic committed
768
			return allocs, fmt.Errorf("missing argument with %d index", i)
769
		}
cznic's avatar
cznic committed
770

771
		switch x := v.Value.(type) {
cznic's avatar
cznic committed
772
		case int64:
cznic's avatar
cznic committed
773 774
			if err := c.bindInt64(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
775 776
			}
		case float64:
cznic's avatar
cznic committed
777 778
			if err := c.bindDouble(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
779 780 781 782 783 784
			}
		case bool:
			v := 0
			if x {
				v = 1
			}
cznic's avatar
cznic committed
785 786
			if err := c.bindInt(pstmt, i, v); err != nil {
				return allocs, err
cznic's avatar
cznic committed
787 788
			}
		case []byte:
cznic's avatar
cznic committed
789 790
			if p, err = c.bindBlob(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
791 792
			}
		case string:
cznic's avatar
cznic committed
793 794
			if p, err = c.bindText(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
795 796
			}
		case time.Time:
cznic's avatar
cznic committed
797 798
			if p, err = c.bindText(pstmt, i, x.String()); err != nil {
				return allocs, err
cznic's avatar
cznic committed
799 800
			}
		default:
cznic's avatar
cznic committed
801 802 803 804
			return allocs, fmt.Errorf("sqlite: invalid driver.Value type %T", x)
		}
		if p != 0 {
			allocs = append(allocs, p)
cznic's avatar
cznic committed
805 806
		}
	}
cznic's avatar
cznic committed
807 808 809 810
	return allocs, nil
}

// int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
cznic's avatar
cznic committed
811
func (c *conn) bindText(pstmt uintptr, idx1 int, value string) (uintptr, error) {
cznic's avatar
cznic committed
812
	p, err := libc.CString(value)
cznic's avatar
cznic committed
813 814 815 816
	if err != nil {
		return 0, err
	}

cznic's avatar
cznic committed
817
	if rc := sqlite3.Xsqlite3_bind_text(c.tls, pstmt, int32(idx1), p, int32(len(value)), 0); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
818 819 820 821 822 823 824 825
		c.free(p)
		return 0, c.errstr(rc)
	}

	return p, nil
}

// int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
cznic's avatar
cznic committed
826
func (c *conn) bindBlob(pstmt uintptr, idx1 int, value []byte) (uintptr, error) {
cznic's avatar
cznic committed
827 828 829 830 831
	p, err := c.malloc(len(value))
	if err != nil {
		return 0, err
	}

cznic's avatar
cznic committed
832
	copy((*libc.RawMem)(unsafe.Pointer(p))[:len(value):len(value)], value)
cznic's avatar
cznic committed
833
	if rc := sqlite3.Xsqlite3_bind_blob(c.tls, pstmt, int32(idx1), p, int32(len(value)), 0); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
834 835 836 837 838 839 840 841
		c.free(p)
		return 0, c.errstr(rc)
	}

	return p, nil
}

// int sqlite3_bind_int(sqlite3_stmt*, int, int);
cznic's avatar
cznic committed
842 843
func (c *conn) bindInt(pstmt uintptr, idx1, value int) (err error) {
	if rc := sqlite3.Xsqlite3_bind_int(c.tls, pstmt, int32(idx1), int32(value)); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
844 845 846
		return c.errstr(rc)
	}

cznic's avatar
cznic committed
847 848 849
	return nil
}

cznic's avatar
cznic committed
850
// int sqlite3_bind_double(sqlite3_stmt*, int, double);
cznic's avatar
cznic committed
851 852
func (c *conn) bindDouble(pstmt uintptr, idx1 int, value float64) (err error) {
	if rc := sqlite3.Xsqlite3_bind_double(c.tls, pstmt, int32(idx1), value); rc != 0 {
cznic's avatar
cznic committed
853 854 855 856 857 858 859
		return c.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
cznic's avatar
cznic committed
860 861
func (c *conn) bindInt64(pstmt uintptr, idx1 int, value int64) (err error) {
	if rc := sqlite3.Xsqlite3_bind_int64(c.tls, pstmt, int32(idx1), value); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
862 863 864 865
		return c.errstr(rc)
	}

	return nil
cznic's avatar
cznic committed
866 867
}

868
// const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
cznic's avatar
cznic committed
869 870
func (c *conn) bindParameterName(pstmt uintptr, i int) (string, error) {
	p := sqlite3.Xsqlite3_bind_parameter_name(c.tls, pstmt, int32(i))
cznic's avatar
cznic committed
871
	return libc.GoString(p), nil
872 873
}

cznic's avatar
cznic committed
874
// int sqlite3_bind_parameter_count(sqlite3_stmt*);
cznic's avatar
cznic committed
875 876
func (c *conn) bindParameterCount(pstmt uintptr) (_ int, err error) {
	r := sqlite3.Xsqlite3_bind_parameter_count(c.tls, pstmt)
cznic's avatar
cznic committed
877 878 879
	return int(r), nil
}

cznic's avatar
cznic committed
880
// int sqlite3_finalize(sqlite3_stmt *pStmt);
cznic's avatar
cznic committed
881 882
func (c *conn) finalize(pstmt uintptr) error {
	if rc := sqlite3.Xsqlite3_finalize(c.tls, pstmt); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
883
		return c.errstr(rc)
cznic's avatar
cznic committed
884 885 886 887 888 889 890 891 892 893 894 895
	}

	return nil
}

// int sqlite3_prepare_v2(
//   sqlite3 *db,            /* Database handle */
//   const char *zSql,       /* SQL statement, UTF-8 encoded */
//   int nByte,              /* Maximum length of zSql in bytes. */
//   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
//   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
// );
cznic's avatar
cznic committed
896 897
func (c *conn) prepareV2(zSQL *uintptr) (pstmt uintptr, err error) {
	var ppstmt, pptail uintptr
cznic's avatar
cznic committed
898

cznic's avatar
cznic committed
899 900 901 902
	defer func() {
		c.free(ppstmt)
		c.free(pptail)
	}()
cznic's avatar
cznic committed
903

cznic's avatar
cznic committed
904
	if ppstmt, err = c.malloc(int(ptrSize)); err != nil {
cznic's avatar
cznic committed
905 906
		return 0, err
	}
cznic's avatar
cznic committed
907

cznic's avatar
cznic committed
908
	if pptail, err = c.malloc(int(ptrSize)); err != nil {
cznic's avatar
cznic committed
909
		return 0, err
cznic's avatar
cznic committed
910 911
	}

cznic's avatar
cznic committed
912
	for {
cznic's avatar
cznic committed
913 914 915 916 917
		switch rc := sqlite3.Xsqlite3_prepare_v2(c.tls, c.db, *zSQL, -1, ppstmt, pptail); rc {
		case sqlite3.SQLITE_OK:
			*zSQL = *(*uintptr)(unsafe.Pointer(pptail))
			return *(*uintptr)(unsafe.Pointer(ppstmt)), nil
		case sqliteLockedSharedcache, sqlite3.SQLITE_BUSY:
cznic's avatar
cznic committed
918 919 920 921 922 923 924
			if err := c.retry(0); err != nil {
				return 0, err
			}
		default:
			return 0, c.errstr(rc)
		}
	}
cznic's avatar
cznic committed
925 926
}

cznic's avatar
cznic committed
927
// void sqlite3_interrupt(sqlite3*);
cznic's avatar
cznic committed
928 929
func (c *conn) interrupt(pdb uintptr) (err error) {
	sqlite3.Xsqlite3_interrupt(c.tls, pdb)
cznic's avatar
cznic committed
930
	return nil
cznic's avatar
cznic committed
931 932
}

cznic's avatar
cznic committed
933 934
// int sqlite3_extended_result_codes(sqlite3*, int onoff);
func (c *conn) extendedResultCodes(on bool) error {
cznic's avatar
cznic committed
935
	if rc := sqlite3.Xsqlite3_extended_result_codes(c.tls, c.db, libc.Bool32(on)); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
936 937 938 939
		return c.errstr(rc)
	}

	return nil
cznic's avatar
cznic committed
940 941
}

cznic's avatar
cznic committed
942 943 944 945 946
// int sqlite3_open_v2(
//   const char *filename,   /* Database filename (UTF-8) */
//   sqlite3 **ppDb,         /* OUT: SQLite db handle */
//   int flags,              /* Flags */
//   const char *zVfs        /* Name of VFS module to use */
cznic's avatar
cznic committed
947
// );
cznic's avatar
cznic committed
948 949
func (c *conn) openV2(name string, flags int32) (uintptr, error) {
	var p, s uintptr
cznic's avatar
cznic committed
950

cznic's avatar
cznic committed
951 952 953 954 955 956
	defer func() {
		if p != 0 {
			c.free(p)
		}
		if s != 0 {
			c.free(s)
957 958 959
		}
	}()

cznic's avatar
cznic committed
960
	p, err := c.malloc(int(ptrSize))
cznic's avatar
cznic committed
961 962 963 964
	if err != nil {
		return 0, err
	}

cznic's avatar
cznic committed
965
	if s, err = libc.CString(name); err != nil {
cznic's avatar
cznic committed
966
		return 0, err
cznic's avatar
cznic committed
967 968
	}

cznic's avatar
cznic committed
969
	if rc := sqlite3.Xsqlite3_open_v2(c.tls, s, p, flags, 0); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
970 971
		return 0, c.errstr(rc)
	}
cznic's avatar
cznic committed
972

cznic's avatar
cznic committed
973
	return *(*uintptr)(unsafe.Pointer(p)), nil
cznic's avatar
cznic committed
974 975
}

cznic's avatar
cznic committed
976
func (c *conn) malloc(n int) (uintptr, error) {
cznic's avatar
cznic committed
977
	if p := libc.Xmalloc(c.tls, types.Size_t(n)); p != 0 {
cznic's avatar
cznic committed
978 979
		return p, nil
	}
cznic's avatar
cznic committed
980

cznic's avatar
cznic committed
981 982
	return 0, fmt.Errorf("sqlite: cannot allocate %d bytes of memory", n)
}
cznic's avatar
cznic committed
983

cznic's avatar
cznic committed
984
func (c *conn) free(p uintptr) {
cznic's avatar
cznic committed
985
	if p != 0 {
cznic's avatar
cznic committed
986
		libc.Xfree(c.tls, p)
cznic's avatar
cznic committed
987
	}
cznic's avatar
cznic committed
988
}
cznic's avatar
cznic committed
989

cznic's avatar
cznic committed
990 991
// const char *sqlite3_errstr(int);
func (c *conn) errstr(rc int32) error {
cznic's avatar
cznic committed
992
	p := sqlite3.Xsqlite3_errstr(c.tls, rc)
cznic's avatar
cznic committed
993
	str := libc.GoString(p)
cznic's avatar
cznic committed
994
	p = sqlite3.Xsqlite3_errmsg(c.tls, c.db)
cznic's avatar
cznic committed
995
	switch msg := libc.GoString(p); {
cznic's avatar
cznic committed
996 997 998 999
	case msg == str:
		return &Error{msg: fmt.Sprintf("%s (%v)", str, rc), code: int(rc)}
	default:
		return &Error{msg: fmt.Sprintf("%s: %s (%v)", str, msg, rc), code: int(rc)}
cznic's avatar
cznic committed
1000 1001 1002
	}
}

cznic's avatar
cznic committed
1003 1004 1005 1006 1007
// Begin starts a transaction.
//
// Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
func (c *conn) Begin() (driver.Tx, error) {
	return c.begin(context.Background(), driver.TxOptions{})
1008 1009
}

cznic's avatar
cznic committed
1010 1011
func (c *conn) begin(ctx context.Context, opts driver.TxOptions) (t driver.Tx, err error) {
	return newTx(c)
cznic's avatar
cznic committed
1012 1013 1014 1015 1016 1017 1018 1019
}

// Close invalidates and potentially stops any current prepared statements and
// transactions, marking this connection as no longer in use.
//
// Because the sql package maintains a free pool of connections and only calls
// Close when there's a surplus of idle connections, it shouldn't be necessary
// for drivers to do their own connection caching.
cznic's avatar
cznic committed
1020 1021 1022 1023 1024
func (c *conn) Close() error {
	if c.db != 0 {
		if err := c.closeV2(c.db); err != nil {
			return err
		}
cznic's avatar
cznic committed
1025

cznic's avatar
cznic committed
1026 1027 1028
		c.db = 0
	}
	return nil
1029 1030
}

cznic's avatar
cznic committed
1031
// int sqlite3_close_v2(sqlite3*);
cznic's avatar
cznic committed
1032 1033
func (c *conn) closeV2(db uintptr) error {
	if rc := sqlite3.Xsqlite3_close_v2(c.tls, db); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
1034 1035
		return c.errstr(rc)
	}
1036

cznic's avatar
cznic committed
1037
	return nil
cznic's avatar
cznic committed
1038 1039 1040 10