sqlite.go 22.2 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 6 7
//go:generate go run generator.go
//go:generate gofmt -l -s -w .

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
	"database/sql"
	"database/sql/driver"
	"fmt"
	"io"
16
	"math"
cznic's avatar
cznic committed
17 18 19 20
	"sync"
	"time"
	"unsafe"

cznic's avatar
cznic committed
21
	"modernc.org/crt/v2"
cznic's avatar
cznic committed
22
	"modernc.org/sqlite/internal/bin"
cznic's avatar
cznic committed
23 24 25 26
)

var (
	_ driver.Conn    = (*conn)(nil)
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
27
	_ driver.Driver  = (*Driver)(nil)
cznic's avatar
cznic committed
28 29 30 31 32 33 34 35 36
	_ driver.Execer  = (*conn)(nil)
	_ driver.Queryer = (*conn)(nil)
	_ driver.Result  = (*result)(nil)
	_ driver.Rows    = (*rows)(nil)
	_ driver.Stmt    = (*stmt)(nil)
	_ driver.Tx      = (*tx)(nil)
)

const (
37
	driverName = "sqlite"
cznic's avatar
cznic committed
38
	ptrSize    = int(unsafe.Sizeof(uintptr(0)))
cznic's avatar
cznic committed
39 40 41
)

func init() {
42
	tls := crt.NewTLS()
cznic's avatar
cznic committed
43
	if bin.Xsqlite3_threadsafe(tls) != 0 { //TODO implement mutexes
44 45 46
		panic(fmt.Errorf("sqlite: thread safety configuration error"))
	}

cznic's avatar
cznic committed
47 48 49 50 51
	sql.Register(driverName, newDrv())
}

type result struct {
	*stmt
52
	lastInsertID int64
cznic's avatar
cznic committed
53 54 55 56 57 58 59 60 61
	rowsAffected int
}

func newResult(s *stmt) (_ *result, err error) {
	r := &result{stmt: s}
	if r.rowsAffected, err = r.changes(); err != nil {
		return nil, err
	}

62
	if r.lastInsertID, err = r.lastInsertRowID(); err != nil {
cznic's avatar
cznic committed
63 64 65 66 67 68 69 70
		return nil, err
	}

	return r, nil
}

// sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
func (r *result) lastInsertRowID() (v int64, _ error) {
71
	return bin.Xsqlite3_last_insert_rowid(r.tls, r.pdb()), nil
cznic's avatar
cznic committed
72 73 74 75
}

// int sqlite3_changes(sqlite3*);
func (r *result) changes() (int, error) {
76 77
	v := bin.Xsqlite3_changes(r.tls, r.pdb())
	return int(v), nil
cznic's avatar
cznic committed
78 79 80 81 82 83 84 85 86
}

// 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
	}

87
	return r.lastInsertID, nil
cznic's avatar
cznic committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
}

// 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 {
	*stmt
	columns []string
	rc0     int
cznic's avatar
cznic committed
103
	pstmt   crt.Intptr
104
	doStep  bool
cznic's avatar
cznic committed
105 106
}

cznic's avatar
cznic committed
107
func newRows(s *stmt, pstmt crt.Intptr, rc0 int) (*rows, error) {
cznic's avatar
cznic committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	r := &rows{
		stmt:  s,
		pstmt: pstmt,
		rc0:   rc0,
	}

	n, err := r.columnCount()
	if err != nil {
		return nil, err
	}

	r.columns = make([]string, n)
	for i := range r.columns {
		if r.columns[i], err = r.columnName(i); err != nil {
			return nil, err
		}
	}

	return r, nil
}

// 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
}

// Close closes the rows iterator.
func (r *rows) Close() (err error) {
	return r.finalize(r.pstmt)
}

// 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) {
	rc := r.rc0
147 148
	if r.doStep {
		if rc, err = r.step(r.pstmt); err != nil {
cznic's avatar
cznic committed
149 150 151 152
			return err
		}
	}

153
	r.doStep = true
