sqlite.go 22.6 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 {
44 45 46
		panic(fmt.Errorf("sqlite: thread safety configuration error"))
	}

cznic's avatar
cznic committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60
	varArgs := crt.Xmalloc(tls, crt.Intptr(ptrSize))
	if varArgs == 0 {
		panic(fmt.Errorf("cannot allocate memory"))
	}

	*(*uintptr)(unsafe.Pointer(uintptr(varArgs))) = uintptr(unsafe.Pointer(&mutexMethods))
	// int sqlite3_config(int, ...);
	if rc := bin.Xsqlite3_config(tls, bin.DSQLITE_CONFIG_MUTEX, uintptr(varArgs)); rc != bin.DSQLITE_OK {
		p := bin.Xsqlite3_errstr(tls, rc)
		str := crt.GoString(p)
		panic(fmt.Errorf("sqlite: failed to configure mutex methods: %v", str))
	}

	crt.Xfree(tls, varArgs)
cznic's avatar
cznic committed
61 62 63 64 65
	sql.Register(driverName, newDrv())
}

type result struct {
	*stmt
66
	lastInsertID int64
cznic's avatar
cznic committed
67 68 69 70 71 72 73 74 75
	rowsAffected int
}

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

76
	if r.lastInsertID, err = r.lastInsertRowID(); err != nil {
cznic's avatar
cznic committed
77 78 79 80 81 82 83 84
		return nil, err
	}

	return r, nil
}

// sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
func (r *result) lastInsertRowID() (v int64, _ error) {
85
	return bin.Xsqlite3_last_insert_rowid(r.tls, r.pdb()), nil
cznic's avatar
cznic committed
86 87 88 89
}

// int sqlite3_changes(sqlite3*);
func (r *result) changes() (int, error) {
90 91
	v := bin.Xsqlite3_changes(r.tls, r.pdb())
	return int(v), nil
cznic's avatar
cznic committed
92 93 94 95 96 97 98 99 100
}

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

101
	return r.lastInsertID, nil
cznic's avatar
cznic committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
}

// 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
117
	pstmt   crt.Intptr
118
	doStep  bool
cznic's avatar
cznic committed
119 120
}

cznic's avatar
cznic committed
121
func newRows(s *stmt, pstmt crt.Intptr, rc0 int) (*rows, error) {
cznic's avatar
cznic committed
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 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	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
161 162
	if r.doStep {
		if rc, err = r.step(r.pstmt); err != nil {
cznic's avatar
cznic committed
163 164 165 166
			return err
		}
	}

167
	r.doStep = true
cznic's avatar
cznic committed
168 169

	switch rc {
cznic's avatar
cznic committed
170
	case bin.DSQLITE_ROW:
cznic's avatar
cznic committed
171 172 173 174 175 176 177 178 179 180 181
		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
182
			case bin.DSQLITE_INTEGER:
cznic's avatar
cznic committed
183 184 185 186 187 188
				v, err := r.columnInt64(i)
				if err != nil {
					return err
				}

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

				dest[i] = v
cznic's avatar
cznic committed
196
			case bin.DSQLITE_TEXT:
cznic's avatar
cznic committed
197 198 199 200 201 202
				v, err := r.columnText(i)
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
203
			case bin.DSQLITE_BLOB:
cznic's avatar
cznic committed
204 205 206 207 208 209
				v, err := r.columnBlob(i)
				if err != nil {
					return err
				}

				dest[i] = v
cznic's avatar
cznic committed
210
			case bin.DSQLITE_NULL:
cznic's avatar
cznic committed
211 212
				dest[i] = nil
			default:
cznic's avatar
cznic committed
213
				return fmt.Errorf("internal error: rc %d", rc)
cznic's avatar
cznic committed
214 215 216
			}
		}
		return nil
cznic's avatar
cznic committed
217
	case bin.DSQLITE_DONE:
