sqlite.go 28.7 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
	_ driver.Queryer = (*conn)(nil)
	_ driver.Result  = (*result)(nil)
32
	_ driver.Rows    = noRows{}
cznic's avatar
cznic committed
33 34 35
	_ driver.Rows    = (*rows)(nil)
	_ driver.Stmt    = (*stmt)(nil)
	_ driver.Tx      = (*tx)(nil)
cznic's avatar
cznic committed
36
	_ error          = (*Error)(nil)
cznic's avatar
cznic committed
37 38 39
)

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

// 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
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 107
		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
108
	}
cznic's avatar
cznic committed
109 110 111
)

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

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

	// int sqlite3_config(int, ...);
cznic's avatar
cznic committed
124
	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
125
		p := sqlite3.Xsqlite3_errstr(tls, rc)
cznic's avatar
cznic committed
126
		str := libc.GoString(p)
cznic's avatar
cznic committed
127 128 129
		panic(fmt.Errorf("sqlite: failed to configure mutex methods: %v", str))
	}

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

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

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

cznic's avatar
cznic committed
146
	if r.lastInsertID, err = c.lastInsertRowID(); err != nil {
cznic's avatar
cznic committed
147 148 149 150 151 152 153 154 155 156 157 158 159
		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
	}

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

// 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
173
	allocs  []uintptr
cznic's avatar
cznic committed
174
	c       *conn
cznic's avatar
cznic committed
175
	columns []string
cznic's avatar
cznic committed
176
	pstmt   uintptr
cznic's avatar
cznic committed
177 178

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

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

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

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

	return r, nil
}

cznic's avatar
cznic committed
206 207 208 209 210 211 212 213 214
// 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
215 216 217 218 219 220 221 222 223 224 225 226
// 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
227 228 229 230
	if r.empty {
		return io.EOF
	}

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

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

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

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

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

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

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

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

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

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

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

// 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
312 313 314
	s.c.free(s.psql)
	s.psql = 0
	return nil
cznic's avatar
cznic committed
315 316
}

cznic's avatar
cznic committed
317
// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
cznic's avatar
cznic committed
318 319
//
//
cznic's avatar
cznic committed
320 321 322 323
// 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
324 325
}

cznic's avatar
cznic committed
326 327 328 329 330 331 332
// 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
333 334
}

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

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

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

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

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

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

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

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

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

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

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

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

			return nil
		}(); err != nil {
cznic's avatar
cznic committed
405 406 407
			return nil, err
		}
	}
cznic's avatar
cznic committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421
	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
422 423
}

cznic's avatar
cznic committed
424 425 426 427 428 429
// 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
430 431 432
	return s.query(context.Background(), toNamedValues(args))
}

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

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

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

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

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

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

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

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

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

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

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

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

				pstmt = 0
				return nil
cznic's avatar
cznic committed
499
			case sqlite3.SQLITE_DONE:
500 501 502 503 504
				if r == nil {
					pstmt = 0
					r = noRows{}
					return nil
				}
cznic's avatar
cznic committed
505 506 507
				// nop
			default:
				return s.c.errstr(int32(rc))
cznic's avatar
cznic committed
508
			}
cznic's avatar
cznic committed
509

cznic's avatar
cznic committed
510
			if *(*byte)(unsafe.Pointer(psql)) == 0 {
cznic's avatar
cznic committed
511 512 513 514 515 516
				if r, err = newRows(s.c, pstmt, allocs, true); err != nil {
					return err
				}

				pstmt = 0
			}
cznic's avatar
cznic committed
517 518
			return nil
		}(); err != nil {
cznic's avatar
cznic committed
519 520 521
			return nil, err
		}
	}
cznic's avatar
cznic committed
522
	return r, err
cznic's avatar
cznic committed
523 524
}

525 526 527 528 529 530
type noRows struct{}

func (noRows) Columns() []string         { return nil }
func (noRows) Close() error              { return nil }
func (noRows) Next([]driver.Value) error { return sql.ErrNoRows }

cznic's avatar
cznic committed
531 532 533 534 535 536 537 538
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
539 540
	}

cznic's avatar
cznic committed
541
	return r, nil
cznic's avatar
cznic committed
542 543
}

cznic's avatar
cznic committed
544 545 546 547
// Commit implements driver.Tx.
func (t *tx) Commit() (err error) {
	return t.exec(context.Background(), "commit")
}
cznic's avatar
cznic committed
548