cznic's avatar
cznic committed
154 155

	switch rc {
cznic's avatar
cznic committed
156
	case bin.DSQLITE_ROW:
cznic's avatar
cznic committed
157 158 159 160 161 162 163 164 165 166 167
		if g, e := len(dest), len(r.columns); g != e {
			return fmt.Errorf("Next(): have %v destination values, expected %v", g, e)
		}

		for i := range dest {
			ct, err := r.columnType(i)
			if err != nil {
				return err
			}

			switch ct {
cznic's avatar
cznic committed
168
			case bin.DSQLITE_INTEGER:
cznic's avatar
cznic committed
169 170 171 172 173 174
				v, err := r.columnInt64(i)
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
175
			case bin.DSQLITE_FLOAT:
cznic's avatar
cznic committed
176 177 178 179 180 181
				v, err := r.columnDouble(i)
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
182
			case bin.DSQLITE_TEXT:
cznic's avatar
cznic committed
183 184 185 186 187 188
				v, err := r.columnText(i)
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
189
			case bin.DSQLITE_BLOB:
cznic's avatar
cznic committed
190 191 192 193 194 195
				v, err := r.columnBlob(i)
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
196
			case bin.DSQLITE_NULL:
cznic's avatar
cznic committed
197 198
				dest[i] = nil
			default:
cznic's avatar
cznic committed
199
				return fmt.Errorf("internal error: rc %d", rc)
cznic's avatar
cznic committed
200 201 202
			}
		}
		return nil
cznic's avatar
cznic committed
203
	case bin.DSQLITE_DONE:
cznic's avatar
cznic committed
204 205 206 207 208 209 210 211
		return io.EOF
	default:
		return r.errstr(int32(rc))
	}
}

// int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
func (r *rows) columnBytes(iCol int) (_ int, err error) {
212 213
	v := bin.Xsqlite3_column_bytes(r.tls, r.pstmt, int32(iCol))
	return int(v), nil
cznic's avatar
cznic committed
214 215 216 217
}

// const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
func (r *rows) columnBlob(iCol int) (v []byte, err error) {
218
	p := bin.Xsqlite3_column_blob(r.tls, r.pstmt, int32(iCol))
cznic's avatar
cznic committed
219 220 221 222 223
	len, err := r.columnBytes(iCol)
	if err != nil {
		return nil, err
	}

cznic's avatar
cznic committed
224 225 226 227 228 229 230
	if p == 0 || len == 0 {
		return nil, nil
	}

	v = make([]byte, len)
	copy(v, (*crt.RawMem)(unsafe.Pointer(uintptr(p)))[:len])
	return v, nil
cznic's avatar
cznic committed
231 232 233 234
}

// const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
func (r *rows) columnText(iCol int) (v string, err error) {
235
	p := bin.Xsqlite3_column_text(r.tls, r.pstmt, int32(iCol))
cznic's avatar
cznic committed
236 237 238 239 240
	len, err := r.columnBytes(iCol)
	if err != nil {
		return "", err
	}

cznic's avatar
cznic committed
241 242 243 244 245 246 247
	if p == 0 || len == 0 {
		return "", nil
	}

	b := make([]byte, len)
	copy(b, (*crt.RawMem)(unsafe.Pointer(uintptr(p)))[:len])
	return string(b), nil
cznic's avatar
cznic committed
248 249 250 251
}

// double sqlite3_column_double(sqlite3_stmt*, int iCol);
func (r *rows) columnDouble(iCol int) (v float64, err error) {
252 253
	v = bin.Xsqlite3_column_double(r.tls, r.pstmt, int32(iCol))
	return v, nil
cznic's avatar
cznic committed
254 255 256 257
}

// sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
func (r *rows) columnInt64(iCol int) (v int64, err error) {
258 259
	v = bin.Xsqlite3_column_int64(r.tls, r.pstmt, int32(iCol))
	return v, nil
cznic's avatar
cznic committed
260 261 262 263
}

// int sqlite3_column_type(sqlite3_stmt*, int iCol);
func (r *rows) columnType(iCol int) (_ int, err error) {
264 265
	v := bin.Xsqlite3_column_type(r.tls, r.pstmt, int32(iCol))
	return int(v), nil
cznic's avatar
cznic committed
266 267 268 269
}