cznic's avatar
cznic committed
218 219 220 221 222 223 224 225
		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) {
226 227
	v := bin.Xsqlite3_column_bytes(r.tls, r.pstmt, int32(iCol))
	return int(v), nil
cznic's avatar
cznic committed
228 229 230 231
}

// const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
func (r *rows) columnBlob(iCol int) (v []byte, err error) {
232
	p := bin.Xsqlite3_column_blob(r.tls, r.pstmt, int32(iCol))
cznic's avatar
cznic committed
233 234 235 236 237
	len, err := r.columnBytes(iCol)
	if err != nil {
		return nil, err
	}

cznic's avatar
cznic committed
238 239 240 241 242 243 244
	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
245 246 247 248
}

// const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
func (r *rows) columnText(iCol int) (v string, err error) {
249
	p := bin.Xsqlite3_column_text(r.tls, r.pstmt, int32(iCol))
cznic's avatar
cznic committed
250 251 252 253 254
	len, err := r.columnBytes(iCol)
	if err != nil {
		return "", err
	}

cznic's avatar
cznic committed
255 256 257 258 259 260 261
	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
262 263 264 265
}

// double sqlite3_column_double(sqlite3_stmt*, int iCol);
func (r *rows) columnDouble(iCol int) (v float64, err error) {
266 267
	v = bin.Xsqlite3_column_double(r.tls, r.pstmt, int32(iCol))
	return v, nil
cznic's avatar
cznic committed
268 269 270 271
}

// sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
func (r *rows) columnInt64(iCol int) (v int64, err error) {
272 273
	v = bin.Xsqlite3_column_int64(r.tls, r.pstmt, int32(iCol))
	return v, nil
cznic's avatar
cznic committed
274 275 276 277
}

// int sqlite3_column_type(sqlite3_stmt*, int iCol);
func (r *rows) columnType(iCol int) (_ int, err error) {
278 279
	v := bin.Xsqlite3_column_type(r.tls, r.pstmt, int32(iCol))
	return int(v), nil
cznic's avatar
cznic committed
280 281 282 283
}

// int sqlite3_column_count(sqlite3_stmt *pStmt);
func (r *rows) columnCount() (_ int, err error) {
284 285
	v := bin.Xsqlite3_column_count(r.tls, r.pstmt)
	return int(v), nil
cznic's avatar
cznic committed
286 287 288 289
}

// const char *sqlite3_column_name(sqlite3_stmt*, int N);
func (r *rows) columnName(n int) (string, error) {
290 291
	p := bin.Xsqlite3_column_name(r.tls, r.pstmt, int32(n))
	return crt.GoString(p), nil
cznic's avatar
cznic committed
292 293 294 295
}

type stmt struct {
	*conn
cznic's avatar
cznic committed
296 297 298 299
	allocs []crt.Intptr
	psql   crt.Intptr // *int8
	ppstmt crt.Intptr // **sqlite3_stmt
	pzTail crt.Intptr // **int8
cznic's avatar
cznic committed
300 301
}