cznic's avatar
cznic committed
549 550 551
// Rollback implements driver.Tx.
func (t *tx) Rollback() (err error) {
	return t.exec(context.Background(), "rollback")
cznic's avatar
cznic committed
552 553
}

cznic's avatar
cznic committed
554
func (t *tx) exec(ctx context.Context, sql string) (err error) {
cznic's avatar
cznic committed
555
	psql, err := libc.CString(sql)
cznic's avatar
cznic committed
556 557 558 559
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
	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
575
	if rc := sqlite3.Xsqlite3_exec(t.c.tls, t.c.db, psql, 0, 0, 0); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
576
		return t.c.errstr(rc)
cznic's avatar
cznic committed
577 578 579 580 581
	}

	return nil
}

cznic's avatar
cznic committed
582
type conn struct {
cznic's avatar
cznic committed
583
	db  uintptr // *sqlite3.Xsqlite3
cznic's avatar
cznic committed
584
	tls *libc.TLS
cznic's avatar
cznic committed
585 586 587
}

func newConn(name string) (*conn, error) {
cznic's avatar
cznic committed
588
	c := &conn{tls: libc.NewTLS()}
cznic's avatar
cznic committed
589 590
	db, err := c.openV2(
		name,
cznic's avatar
cznic committed
591 592 593
		sqlite3.SQLITE_OPEN_READWRITE|sqlite3.SQLITE_OPEN_CREATE|
			sqlite3.SQLITE_OPEN_FULLMUTEX|
			sqlite3.SQLITE_OPEN_URI,
cznic's avatar
cznic committed
594
	)
cznic's avatar
cznic committed
595
	if err != nil {
cznic's avatar
cznic committed
596
		return nil, err
cznic's avatar
cznic committed
597 598
	}

cznic's avatar
cznic committed
599 600 601
	c.db = db
	if err = c.extendedResultCodes(true); err != nil {
		return nil, err
cznic's avatar
cznic committed
602 603
	}

604 605 606
	// 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
607 608
}

cznic's avatar
cznic committed
609
// const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
610 611
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
612 613 614 615
	len, err := c.columnBytes(pstmt, iCol)
	if err != nil {
		return nil, err
	}
616

cznic's avatar
cznic committed
617 618 619 620 621
	if p == 0 || len == 0 {
		return nil, nil
	}

	v = make([]byte, len)
cznic's avatar
cznic committed
622
	copy(v, (*libc.RawMem)(unsafe.Pointer(p))[:len:len])
cznic's avatar
cznic committed
623 624 625 626
	return v, nil
}

// int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
627 628
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
629 630 631 632
	return int(v), nil
}

// const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
633 634
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
635 636 637 638 639 640 641 642 643 644
	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
645
	copy(b, (*libc.RawMem)(unsafe.Pointer(p))[:len:len])
cznic's avatar
cznic committed
646 647 648 649
	return string(b), nil
}

// double sqlite3_column_double(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
650 651
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
652 653 654 655
	return v, nil
}

// sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
656 657
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
658 659 660 661
	return v, nil
}

// int sqlite3_column_type(sqlite3_stmt*, int iCol);
cznic's avatar
cznic committed
662 663
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
664 665 666 667
	return int(v), nil
}

// const char *sqlite3_column_name(sqlite3_stmt*, int N);
cznic's avatar
cznic committed
668 669
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
670
	return libc.GoString(p), nil
cznic's avatar
cznic committed
671 672 673
}

// int sqlite3_column_count(sqlite3_stmt *pStmt);
cznic's avatar
cznic committed
674 675
func (c *conn) columnCount(pstmt uintptr) (_ int, err error) {
	v := sqlite3.Xsqlite3_column_count(c.tls, pstmt)
cznic's avatar
cznic committed
676 677 678 679 680
	return int(v), nil
}

// sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
func (c *conn) lastInsertRowID() (v int64, _ error) {
cznic's avatar
cznic committed
681
	return sqlite3.Xsqlite3_last_insert_rowid(c.tls, c.db), nil
cznic's avatar
cznic committed
682 683 684 685
}

// int sqlite3_changes(sqlite3*);
func (c *conn) changes() (int, error) {
cznic's avatar
cznic committed
686
	v := sqlite3.Xsqlite3_changes(c.tls, c.db)
cznic's avatar
cznic committed
687 688 689 690
	return int(v), nil
}