// int sqlite3_column_count(sqlite3_stmt *pStmt);
func (r *rows) columnCount() (_ int, err error) {
270 271
	v := bin.Xsqlite3_column_count(r.tls, r.pstmt)
	return int(v), nil
cznic's avatar
cznic committed
272 273 274 275
}

// const char *sqlite3_column_name(sqlite3_stmt*, int N);
func (r *rows) columnName(n int) (string, error) {
276 277
	p := bin.Xsqlite3_column_name(r.tls, r.pstmt, int32(n))
	return crt.GoString(p), nil
cznic's avatar
cznic committed
278 279 280 281
}

type stmt struct {
	*conn
cznic's avatar
cznic committed
282 283 284 285
	allocs []crt.Intptr
	psql   crt.Intptr // *int8
	ppstmt crt.Intptr // **sqlite3_stmt
	pzTail crt.Intptr // **int8
cznic's avatar
cznic committed
286 287
}

288
func newStmt(c *conn, sql string) (*stmt, error) {
cznic's avatar
cznic committed
289
	s := &stmt{conn: c}
290
	psql, err := s.cString(sql)
cznic's avatar
cznic committed
291 292 293 294
	if err != nil {
		return nil, err
	}

295 296
	s.psql = psql
	ppstmt, err := s.malloc(ptrSize)
cznic's avatar
cznic committed
297
	if err != nil {
cznic's avatar
cznic committed
298
		s.free(psql)
cznic's avatar
cznic committed
299 300 301
		return nil, err
	}

cznic's avatar
cznic committed
302
	s.ppstmt = ppstmt
cznic's avatar
cznic committed
303 304
	pzTail, err := s.malloc(ptrSize)
	if err != nil {
cznic's avatar
cznic committed
305
		s.free(psql)
306
		s.free(ppstmt)
cznic's avatar
cznic committed
307 308 309
		return nil, err
	}

cznic's avatar
cznic committed
310
	s.pzTail = pzTail
cznic's avatar
cznic committed
311 312 313 314 315 316 317
	return s, nil
}

// 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
318 319 320
	if s.psql != 0 {
		err = s.free(s.psql)
		s.psql = 0
cznic's avatar
cznic committed
321
	}
cznic's avatar
cznic committed
322 323
	if s.ppstmt != 0 {
		if err2 := s.free(s.ppstmt); err2 != nil && err == nil {
cznic's avatar
cznic committed
324 325
			err = err2
		}
cznic's avatar
cznic committed
326
		s.ppstmt = 0
cznic's avatar
cznic committed
327
	}
cznic's avatar
cznic committed
328 329
	if s.pzTail != 0 {
		if err2 := s.free(s.pzTail); err2 != nil && err == nil {
cznic's avatar
cznic committed
330 331
			err = err2
		}
cznic's avatar
cznic committed
332
		s.pzTail = 0
cznic's avatar
cznic committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	}
	for _, v := range s.allocs {
		if err2 := s.free(v); err2 != nil && err == nil {
			err = err2
		}
	}
	s.allocs = nil
	return err
}

// 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
}

// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
357 358 359 360 361
func (s *stmt) Exec(args []driver.Value) (driver.Result, error) {
	return s.exec(context.Background(), toNamedValues(args))
}

func (s *stmt) exec(ctx context.Context, args []namedValue) (r driver.Result, err error) {
cznic's avatar
cznic committed
362
	var pstmt crt.Intptr
363 364 365 366 367 368

	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
cznic's avatar
cznic committed
369
			if pstmt != 0 {
370 371 372 373 374 375
				s.interrupt(s.pdb())
			}
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
376
	for psql := s.psql; *(*byte)(unsafe.Pointer(uintptr(psql))) != 0; psql = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.pzTail))) {
cznic's avatar
cznic committed
377 378 379 380
		if err := s.prepareV2(psql); err != nil {
			return nil, err
		}

cznic's avatar
cznic committed
381 382
		pstmt = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.ppstmt)))
		if pstmt == 0 {
cznic's avatar
cznic committed
383 384 385
			continue
		}