302
func newStmt(c *conn, sql string) (*stmt, error) {
cznic's avatar
cznic committed
303
	s := &stmt{conn: c}
304
	psql, err := s.cString(sql)
cznic's avatar
cznic committed
305 306 307 308
	if err != nil {
		return nil, err
	}

309 310
	s.psql = psql
	ppstmt, err := s.malloc(ptrSize)
cznic's avatar
cznic committed
311
	if err != nil {
cznic's avatar
cznic committed
312
		s.free(psql)
cznic's avatar
cznic committed
313 314 315
		return nil, err
	}

cznic's avatar
cznic committed
316
	s.ppstmt = ppstmt
cznic's avatar
cznic committed
317 318
	pzTail, err := s.malloc(ptrSize)
	if err != nil {
cznic's avatar
cznic committed
319
		s.free(psql)
320
		s.free(ppstmt)
cznic's avatar
cznic committed
321 322 323
		return nil, err
	}

cznic's avatar
cznic committed
324
	s.pzTail = pzTail
cznic's avatar
cznic committed
325 326 327 328 329 330 331
	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
332 333 334
	if s.psql != 0 {
		err = s.free(s.psql)
		s.psql = 0
cznic's avatar
cznic committed
335
	}
cznic's avatar
cznic committed
336 337
	if s.ppstmt != 0 {
		if err2 := s.free(s.ppstmt); err2 != nil && err == nil {
cznic's avatar
cznic committed
338 339
			err = err2
		}
cznic's avatar
cznic committed
340
		s.ppstmt = 0
cznic's avatar
cznic committed
341
	}
cznic's avatar
cznic committed
342 343
	if s.pzTail != 0 {
		if err2 := s.free(s.pzTail); err2 != nil && err == nil {
cznic's avatar
cznic committed
344 345
			err = err2
		}
cznic's avatar
cznic committed
346
		s.pzTail = 0
cznic's avatar
cznic committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
	}
	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.
371 372 373 374 375
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
376
	var pstmt crt.Intptr
377 378 379 380 381 382

	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
cznic's avatar
cznic committed
383
			if pstmt != 0 {
384 385 386 387 388 389
				s.interrupt(s.pdb())
			}
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
390
	for psql := s.psql; *(*byte)(unsafe.Pointer(uintptr(psql))) != 0; psql = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.pzTail))) {
cznic's avatar
cznic committed
391 392 393 394
		if err := s.prepareV2(psql); err != nil {
			return nil, err
		}

cznic's avatar
cznic committed
395 396
		pstmt = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.ppstmt)))
		if pstmt == 0 {
cznic's avatar
cznic committed
397 398 399
			continue
		}

400
		n, err := s.bindParameterCount(pstmt)
cznic's avatar
cznic committed
401 402 403 404 405
		if err != nil {
			return nil, err
		}

		if n != 0 {
406
			if err = s.bind(pstmt, n, args); err != nil {
cznic's avatar
cznic committed
407 408 409
				return nil, err
			}
		}
410

411
		rc, err := s.step(pstmt)
cznic's avatar
cznic committed
412
		if err != nil {
413
			s.finalize(pstmt)
cznic's avatar
cznic committed
414 415 416 417
			return nil, err
		}

		switch rc & 0xff {
cznic's avatar
cznic committed
418
		case bin.DSQLITE_DONE, bin.DSQLITE_ROW:
419
			if err := s.finalize(pstmt); err != nil {
cznic's avatar
cznic committed
420 421 422 423
				return nil, err
			}
		default:
			err = s.errstr(int32(rc))
424
			s.finalize(pstmt)
cznic's avatar
cznic committed
425 426 427 428 429 430
			return nil, err
		}
	}
	return newResult(s)
}

431 432 433 434 435
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
436
	var pstmt, rowStmt crt.Intptr
cznic's avatar
cznic committed
437
	var rc0 int
438 439 440 441 442 443

	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
cznic's avatar
cznic committed
444
			if pstmt != 0 {
445 446 447 448 449 450
				s.interrupt(s.pdb())
			}
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
451
	for psql := s.psql; *(*byte)(unsafe.Pointer(uintptr(psql))) != 0; psql = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.pzTail))) {
cznic's avatar
cznic committed
452 453 454 455
		if err := s.prepareV2(psql); err != nil {
			return nil, err
		}

cznic's avatar
cznic committed
456 457
		pstmt = *(*crt.Intptr)(unsafe.Pointer(uintptr(s.ppstmt)))
		if pstmt == 0 {
cznic's avatar
cznic committed
458 459 460
			continue
		}

461
		n, err := s.bindParameterCount(pstmt)
cznic's avatar
cznic committed
462 463 464 465 466
		if err != nil {
			return nil, err
		}

		if n != 0 {
467
			if err = s.bind(pstmt, n, args); err != nil {
cznic's avatar
cznic committed
468 469 470
				return nil, err
			}
		}
471

472
		rc, err := s.step(pstmt)
cznic's avatar
cznic committed
473
		if err != nil {
474
			s.finalize(pstmt)
cznic's avatar
cznic committed
475 476 477 478
			return nil, err
		}

		switch rc {
cznic's avatar
cznic committed
479 480
		case bin.DSQLITE_ROW:
			if rowStmt != 0 {
481
				if err := s.finalize(pstmt); err != nil {
cznic's avatar
cznic committed
482 483 484 485 486 487
					return nil, err
				}

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

488
			rowStmt = pstmt
cznic's avatar
cznic committed
489
			rc0 = rc
cznic's avatar
cznic committed
490 491
		case bin.DSQLITE_DONE:
			if rowStmt == 0 {
cznic's avatar
cznic committed
492 493 494 495
				rc0 = rc
			}
		default:
			err = s.errstr(int32(rc))
496
			s.finalize(pstmt)
cznic's avatar
cznic committed
497 498 499 500 501 502 503
			return nil, err
		}
	}
	return newRows(s, rowStmt, rc0)
}