// int sqlite3_step(sqlite3_stmt*);
cznic's avatar
cznic committed
691
func (c *conn) step(pstmt uintptr) (int, error) {
cznic's avatar
cznic committed
692
	for {
cznic's avatar
cznic committed
693 694
		switch rc := sqlite3.Xsqlite3_step(c.tls, pstmt); rc {
		case sqliteLockedSharedcache, sqlite3.SQLITE_BUSY:
cznic's avatar
cznic committed
695
			if err := c.retry(pstmt); err != nil {
cznic's avatar
cznic committed
696
				return sqlite3.SQLITE_LOCKED, err
cznic's avatar
cznic committed
697 698 699 700 701 702 703
			}
		default:
			return int(rc), nil
		}
	}
}

cznic's avatar
cznic committed
704 705
func (c *conn) retry(pstmt uintptr) error {
	mu := mutexAlloc(c.tls, sqlite3.SQLITE_MUTEX_FAST)
cznic's avatar
cznic committed
706
	(*mutex)(unsafe.Pointer(mu)).enter(c.tls.ID) // Block
cznic's avatar
cznic committed
707
	rc := sqlite3.Xsqlite3_unlock_notify(
cznic's avatar
cznic committed
708 709
		c.tls,
		c.db,
cznic's avatar
cznic committed
710
		*(*uintptr)(unsafe.Pointer(&struct {
cznic's avatar
cznic committed
711
			f func(*libc.TLS, uintptr, int32)
cznic's avatar
cznic committed
712 713 714
		}{unlockNotify})),
		mu,
	)
cznic's avatar
cznic committed
715
	if rc == sqlite3.SQLITE_LOCKED { // Deadlock, see https://www.sqlite.org/c3ref/unlock_notify.html
cznic's avatar
cznic committed
716
		(*mutex)(unsafe.Pointer(mu)).leave(c.tls.ID) // Clear
cznic's avatar
cznic committed
717 718 719 720
		mutexFree(c.tls, mu)
		return c.errstr(rc)
	}

cznic's avatar
cznic committed
721 722
	(*mutex)(unsafe.Pointer(mu)).enter(c.tls.ID) // Wait
	(*mutex)(unsafe.Pointer(mu)).leave(c.tls.ID) // Clear
cznic's avatar
cznic committed
723 724
	mutexFree(c.tls, mu)
	if pstmt != 0 {
cznic's avatar
cznic committed
725
		sqlite3.Xsqlite3_reset(c.tls, pstmt)
cznic's avatar
cznic committed
726 727 728 729
	}
	return nil
}

cznic's avatar
cznic committed
730
func unlockNotify(t *libc.TLS, ppArg uintptr, nArg int32) {
cznic's avatar
cznic committed
731
	for i := int32(0); i < nArg; i++ {
cznic's avatar
cznic committed
732 733 734
		mu := *(*uintptr)(unsafe.Pointer(ppArg))
		(*mutex)(unsafe.Pointer(mu)).leave(t.ID) // Signal
		ppArg += ptrSize
cznic's avatar
cznic committed
735 736 737
	}
}

cznic's avatar
cznic committed
738
func (c *conn) bind(pstmt uintptr, n int, args []driver.NamedValue) (allocs []uintptr, err error) {
cznic's avatar
cznic committed
739 740 741 742 743 744 745 746 747 748 749 750
	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
751
		var p uintptr
cznic's avatar
cznic committed
752 753 754 755 756 757 758 759 760 761 762
		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
763 764 765 766 767 768 769 770 771 772 773 774 775 776
				// 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
777
				return allocs, fmt.Errorf("missing named argument %q", name[1:])
778
			}
779

cznic's avatar
cznic committed
780
			return allocs, fmt.Errorf("missing argument with %d index", i)
781
		}
cznic's avatar
cznic committed
782

783
		switch x := v.Value.(type) {
cznic's avatar
cznic committed
784
		case int64:
cznic's avatar
cznic committed
785 786
			if err := c.bindInt64(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
787 788
			}
		case float64:
cznic's avatar
cznic committed
789 790
			if err := c.bindDouble(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
791 792 793 794 795 796
			}
		case bool:
			v := 0
			if x {
				v = 1
			}
cznic's avatar
cznic committed
797 798
			if err := c.bindInt(pstmt, i, v); err != nil {
				return allocs, err
cznic's avatar
cznic committed
799 800
			}
		case []byte:
cznic's avatar
cznic committed
801 802
			if p, err = c.bindBlob(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
803 804
			}
		case string:
cznic's avatar
cznic committed
805 806
			if p, err = c.bindText(pstmt, i, x); err != nil {
				return allocs, err
cznic's avatar
cznic committed
807 808
			}
		case time.Time:
cznic's avatar
cznic committed
809 810
			if p, err = c.bindText(pstmt, i, x.String()); err != nil {
				return allocs, err
cznic's avatar
cznic committed
811 812
			}
		default:
cznic's avatar
cznic committed
813 814 815 816
			return allocs, fmt.Errorf("sqlite: invalid driver.Value type %T", x)
		}
		if p != 0 {
			allocs = append(allocs, p)
cznic's avatar
cznic committed
817 818
		}
	}