386
		n, err := s.bindParameterCount(pstmt)
cznic's avatar
cznic committed
387 388 389 390 391
		if err != nil {
			return nil, err
		}

		if n != 0 {
392
			if err = s.bind(pstmt, n, args); err != nil {
cznic's avatar
cznic committed
393 394 395
				return nil, err
			}
		}
396

397
		rc, err := s.step(pstmt)
cznic's avatar
cznic committed
398
		if err != nil {
399
			s.finalize(pstmt)
cznic's avatar
cznic committed
400 401 402 403
			return nil, err
		}

		switch rc & 0xff {
cznic's avatar
cznic committed
404
		case bin.DSQLITE_DONE, bin.DSQLITE_ROW:
405
			if err := s.finalize(pstmt); err != nil {
cznic's avatar
cznic committed
406 407 408 409
				return nil, err
			}
		default:
			err = s.errstr(int32(rc))
410
			s.finalize(pstmt)
cznic's avatar
cznic committed
411 412 413 414 415 416
			return nil, err
		}
	}
	return newResult(s)
}

417 418 419 420 421
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) {
	return s.query(context.Background(), toNamedValues(args))
}

func (s *stmt) query(ctx context.Context, args []namedValue) (r driver.Rows, err error) {
cznic's avatar
cznic committed
422
	var pstmt, rowStmt crt.Intptr
cznic's avatar
cznic committed
423
	var rc0 int
424 425 426 427 428 429

	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
cznic's avatar
cznic committed
430
			if pstmt != 0 {
431 432 433 434 435 436
				s.interrupt(s.pdb())
			}
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
437
	for psql := s.psql; *(*byte)(unsafe.Pointer(uintptr(psql))) != 0; psql = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.pzTail))) {
cznic's avatar
cznic committed
438 439 440 441
		if err := s.prepareV2(psql); err != nil {
			return nil, err
		}

cznic's avatar
cznic committed
442 443
		pstmt = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.ppstmt)))
		if pstmt == 0 {
cznic's avatar
cznic committed
444 445 446
			continue
		}

447
		n, err := s.bindParameterCount(pstmt)
cznic's avatar
cznic committed
448 449 450 451 452
		if err != nil {
			return nil, err
		}

		if n != 0 {
453
			if err = s.bind(pstmt, n, args); err != nil {
cznic's avatar
cznic committed
454 455 456
				return nil, err
			}
		}
457

458
		rc, err := s.step(pstmt)
cznic's avatar
cznic committed
459
		if err != nil {
460
			s.finalize(pstmt)
cznic's avatar
cznic committed
461 462 463 464
			return nil, err
		}

		switch rc {
cznic's avatar
cznic committed
465 466
		case bin.DSQLITE_ROW:
			if rowStmt != 0 {
467
				if err := s.finalize(pstmt); err != nil {
cznic's avatar
cznic committed
468 469 470 471 472 473
					return nil, err
				}

				return nil, fmt.Errorf("query contains multiple select statements")
			}

474
			rowStmt = pstmt
cznic's avatar
cznic committed
475
			rc0 = rc
cznic's avatar
cznic committed
476 477
		case bin.DSQLITE_DONE:
			if rowStmt == 0 {
cznic's avatar
cznic committed
478 479 480 481
				rc0 = rc
			}
		default:
			err = s.errstr(int32(rc))
482
			s.finalize(pstmt)
cznic's avatar
cznic committed
483 484 485 486 487 488 489
			return nil, err
		}
	}
	return newRows(s, rowStmt, rc0)
}