// int sqlite3_bind_double(sqlite3_stmt*, int, double);
cznic's avatar
cznic committed
504
func (s *stmt) bindDouble(pstmt crt.Intptr, idx1 int, value float64) (err error) {
505
	if rc := bin.Xsqlite3_bind_double(s.tls, pstmt, int32(idx1), value); rc != 0 {
cznic's avatar
cznic committed
506 507 508 509 510 511 512
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int(sqlite3_stmt*, int, int);
cznic's avatar
cznic committed
513 514
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
515 516 517 518 519 520 521
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
cznic's avatar
cznic committed
522 523
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
524 525 526 527 528 529 530
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
cznic's avatar
cznic committed
531
func (s *stmt) bindBlob(pstmt crt.Intptr, idx1 int, value []byte) (err error) {
cznic's avatar
cznic committed
532 533 534 535 536 537
	p, err := s.malloc(len(value))
	if err != nil {
		return err
	}

	s.allocs = append(s.allocs, p)
cznic's avatar
cznic committed
538 539
	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
540 541 542 543 544 545 546
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
cznic's avatar
cznic committed
547
func (s *stmt) bindText(pstmt crt.Intptr, idx1 int, value string) (err error) {
cznic's avatar
cznic committed
548 549 550 551 552
	p, err := s.cString(value)
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
553 554
	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
555 556 557 558 559 560
		return s.errstr(rc)
	}

	return nil
}

cznic's avatar
cznic committed
561
func (s *stmt) bind(pstmt crt.Intptr, n int, args []namedValue) error {
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	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:])
			}
590 591

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

594
		switch x := v.Value.(type) {
cznic's avatar
cznic committed
595
		case int64:
596
			if err := s.bindInt64(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
597 598 599
				return err
			}
		case float64:
600
			if err := s.bindDouble(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
601 602 603 604 605 606 607
				return err
			}
		case bool:
			v := 0
			if x {
				v = 1
			}
608
			if err := s.bindInt(pstmt, i, v); err != nil {
cznic's avatar
cznic committed
609 610 611
				return err
			}
		case []byte:
612
			if err := s.bindBlob(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
613 614 615
				return err
			}
		case string:
616
			if err := s.bindText(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
617 618 619
				return err
			}
		case time.Time:
620
			if err := s.bindText(pstmt, i, x.String()); err != nil {
cznic's avatar
cznic committed
621 622 623 624 625 626 627 628 629 630
				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
631
func (s *stmt) bindParameterCount(pstmt crt.Intptr) (_ int, err error) {
632 633
	r := bin.Xsqlite3_bind_parameter_count(s.tls, pstmt)
	return int(r), nil
cznic's avatar
cznic committed
634 635
}

636
// const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
cznic's avatar
cznic committed
637
func (s *stmt) bindParameterName(pstmt crt.Intptr, i int) (string, error) {
638 639
	p := bin.Xsqlite3_bind_parameter_name(s.tls, pstmt, int32(i))
	return crt.GoString(p), nil
640 641
}

cznic's avatar
cznic committed
642
// int sqlite3_finalize(sqlite3_stmt *pStmt);
cznic's avatar
cznic committed
643 644
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
645 646 647 648 649 650 651
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_step(sqlite3_stmt*);
cznic's avatar
cznic committed
652
func (s *stmt) step(pstmt crt.Intptr) (int, error) {
653 654
	r := bin.Xsqlite3_step(s.tls, pstmt)
	return int(r), nil
cznic's avatar
cznic committed
655 656 657 658 659 660 661 662 663
}

// 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
664 665
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
666 667 668 669 670 671 672 673 674 675 676 677
		return s.errstr(rc)
	}

	return nil
}