cznic's avatar
cznic committed
819 820 821 822
	return allocs, nil
}

// int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
cznic's avatar
cznic committed
823
func (c *conn) bindText(pstmt uintptr, idx1 int, value string) (uintptr, error) {
cznic's avatar
cznic committed
824
	p, err := libc.CString(value)
cznic's avatar
cznic committed
825 826 827 828
	if err != nil {
		return 0, err
	}

cznic's avatar
cznic committed
829
	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
830 831 832 833 834 835 836 837
		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
838
func (c *conn) bindBlob(pstmt uintptr, idx1 int, value []byte) (uintptr, error) {
cznic's avatar
cznic committed
839 840 841 842 843
	p, err := c.malloc(len(value))
	if err != nil {
		return 0, err
	}

cznic's avatar
cznic committed
844
	copy((*libc.RawMem)(unsafe.Pointer(p))[:len(value):len(value)], value)
cznic's avatar
cznic committed
845
	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
846 847 848 849 850 851 852 853
		c.free(p)
		return 0, c.errstr(rc)
	}

	return p, nil
}

// int sqlite3_bind_int(sqlite3_stmt*, int, int);
cznic's avatar
cznic committed
854 855
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
856 857 858
		return c.errstr(rc)
	}

cznic's avatar
cznic committed
859 860 861
	return nil
}

cznic's avatar
cznic committed
862
// int sqlite3_bind_double(sqlite3_stmt*, int, double);
cznic's avatar
cznic committed
863 864
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
865 866 867 868 869 870 871
		return c.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
cznic's avatar
cznic committed
872 873
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
874 875 876 877
		return c.errstr(rc)
	}

	return nil
cznic's avatar
cznic committed
878 879
}

880
// const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
cznic's avatar
cznic committed
881 882
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
883
	return libc.GoString(p), nil
884 885
}

cznic's avatar
cznic committed
886
// int sqlite3_bind_parameter_count(sqlite3_stmt*);
cznic's avatar
cznic committed
887 888
func (c *conn) bindParameterCount(pstmt uintptr) (_ int, err error) {
	r := sqlite3.Xsqlite3_bind_parameter_count(c.tls, pstmt)
cznic's avatar
cznic committed
889 890 891
	return int(r), nil
}

cznic's avatar
cznic committed
892
// int sqlite3_finalize(sqlite3_stmt *pStmt);
cznic's avatar
cznic committed
893 894
func (c *conn) finalize(pstmt uintptr) error {
	if rc := sqlite3.Xsqlite3_finalize(c.tls, pstmt); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
895
		return c.errstr(rc)
cznic's avatar
cznic committed
896 897 898 899 900 901 902 903 904 905 906 907
	}

	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
908 909
func (c *conn) prepareV2(zSQL *uintptr) (pstmt uintptr, err error) {
	var ppstmt, pptail uintptr
cznic's avatar
cznic committed
910

cznic's avatar
cznic committed
911 912 913 914
	defer func() {
		c.free(ppstmt)
		c.free(pptail)
	}()
cznic's avatar
cznic committed
915

cznic's avatar
cznic committed
916
	if ppstmt, err = c.malloc(int(ptrSize)); err != nil {
cznic's avatar
cznic committed
917 918
		return 0, err
	}
cznic's avatar
cznic committed
919

cznic's avatar
cznic committed
920
	if pptail, err = c.malloc(int(ptrSize)); err != nil {
cznic's avatar
cznic committed
921
		return 0, err
cznic's avatar
cznic committed
922 923
	}

cznic's avatar
cznic committed
924
	for {
cznic's avatar
cznic committed
925 926 927 928 929
		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
930 931 932 933 934 935 936
			if err := c.retry(0); err != nil {
				return 0, err
			}
		default:
			return 0, c.errstr(rc)
		}
	}