// int sqlite3_bind_double(sqlite3_stmt*, int, double);
cznic's avatar
cznic committed
490
func (s *stmt) bindDouble(pstmt crt.Intptr, idx1 int, value float64) (err error) {
491
	if rc := bin.Xsqlite3_bind_double(s.tls, pstmt, int32(idx1), value); rc != 0 {
cznic's avatar
cznic committed
492 493 494 495 496 497 498
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int(sqlite3_stmt*, int, int);
cznic's avatar
cznic committed
499 500
func (s *stmt) bindInt(pstmt crt.Intptr, idx1, value int) (err error) {
	if rc := bin.Xsqlite3_bind_int(s.tls, pstmt, int32(idx1), int32(value)); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
501 502 503 504 505 506 507
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
cznic's avatar
cznic committed
508 509
func (s *stmt) bindInt64(pstmt crt.Intptr, idx1 int, value int64) (err error) {
	if rc := bin.Xsqlite3_bind_int64(s.tls, pstmt, int32(idx1), value); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
510 511 512 513 514 515 516
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
cznic's avatar
cznic committed
517
func (s *stmt) bindBlob(pstmt crt.Intptr, idx1 int, value []byte) (err error) {
cznic's avatar
cznic committed
518 519 520 521 522 523
	p, err := s.malloc(len(value))
	if err != nil {
		return err
	}

	s.allocs = append(s.allocs, p)
cznic's avatar
cznic committed
524 525
	copy((*crt.RawMem)(unsafe.Pointer(uintptr(p)))[:len(value)], value)
	if rc := bin.Xsqlite3_bind_blob(s.tls, pstmt, int32(idx1), p, int32(len(value)), 0); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
526 527 528 529 530 531 532
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
cznic's avatar
cznic committed
533
func (s *stmt) bindText(pstmt crt.Intptr, idx1 int, value string) (err error) {
cznic's avatar
cznic committed
534 535 536 537 538
	p, err := s.cString(value)
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
539 540
	s.allocs = append(s.allocs, p)
	if rc := bin.Xsqlite3_bind_text(s.tls, pstmt, int32(idx1), p, int32(len(value)), 0); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
541 542 543 544 545 546
		return s.errstr(rc)
	}

	return nil
}

cznic's avatar
cznic committed
547
func (s *stmt) bind(pstmt crt.Intptr, n int, args []namedValue) error {
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
	for i := 1; i <= n; i++ {
		name, err := s.bindParameterName(pstmt, i)
		if err != nil {
			return err
		}

		var v 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
				// 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 != "" {
				return fmt.Errorf("missing named argument %q", name[1:])
			}
576 577

			return fmt.Errorf("missing argument with %d index", i)
578
		}
cznic's avatar
cznic committed
579

580
		switch x := v.Value.(type) {
cznic's avatar
cznic committed
581
		case int64:
582
			if err := s.bindInt64(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
583 584 585
				return err
			}
		case float64:
586
			if err := s.bindDouble(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
587 588 589 590 591 592 593
				return err
			}
		case bool:
			v := 0
			if x {
				v = 1
			}
594
			if err := s.bindInt(pstmt, i, v); err != nil {
cznic's avatar
cznic committed
595 596 597
				return err
			}
		case []byte:
598
			if err := s.bindBlob(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
599 600 601
				return err
			}
		case string:
602
			if err := s.bindText(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
603 604 605
				return err
			}
		case time.Time:
606
			if err := s.bindText(pstmt, i, x.String()); err != nil {
cznic's avatar
cznic committed
607 608 609 610 611 612 613 614 615 616
				return err
			}
		default:
			return fmt.Errorf("invalid driver.Value type %T", x)
		}
	}
	return nil
}

// int sqlite3_bind_parameter_count(sqlite3_stmt*);
cznic's avatar
cznic committed
617
func (s *stmt) bindParameterCount(pstmt crt.Intptr) (_ int, err error) {
618 619
	r := bin.Xsqlite3_bind_parameter_count(s.tls, pstmt)
	return int(r), nil
cznic's avatar
cznic committed
620 621
}

622
// const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
cznic's avatar
cznic committed
623
func (s *stmt) bindParameterName(pstmt crt.Intptr, i int) (string, error) {
624 625
	p := bin.Xsqlite3_bind_parameter_name(s.tls, pstmt, int32(i))
	return crt.GoString(p), nil
626 627
}

cznic's avatar
cznic committed
628
// int sqlite3_finalize(sqlite3_stmt *pStmt);
cznic's avatar
cznic committed
629 630
func (s *stmt) finalize(pstmt crt.Intptr) error {
	if rc := bin.Xsqlite3_finalize(s.tls, pstmt); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
631 632 633 634 635 636 637
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_step(sqlite3_stmt*);
cznic's avatar
cznic committed
638
func (s *stmt) step(pstmt crt.Intptr) (int, error) {
639 640
	r := bin.Xsqlite3_step(s.tls, pstmt)
	return int(r), nil
cznic's avatar
cznic committed
641 642 643 644 645 646 647 648 649
}

// 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
650 651
func (s *stmt) prepareV2(zSQL crt.Intptr) error {
	if rc := bin.Xsqlite3_prepare_v2(s.tls, s.pdb(), zSQL, -1, s.ppstmt, s.pzTail); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
652 653 654 655 656 657 658 659 660 661 662 663
		return s.errstr(rc)
	}

	return nil
}

type tx struct {
	*conn
}

func newTx(c *conn) (*tx, error) {
	t := &tx{conn: c}
664
	if err := t.exec(context.Background(), "begin"); err != nil {
cznic's avatar
cznic committed
665 666 667 668 669 670 671 672
		return nil, err
	}

	return t, nil
}

// Commit implements driver.Tx.
func (t *tx) Commit() (err error) {
673
	return t.exec(context.Background(), "commit")
cznic's avatar
cznic committed
674 675 676 677
}

// Rollback implements driver.Tx.
func (t *tx) Rollback() (err error) {
678
	return t.exec(context.Background(), "rollback")
cznic's avatar
cznic committed
679 680 681 682 683 684 685 686 687
}

// int sqlite3_exec(
//   sqlite3*,                                  /* An open database */
//   const char *sql,                           /* SQL to be evaluated */
//   int (*callback)(void*,int,char**,char**),  /* Callback function */
//   void *,                                    /* 1st argument to callback */
//   char **errmsg                              /* Error msg written here */
// );
688
func (t *tx) exec(ctx context.Context, sql string) (err error) {
689
	psql, err := t.cString(sql)
cznic's avatar
cznic committed
690 691 692 693
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
694
	defer t.free(psql)
cznic's avatar
cznic committed
695

cznic's avatar
cznic committed
696
	//TODO use t.conn.ExecContext() instead
697 698 699 700 701 702 703 704 705 706
	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
			t.interrupt(t.pdb())
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
707
	if rc := bin.Xsqlite3_exec(t.tls, t.pdb(), psql, 0, 0, 0); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
708 709 710 711 712 713 714
		return t.errstr(rc)
	}

	return nil
}

type conn struct {
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
715
	*Driver
cznic's avatar
cznic committed
716
	ppdb crt.Intptr // **bin.Xsqlite3
717
	tls  *crt.TLS
cznic's avatar
cznic committed
718 719
}

Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
720 721
func newConn(s *Driver, name string) (_ *conn, err error) {
	c := &conn{Driver: s}
cznic's avatar
cznic committed
722 723 724 725 726 727 728 729 730 731 732

	defer func() {
		if err != nil {
			c.close()
		}
	}()

	c.Lock()

	defer c.Unlock()

733
	c.tls = crt.NewTLS()
cznic's avatar
cznic committed
734 735
	if err = c.openV2(
		name,
cznic's avatar
cznic committed
736 737 738
		bin.DSQLITE_OPEN_READWRITE|bin.DSQLITE_OPEN_CREATE|
			bin.DSQLITE_OPEN_FULLMUTEX|
			bin.DSQLITE_OPEN_URI,
cznic's avatar
cznic committed
739 740 741 742 743 744 745 746 747 748 749 750 751
	); err != nil {
		return nil, err
	}

	if err = c.extendedResultCodes(true); err != nil {
		return nil, err
	}

	return c, nil
}

// Prepare returns a prepared statement, bound to this connection.
func (c *conn) Prepare(query string) (s driver.Stmt, err error) {
752 753 754 755
	return c.prepare(context.Background(), query)
}

func (c *conn) prepare(ctx context.Context, query string) (s driver.Stmt, err error) {
cznic's avatar
cznic committed
756 757 758 759 760 761 762 763 764 765 766 767 768
	return newStmt(c, query)
}

// 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.
func (c *conn) Close() (err error) {
	return c.close()
}

769 770 771 772 773 774 775 776 777 778 779 780
// Begin starts a transaction.
func (c *conn) Begin() (driver.Tx, error) {
	return c.begin(context.Background(), txOptions{})
}

// copy of driver.TxOptions
type txOptions struct {
	Isolation int // driver.IsolationLevel
	ReadOnly  bool
}

func (c *conn) begin(ctx context.Context, opts txOptions) (t driver.Tx, err error) {
cznic's avatar
cznic committed
781 782 783 784 785 786 787 788 789
	return newTx(c)
}

// Execer is an optional interface that may be implemented by a Conn.
//
// If a Conn does not implement Execer, the sql package's DB.Exec will first
// prepare a query, execute the statement, and then close the statement.
//
// Exec may return ErrSkip.
790 791 792 793 794
func (c *conn) Exec(query string, args []driver.Value) (driver.Result, error) {
	return c.exec(context.Background(), query, toNamedValues(args))
}

func (c *conn) exec(ctx context.Context, query string, args []namedValue) (r driver.Result, err error) {
795
	s, err := c.prepare(ctx, query)
cznic's avatar
cznic committed
796 797 798 799 800 801 802 803 804 805
	if err != nil {
		return nil, err
	}

	defer func() {
		if err2 := s.Close(); err2 != nil && err == nil {
			err = err2
		}
	}()

806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
	return s.(*stmt).exec(ctx, args)
}

// copy of driver.NameValue
type namedValue struct {
	Name    string
	Ordinal int
	Value   driver.Value
}

// toNamedValues converts []driver.Value to []namedValue
func toNamedValues(vals []driver.Value) []namedValue {
	args := make([]namedValue, 0, len(vals))
	for i, val := range vals {
		args = append(args, namedValue{Value: val, Ordinal: i + 1})
	}
	return args
cznic's avatar
cznic committed
823 824 825 826 827 828 829 830
}

// Queryer is an optional interface that may be implemented by a Conn.
//
// If a Conn does not implement Queryer, the sql package's DB.Query will first
// prepare a query, execute the statement, and then close the statement.
//
// Query may return ErrSkip.
831 832 833 834 835
func (c *conn) Query(query string, args []driver.Value) (driver.Rows, error) {
	return c.query(context.Background(), query, toNamedValues(args))
}

func (c *conn) query(ctx context.Context, query string, args []namedValue) (r driver.Rows, err error) {
836
	s, err := c.prepare(ctx, query)
cznic's avatar
cznic committed
837 838 839 840 841 842 843 844 845 846
	if err != nil {
		return nil, err
	}

	defer func() {
		if err2 := s.Close(); err2 != nil && err == nil {
			err = err2
		}
	}()

847
	return s.(*stmt).query(ctx, args)
cznic's avatar
cznic committed
848 849
}

cznic's avatar
cznic committed
850
func (c *conn) pdb() crt.Intptr { return *(*crt.Intptr)(unsafe.Pointer(uintptr(c.ppdb))) }
cznic's avatar
cznic committed
851 852 853

// int sqlite3_extended_result_codes(sqlite3*, int onoff);
func (c *conn) extendedResultCodes(on bool) (err error) {
cznic's avatar
cznic committed
854
	if rc := bin.Xsqlite3_extended_result_codes(c.tls, c.pdb(), crt.Bool32(on)); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
855 856 857 858 859 860 861
		return c.errstr(rc)
	}

	return nil
}