type tx struct {
	*conn
}

func newTx(c *conn) (*tx, error) {
	t := &tx{conn: c}
678
	if err := t.exec(context.Background(), "begin"); err != nil {
cznic's avatar
cznic committed
679 680 681 682 683 684 685 686
		return nil, err
	}

	return t, nil
}

// Commit implements driver.Tx.
func (t *tx) Commit() (err error) {
687
	return t.exec(context.Background(), "commit")
cznic's avatar
cznic committed
688 689 690 691
}

// Rollback implements driver.Tx.
func (t *tx) Rollback() (err error) {
692
	return t.exec(context.Background(), "rollback")
cznic's avatar
cznic committed
693 694 695 696 697 698 699 700 701
}

// 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 */
// );
702
func (t *tx) exec(ctx context.Context, sql string) (err error) {
703
	psql, err := t.cString(sql)
cznic's avatar
cznic committed
704 705 706 707
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
708
	defer t.free(psql)
cznic's avatar
cznic committed
709

cznic's avatar
cznic committed
710
	//TODO use t.conn.ExecContext() instead
711 712 713 714 715 716 717 718 719 720
	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
			t.interrupt(t.pdb())
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
721
	if rc := bin.Xsqlite3_exec(t.tls, t.pdb(), psql, 0, 0, 0); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
722 723 724 725 726 727 728
		return t.errstr(rc)
	}

	return nil
}

type conn struct {
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
729
	*Driver
cznic's avatar
cznic committed
730
	ppdb crt.Intptr // **bin.Xsqlite3
731
	tls  *crt.TLS
cznic's avatar
cznic committed
732 733
}

Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
734 735
func newConn(s *Driver, name string) (_ *conn, err error) {
	c := &conn{Driver: s}
cznic's avatar
cznic committed
736 737 738 739 740 741 742

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

743
	c.tls = crt.NewTLS()
cznic's avatar
cznic committed
744 745
	if err = c.openV2(
		name,
cznic's avatar
cznic committed
746 747 748
		bin.DSQLITE_OPEN_READWRITE|bin.DSQLITE_OPEN_CREATE|
			bin.DSQLITE_OPEN_FULLMUTEX|
			bin.DSQLITE_OPEN_URI,
cznic's avatar
cznic committed
749 750 751 752 753 754 755 756 757 758 759 760 761
	); 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) {
762 763 764 765
	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
766 767 768 769 770 771 772 773 774 775 776 777 778
	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()
}

779 780 781 782 783 784 785 786 787 788 789 790
// 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
791 792 793 794 795 796 797 798 799
	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.
800 801 802 803 804
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) {
805
	s, err := c.prepare(ctx, query)
cznic's avatar
cznic committed
806 807 808 809 810 811 812 813 814 815
	if err != nil {
		return nil, err
	}

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

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
	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
833 834 835 836 837 838 839 840
}

// 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.
841 842 843 844 845
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) {
846
	s, err := c.prepare(ctx, query)
cznic's avatar
cznic committed
847 848 849 850 851 852 853 854 855 856
	if err != nil {
		return nil, err
	}

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

857
	return s.(*stmt).query(ctx, args)
cznic's avatar
cznic committed
858 859
}