cznic's avatar
cznic committed
937 938
}

cznic's avatar
cznic committed
939
// void sqlite3_interrupt(sqlite3*);
cznic's avatar
cznic committed
940 941
func (c *conn) interrupt(pdb uintptr) (err error) {
	sqlite3.Xsqlite3_interrupt(c.tls, pdb)
cznic's avatar
cznic committed
942
	return nil
cznic's avatar
cznic committed
943 944
}

cznic's avatar
cznic committed
945 946
// int sqlite3_extended_result_codes(sqlite3*, int onoff);
func (c *conn) extendedResultCodes(on bool) error {
cznic's avatar
cznic committed
947
	if rc := sqlite3.Xsqlite3_extended_result_codes(c.tls, c.db, libc.Bool32(on)); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
948 949 950 951
		return c.errstr(rc)
	}

	return nil
cznic's avatar
cznic committed
952 953
}

cznic's avatar
cznic committed
954 955 956 957 958
// 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
959
// );
cznic's avatar
cznic committed
960 961
func (c *conn) openV2(name string, flags int32) (uintptr, error) {
	var p, s uintptr
cznic's avatar
cznic committed
962

cznic's avatar
cznic committed
963 964 965 966 967 968
	defer func() {
		if p != 0 {
			c.free(p)
		}
		if s != 0 {
			c.free(s)
969 970 971
		}
	}()

cznic's avatar
cznic committed
972
	p, err := c.malloc(int(ptrSize))
cznic's avatar
cznic committed
973 974 975 976
	if err != nil {
		return 0, err
	}

cznic's avatar
cznic committed
977
	if s, err = libc.CString(name); err != nil {
cznic's avatar
cznic committed
978
		return 0, err
cznic's avatar
cznic committed
979 980
	}

cznic's avatar
cznic committed
981
	if rc := sqlite3.Xsqlite3_open_v2(c.tls, s, p, flags, 0); rc != sqlite3.SQLITE_OK {
cznic's avatar
cznic committed
982 983
		return 0, c.errstr(rc)
	}
cznic's avatar
cznic committed
984

cznic's avatar
cznic committed
985
	return *(*uintptr)(unsafe.Pointer(p)), nil
cznic's avatar
cznic committed
986 987
}

cznic's avatar
cznic committed
988
func (c *conn) malloc(n int) (uintptr, error) {
cznic's avatar
cznic committed
989
	if p := libc.Xmalloc(c.tls, types.Size_t(n)); p != 0 {
cznic's avatar
cznic committed
990 991
		return p, nil
	}
cznic's avatar
cznic committed
992

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

cznic's avatar
cznic committed
996
func (c *conn) free(p uintptr) {
cznic's avatar
cznic committed
997
	if p != 0 {
cznic's avatar
cznic committed
998
		libc.Xfree(c.tls, p)
cznic's avatar
cznic committed
999
	}
cznic's avatar
cznic committed
1000
}
cznic's avatar
cznic committed
1001

cznic's avatar
cznic committed
1002 1003
// const char *sqlite3_errstr(int);
func (c *conn) errstr(rc int32) error {
cznic's avatar
cznic committed
1004
	p := sqlite3.Xsqlite3_errstr(c.tls, rc)
cznic's avatar
cznic committed
1005
	str := libc.GoString(p)
cznic's avatar
cznic committed
1006
	p = sqlite3.Xsqlite3_errmsg(c.tls, c.db)
cznic's avatar
cznic committed
1007
	switch msg := libc.GoString(p); {
cznic's avatar
cznic committed
1008 1009 1010 1011
	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
1012 1013 1014
	}
}

cznic's avatar
cznic committed
1015 1016 1017 1018 1019
// 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{})
1020 1021
}

cznic's avatar
cznic committed
1022 1023
func (c *conn) begin(ctx context.Context, opts driver.TxOptions) (t driver.Tx, err error) {
	return newTx(c)
cznic's avatar
cznic committed
1024 1025 1026 1027 1028 1029 1030 1031
}

// 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
1032 1033 1034 1035 1036
func (c *conn) Close() error {
	if c.db != 0 {
		if err := c.closeV2(c.db); err != nil {
			return err
		}
cznic's avatar
cznic committed
1037

cznic's avatar
cznic committed
1038 1039 1040
		c.db = 0
	}
	return nil
1041 1042
}

cznic's avatar
cznic committed
1043