// void *sqlite3_malloc(int);
cznic's avatar
cznic committed
862
func (c *conn) malloc(n int) (r crt.Intptr, err error) {
863
	if n > math.MaxInt32 {
cznic's avatar
cznic committed
864
		return 0, fmt.Errorf("cannot allocate %d bytes of memory", n)
865 866 867
	}

	r = bin.Xsqlite3_malloc(c.tls, int32(n))
cznic's avatar
cznic committed
868 869
	if r == 0 {
		return 0, fmt.Errorf("malloc(%v) failed", n)
870 871 872
	}

	return r, nil
cznic's avatar
cznic committed
873 874
}

cznic's avatar
cznic committed
875
func (c *conn) cString(s string) (crt.Intptr, error) {
cznic's avatar
cznic committed
876
	n := len(s)
877 878
	p, err := c.malloc(n + 1)
	if err != nil {
cznic's avatar
cznic committed
879
		return 0, err
cznic's avatar
cznic committed
880 881
	}

cznic's avatar
cznic committed
882 883 884
	copy((*crt.RawMem)(unsafe.Pointer(uintptr(p)))[:n], s)
	*(*byte)(unsafe.Pointer(uintptr(p) + uintptr(n))) = 0
	return p, nil
cznic's avatar
cznic committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898
}