cznic's avatar
cznic committed
860
func (c *conn) pdb() crt.Intptr { return *(*crt.Intptr)(unsafe.Pointer(uintptr(c.ppdb))) }
cznic's avatar
cznic committed
861 862 863

// int sqlite3_extended_result_codes(sqlite3*, int onoff);
func (c *conn) extendedResultCodes(on bool) (err error) {
cznic's avatar
cznic committed
864
	if rc := bin.Xsqlite3_extended_result_codes(c.tls, c.pdb(), crt.Bool32(on)); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
865 866 867 868 869 870 871
		return c.errstr(rc)
	}

	return nil
}

// void *sqlite3_malloc(int);
cznic's avatar
cznic committed
872
func (c *conn) malloc(n int) (r crt.Intptr, err error) {
873
	if n > math.MaxInt32 {
cznic's avatar
cznic committed
874
		return 0, fmt.Errorf("cannot allocate %d bytes of memory", n)
875 876 877
	}

	r = bin.Xsqlite3_malloc(c.tls, int32(n))
cznic's avatar
cznic committed
878 879
	if r == 0 {
		return 0, fmt.Errorf("malloc(%v) failed", n)
880 881 882
	}

	return r, nil
cznic's avatar
cznic committed
883 884
}

cznic's avatar
cznic committed
885
func (c *conn) cString(s string) (crt.Intptr, error) {
cznic's avatar
cznic committed
886
	n := len(s)
887 888
	p, err := c.malloc(n + 1)
	if err != nil {
cznic's avatar
cznic committed
889
		return 0, err
cznic's avatar
cznic committed
890 891
	}

cznic's avatar
cznic committed
892 893 894
	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
895 896 897 898 899 900 901 902 903 904 905 906 907 908
}

// 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
909
	defer c.free(filename)
cznic's avatar
cznic committed
910

911
	ppdb, err := c.malloc(ptrSize)
cznic's avatar
cznic committed
912 913 914 915
	if err != nil {
		return err
	}

cznic's avatar
cznic committed
916 917
	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
918 919 920 921 922 923 924 925
		return c.errstr(rc)
	}

	return nil
}

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

930
	switch msg := crt.GoString(p); {
cznic's avatar
cznic committed
931 932 933 934 935 936 937 938 939
	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
940
	if rc := bin.Xsqlite3_close_v2(c.tls, c.pdb()); rc != bin.DSQLITE_OK {
cznic's avatar
cznic committed
941 942 943
		return c.errstr(rc)
	}

cznic's avatar
cznic committed
944 945
	err = c.free(c.ppdb)
	c.ppdb = 0
cznic's avatar
cznic committed
946 947 948 949
	return err
}

// void sqlite3_free(void*);
cznic's avatar
cznic committed
950
func (c *conn) free(p crt.Intptr) (err error) {
951 952
	bin.Xsqlite3_free(c.tls, p)
	return nil
cznic's avatar
cznic committed
953 954
}

955
// void sqlite3_interrupt(sqlite3*);
cznic's avatar
cznic committed
956
func (c *conn) interrupt(pdb crt.Intptr) (err error) {
957 958
	bin.Xsqlite3_interrupt(c.tls, pdb)
	return nil
959 960
}

cznic's avatar
cznic committed
961 962 963
func (c *conn) close() (err error) {
	c.Lock()

964
	defer c.Unlock()
cznic's avatar
cznic committed
965

cznic's avatar
cznic committed
966
	if c.ppdb != 0 {
cznic's avatar
cznic committed
967 968 969 970 971
		err = c.closeV2()
	}
	return err
}

972
// Driver implements database/sql/driver.Driver.
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
973
type Driver struct {
cznic's avatar
cznic committed
974 975 976
	sync.Mutex
}

Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
977
func newDrv() *Driver { return &Driver{} }
cznic's avatar
cznic committed
978 979 980 981 982 983 984 985 986

// 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
987
func (s *Driver) Open(name string) (c driver.Conn, err error) {
cznic's avatar
cznic committed
988 989
	return newConn(s, name)
}