// 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 */
// );
func (c *conn) openV2(name string, flags int32) error {
	filename, err := c.cString(name)
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
899
	defer c.free(filename)
cznic's avatar
cznic committed
900

901
	ppdb, err := c.malloc(ptrSize)
cznic's avatar
cznic committed
902 903 904 905
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
906 907
	c.ppdb = ppdb
	if rc := bin.Xsqlite3_open_v2(c.tls, filename, c.ppdb, flags, 0); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
908 909 910 911 912 913 914 915
		return c.errstr(rc)
	}

	return nil
}

// const char *sqlite3_errstr(int);
func (c *conn) errstr(rc int32) (err error) {
916 917 918
	p := bin.Xsqlite3_errstr(c.tls, rc)
	str := crt.GoString(p)
	p = bin.Xsqlite3_errmsg(c.tls, c.pdb())
cznic's avatar
cznic committed
919

920
	switch msg := crt.GoString(p); {
cznic's avatar
cznic committed
921 922 923 924 925 926 927 928 929
	case msg == str:
		return fmt.Errorf("%s (%v)", str, rc)
	default:
		return fmt.Errorf("%s: %s (%v)", str, msg, rc)
	}
}

// int sqlite3_close_v2(sqlite3*);
func (c *conn) closeV2() (err error) {
cznic's avatar
cznic committed
930
	if rc := bin.Xsqlite3_close_v2(c.tls, c.pdb()); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
931 932 933
		return c.errstr(rc)
	}

cznic's avatar
cznic committed
934 935
	err = c.free(c.ppdb)
	c.ppdb = 0
cznic's avatar
cznic committed
936 937 938 939
	return err
}

// void sqlite3_free(void*);
cznic's avatar
cznic committed
940
func (c *conn) free(p crt.Intptr) (err error) {
941 942
	bin.Xsqlite3_free(c.tls, p)
	return nil
cznic's avatar
cznic committed
943 944
}

945
// void sqlite3_interrupt(sqlite3*);
cznic's avatar
cznic committed
946
func (c *conn) interrupt(pdb crt.Intptr) (err error) {
947 948
	bin.Xsqlite3_interrupt(c.tls, pdb)
	return nil
949 950
}

cznic's avatar
cznic committed
951 952 953
func (c *conn) close() (err error) {
	c.Lock()

954
	defer c.Unlock()
cznic's avatar
cznic committed
955

cznic's avatar
cznic committed
956
	if c.ppdb != 0 {
cznic's avatar
cznic committed
957 958 959 960 961
		err = c.closeV2()
	}
	return err
}

962
// Driver implements database/sql/driver.Driver.
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
963
type Driver struct {
cznic's avatar
cznic committed
964 965 966
	sync.Mutex
}

Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
967
func newDrv() *Driver { return &Driver{} }
cznic's avatar
cznic committed
968 969 970 971 972 973 974 975 976

// Open returns a new connection to the database.  The name is a string in a
// driver-specific format.
//
// Open may return a cached connection (one previously closed), but doing so is
// unnecessary; the sql package maintains a pool of idle connections for
// efficient re-use.
//
// The returned connection is only used by one goroutine at a time.
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
977
func (s *Driver) Open(name string) (c driver.Conn, err error) {
cznic's avatar
cznic committed
978 979
	return newConn(s, name)
}