sqlite.go 30.3 KB
Newer Older
cznic's avatar
cznic committed
1 2 3 4 5 6 7 8 9
// 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.

//go:generate go run generator.go

// Package sqlite is an in-process implementation of a self-contained,
// serverless, zero-configuration, transactional SQL database engine. (Work In Progress)
//
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Connecting to a database
//
// To access a Sqlite database do something like
//
//	import (
//		"database/sql"
//
//		_ "github.com/cznic/sqlite"
//	)
//
//	...
//
//
//	db, err := sql.Open("sqlite", dsnURI)
//
//	...
//
//
cznic's avatar
cznic committed
28 29 30 31
// Do not use in production
//
// This is an experimental, pre-alpha, technology preview package. Performance
// is not (yet) a priority. When this virtual machine approach, hopefully,
cznic's avatar
cznic committed
32
// reaches a reasonable level of completeness and correctness, the plan is to
cznic's avatar
cznic committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
// eventually mechanically translate the IR form, produced by
// http://github.com/cznic/ccir, to Go. Unreadable Go, presumably.
//
// Supported platforms and architectures
//
// See http://github.com/cznic/ccir. To add a newly supported os/arch
// combination to this package try running 'go generate'.
//
// Sqlite documentation
//
// See https://sqlite.org/docs.html
package sqlite

import (
	"bytes"
	"compress/gzip"
	"database/sql"
	"database/sql/driver"
	"encoding/gob"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"runtime"
	"sync"
	"time"
	"unsafe"

	"github.com/cznic/internal/buffer"
	"github.com/cznic/ir"
	"github.com/cznic/mathutil"
	"github.com/cznic/sqlite/internal/bin"
	"github.com/cznic/virtual"
	"github.com/cznic/xc"
67
	"golang.org/x/net/context"
cznic's avatar
cznic committed
68 69 70 71
)

var (
	_ driver.Conn    = (*conn)(nil)
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
72
	_ driver.Driver  = (*Driver)(nil)
cznic's avatar
cznic committed
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
	_ driver.Execer  = (*conn)(nil)
	_ driver.Queryer = (*conn)(nil)
	_ driver.Result  = (*result)(nil)
	_ driver.Rows    = (*rows)(nil)
	_ driver.Stmt    = (*stmt)(nil)
	_ driver.Tx      = (*tx)(nil)
	_ io.Writer      = debugWriter{}
)

const (
	driverName      = "sqlite"
	ptrSize         = mathutil.UintPtrBits / 8
	vmHeapReserve   = 1 << 20
	vmHeapSize      = 32 << 20
	vmMainStackSize = 1 << 16
	vmStackSize     = 1 << 18
)

var (
	binary virtual.Binary
	dict   = xc.Dict
	null   = virtual.Ptr(0)
	vm     *virtual.Machine

	// FFI
	bindBlob            int
	bindDouble          int
	bindInt             int
	bindInt64           int
	bindParameterCount  int
103
	bindParameterName   int
cznic's avatar
cznic committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	bindText            int
	changes             int
	closeV2             int
	columnBlob          int
	columnBytes         int
	columnCount         int
	columnDouble        int
	columnInt64         int
	columnName          int
	columnText          int
	columnType          int
	errmsg              int
	errstr              int
	exec                int
	extendedResultCodes int
	finalize            int
	free                int
121
	interrupt           int
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 161 162
	lastInsertRowID     int
	maloc               int
	openV2              int
	prepareV2           int
	step                int
)

func init() {
	b0 := bytes.NewBufferString(bin.Data)
	decomp, err := gzip.NewReader(b0)
	if err != nil {
		panic(err)
	}

	var b1 bytes.Buffer
	chunk := make([]byte, 1<<15)
	for {
		n, err := decomp.Read(chunk)
		b1.Write(chunk[:n])
		if err != nil {
			if err != io.EOF {
				panic(err)
			}

			break
		}
	}
	dec := gob.NewDecoder(&b1)
	if err := dec.Decode(&binary); err != nil {
		panic(err)
	}

	for _, v := range []struct {
		*int
		string
	}{
		{&bindBlob, "sqlite3_bind_blob"},
		{&bindDouble, "sqlite3_bind_double"},
		{&bindInt, "sqlite3_bind_int"},
		{&bindInt64, "sqlite3_bind_int64"},
		{&bindParameterCount, "sqlite3_bind_parameter_count"},
163
		{&bindParameterName, "sqlite3_bind_parameter_name"},
cznic's avatar
cznic committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
		{&bindText, "sqlite3_bind_text"},
		{&changes, "sqlite3_changes"},
		{&closeV2, "sqlite3_close_v2"},
		{&columnBlob, "sqlite3_column_blob"},
		{&columnBytes, "sqlite3_column_bytes"},
		{&columnCount, "sqlite3_column_count"},
		{&columnDouble, "sqlite3_column_double"},
		{&columnInt64, "sqlite3_column_int64"},
		{&columnName, "sqlite3_column_name"},
		{&columnText, "sqlite3_column_text"},
		{&columnType, "sqlite3_column_type"},
		{&errmsg, "sqlite3_errmsg"},
		{&errstr, "sqlite3_errstr"},
		{&exec, "sqlite3_exec"},
		{&extendedResultCodes, "sqlite3_extended_result_codes"},
		{&finalize, "sqlite3_finalize"},
		{&free, "sqlite3_free"},
181
		{&interrupt, "sqlite3_interrupt"},
cznic's avatar
cznic committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
		{&lastInsertRowID, "sqlite3_last_insert_rowid"},
		{&maloc, "sqlite3_malloc"},
		{&openV2, "sqlite3_open_v2"},
		{&prepareV2, "sqlite3_prepare_v2"},
		{&step, "sqlite3_step"},
	} {
		var ok bool
		if *v.int, ok = binary.Sym[ir.NameID(dict.SID(v.string))]; !ok {
			panic(fmt.Errorf("missing symbol: %v", v.string))
		}
	}

	sql.Register(driverName, newDrv())
}

func tracer(rx interface{}, format string, args ...interface{}) {
	var b buffer.Bytes
	_, file, line, _ := runtime.Caller(1)
	fmt.Fprintf(&b, "%v:%v: (%[3]T)(%[3]p).", file, line, rx)
	fmt.Fprintf(&b, format, args...)
	fmt.Fprintf(os.Stderr, "%s\n", b.Bytes())
	b.Close()
}

func readI8(p uintptr) int8     { return *(*int8)(unsafe.Pointer(p)) }
func readPtr(p uintptr) uintptr { return *(*uintptr)(unsafe.Pointer(p)) }

type debugWriter struct{}

func (debugWriter) Write(b []byte) (int, error) { return os.Stderr.Write(b) }

type result struct {
	*stmt
	lastInsertId int64
	rowsAffected int
}

func (r *result) String() string {
	return fmt.Sprintf("&%T@%p{stmt: %p, LastInsertId: %v, RowsAffected: %v}", *r, r, r.stmt, r.lastInsertId, r.rowsAffected)
}

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

	if r.lastInsertId, err = r.lastInsertRowID(); err != nil {
		return nil, err
	}

	return r, nil
}

// sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
func (r *result) lastInsertRowID() (v int64, _ error) {
	_, err := r.FFI1(
		lastInsertRowID,
		virtual.Int64Result{&v},
241
		virtual.Ptr(r.pdb()),
cznic's avatar
cznic committed
242 243 244 245 246 247 248 249 250 251
	)
	return v, err
}

// int sqlite3_changes(sqlite3*);
func (r *result) changes() (int, error) {
	var v int32
	_, err := r.FFI1(
		changes,
		virtual.Int32Result{&v},
252
		virtual.Ptr(r.pdb()),
cznic's avatar
cznic committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
	)
	return int(v), err
}

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

	return r.lastInsertId, nil
}

// 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
	pstmt   uintptr
281
	doStep  bool
cznic's avatar
cznic committed
282 283 284
}

func (r *rows) String() string {
285
	return fmt.Sprintf("&%T@%p{stmt: %p, columns: %v, rc0: %v, pstmt: %#x, doStep: %v}", *r, r, r.stmt, r.columns, r.rc0, r.pstmt, r.doStep)
cznic's avatar
cznic committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
}

func newRows(s *stmt, pstmt uintptr, rc0 int) (*rows, error) {
	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) {
	if trace {
		defer func() {
			tracer(r, "Columns(): %v", c)
		}()
	}
	return r.columns
}

// Close closes the rows iterator.
func (r *rows) Close() (err error) {
	if trace {
		defer func() {
			tracer(r, "Close(): %v", err)
		}()
	}
	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) {
	if trace {
		defer func() {
			tracer(r, "Next(%v): %v", dest, err)
		}()
	}
	rc := r.rc0
343 344
	if r.doStep {
		if rc, err = r.step(r.pstmt); err != nil {
cznic's avatar
cznic committed
345 346 347 348
			return err
		}
	}

349
	r.doStep = true
cznic's avatar
cznic committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

	switch rc {
	case bin.XSQLITE_ROW:
		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 {
			case bin.XSQLITE_INTEGER:
				v, err := r.columnInt64(i)
				if err != nil {
					return err
				}

				dest[i] = v
			case bin.XSQLITE_FLOAT:
				v, err := r.columnDouble(i)
				if err != nil {
					return err
				}

				dest[i] = v
			case bin.XSQLITE_TEXT:
				v, err := r.columnText(i)
				if err != nil {
					return err
				}

				dest[i] = v
			case bin.XSQLITE_BLOB:
				v, err := r.columnBlob(i)
				if err != nil {
					return err
				}

				dest[i] = v
			case bin.XSQLITE_NULL:
				dest[i] = nil
			default:
				panic("internal error")
			}
		}
		return nil
	case bin.XSQLITE_DONE:
		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) {
	var v int32
	if _, err = r.FFI1(
		columnBytes,
		virtual.Int32Result{&v},
		virtual.Ptr(r.pstmt), virtual.Int32(iCol),
	); err != nil {
		return 0, err
	}

	return int(v), err
}

// const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
func (r *rows) columnBlob(iCol int) (v []byte, err error) {
	var p uintptr
	if _, err = r.FFI1(
		columnBlob,
		virtual.PtrResult{&p},
		virtual.Ptr(r.pstmt), virtual.Int32(iCol),
	); err != nil {
		return nil, err
	}

	len, err := r.columnBytes(iCol)
	if err != nil {
		return nil, err
	}

	return virtual.GoBytesLen(p, len), nil
}

// const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
func (r *rows) columnText(iCol int) (v string, err error) {
	var p uintptr
	if _, err = r.FFI1(
		columnText,
		virtual.PtrResult{&p},
		virtual.Ptr(r.pstmt), virtual.Int32(iCol),
	); err != nil {
		return "", err
	}

	len, err := r.columnBytes(iCol)
	if err != nil {
		return "", err
	}

	return virtual.GoStringLen(p, len), nil
}

// double sqlite3_column_double(sqlite3_stmt*, int iCol);
func (r *rows) columnDouble(iCol int) (v float64, err error) {
	_, err = r.FFI1(
		columnDouble,
		virtual.Float64Result{&v},
		virtual.Ptr(r.pstmt), virtual.Int32(iCol),
	)
	return v, err
}

// sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
func (r *rows) columnInt64(iCol int) (v int64, err error) {
	_, err = r.FFI1(
		columnInt64,
		virtual.Int64Result{&v},
		virtual.Ptr(r.pstmt), virtual.Int32(iCol),
	)
	return v, err
}

// int sqlite3_column_type(sqlite3_stmt*, int iCol);
func (r *rows) columnType(iCol int) (_ int, err error) {
	var v int32
	_, err = r.FFI1(
		columnType,
		virtual.Int32Result{&v},
		virtual.Ptr(r.pstmt), virtual.Int32(iCol),
	)
	return int(v), err
}

// int sqlite3_column_count(sqlite3_stmt *pStmt);
func (r *rows) columnCount() (_ int, err error) {
	var v int32
	_, err = r.FFI1(
		columnCount,
		virtual.Int32Result{&v},
		virtual.Ptr(r.pstmt),
	)
	return int(v), err
}

// const char *sqlite3_column_name(sqlite3_stmt*, int N);
func (r *rows) columnName(n int) (string, error) {
	var p uintptr
	if _, err := r.FFI1(
		columnName,
		virtual.PtrResult{&p},
		virtual.Ptr(r.pstmt), virtual.Int32(n),
	); err != nil {
		return "", err
	}

	return virtual.GoString(p), nil
}

type stmt struct {
	*conn
	allocs []uintptr
517 518
	psql   uintptr
	ppstmt uintptr
cznic's avatar
cznic committed
519 520 521 522
	pzTail uintptr
}

func (s *stmt) String() string {
523
	return fmt.Sprintf("&%T@%p{conn: %p, alloc %v, psql: %#x, ppstmt: %#x, pzTail: %#x}", *s, s, s.conn, s.allocs, s.psql, s.ppstmt, s.pzTail)
cznic's avatar
cznic committed
524 525
}

526
func newStmt(c *conn, sql string) (*stmt, error) {
cznic's avatar
cznic committed
527
	s := &stmt{conn: c}
528
	psql, err := s.cString(sql)
cznic's avatar
cznic committed
529 530 531 532
	if err != nil {
		return nil, err
	}

533 534
	s.psql = psql
	ppstmt, err := s.malloc(ptrSize)
cznic's avatar
cznic committed
535
	if err != nil {
536
		s.free(psql)
cznic's avatar
cznic committed
537 538 539
		return nil, err
	}

540
	s.ppstmt = ppstmt
cznic's avatar
cznic committed
541 542
	pzTail, err := s.malloc(ptrSize)
	if err != nil {
543 544
		s.free(psql)
		s.free(ppstmt)
cznic's avatar
cznic committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
		return nil, err
	}

	s.pzTail = pzTail
	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) {
	if trace {
		defer func() {
			tracer(s, "Close(): %v", err)
		}()
	}
561 562 563
	if s.psql != 0 {
		err = s.free(s.psql)
		s.psql = 0
cznic's avatar
cznic committed
564
	}
565 566
	if s.ppstmt != 0 {
		if err2 := s.free(s.ppstmt); err2 != nil && err == nil {
cznic's avatar
cznic committed
567 568
			err = err2
		}
569
		s.ppstmt = 0
cznic's avatar
cznic committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
	}
	if s.pzTail != 0 {
		if err2 := s.free(s.pzTail); err2 != nil && err == nil {
			err = err2
		}
		s.pzTail = 0
	}
	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) {
	if trace {
		defer func() {
			tracer(s, "NumInput(): %v", n)
		}()
	}
	return -1
}

// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
605 606 607 608 609
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
610
	if trace {
611
		defer func(args []namedValue) {
cznic's avatar
cznic committed
612 613 614
			tracer(s, "Exec(%v): (%v, %v)", args, r, err)
		}(args)
	}
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

	var pstmt uintptr

	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
			if pstmt != 0 {
				s.interrupt(s.pdb())
			}
		case <-donech:
		}
	}()

630
	for psql := s.psql; readI8(psql) != 0; psql = readPtr(s.pzTail) {
cznic's avatar
cznic committed
631 632 633 634
		if err := s.prepareV2(psql); err != nil {
			return nil, err
		}

635
		pstmt = readPtr(s.ppstmt)
636
		if pstmt == 0 {
cznic's avatar
cznic committed
637 638 639
			continue
		}

640
		n, err := s.bindParameterCount(pstmt)
cznic's avatar
cznic committed
641 642 643 644 645
		if err != nil {
			return nil, err
		}

		if n != 0 {
646
			if err = s.bind(pstmt, n, args); err != nil {
cznic's avatar
cznic committed
647 648 649
				return nil, err
			}
		}
650

651
		rc, err := s.step(pstmt)
cznic's avatar
cznic committed
652
		if err != nil {
653
			s.finalize(pstmt)
cznic's avatar
cznic committed
654 655 656 657 658
			return nil, err
		}

		switch rc & 0xff {
		case bin.XSQLITE_DONE, bin.XSQLITE_ROW:
659
			if err := s.finalize(pstmt); err != nil {
cznic's avatar
cznic committed
660 661 662 663
				return nil, err
			}
		default:
			err = s.errstr(int32(rc))
664
			s.finalize(pstmt)
cznic's avatar
cznic committed
665 666 667 668 669 670
			return nil, err
		}
	}
	return newResult(s)
}

671 672 673 674 675
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
676
	if trace {
677
		defer func(args []namedValue) {
cznic's avatar
cznic committed
678 679 680
			tracer(s, "Query(%v): (%v, %v)", args, r, err)
		}(args)
	}
681 682

	var pstmt uintptr
cznic's avatar
cznic committed
683 684
	var rowStmt uintptr
	var rc0 int
685 686 687 688 689 690 691 692 693 694 695 696 697

	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
			if pstmt != 0 {
				s.interrupt(s.pdb())
			}
		case <-donech:
		}
	}()

698
	for psql := s.psql; readI8(psql) != 0; psql = readPtr(s.pzTail) {
cznic's avatar
cznic committed
699 700 701 702
		if err := s.prepareV2(psql); err != nil {
			return nil, err
		}

703
		pstmt = readPtr(s.ppstmt)
704
		if pstmt == 0 {
cznic's avatar
cznic committed
705 706 707
			continue
		}

708
		n, err := s.bindParameterCount(pstmt)
cznic's avatar
cznic committed
709 710 711 712 713
		if err != nil {
			return nil, err
		}

		if n != 0 {
714
			if err = s.bind(pstmt, n, args); err != nil {
cznic's avatar
cznic committed
715 716 717
				return nil, err
			}
		}
718

719
		rc, err := s.step(pstmt)
cznic's avatar
cznic committed
720
		if err != nil {
721
			s.finalize(pstmt)
cznic's avatar
cznic committed
722 723 724 725 726 727
			return nil, err
		}

		switch rc {
		case bin.XSQLITE_ROW:
			if rowStmt != 0 {
728
				if err := s.finalize(pstmt); err != nil {
cznic's avatar
cznic committed
729 730 731 732 733 734
					return nil, err
				}

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

735
			rowStmt = pstmt
cznic's avatar
cznic committed
736 737 738 739 740 741 742
			rc0 = rc
		case bin.XSQLITE_DONE:
			if rowStmt == 0 {
				rc0 = rc
			}
		default:
			err = s.errstr(int32(rc))
743
			s.finalize(pstmt)
cznic's avatar
cznic committed
744 745 746 747 748 749 750
			return nil, err
		}
	}
	return newRows(s, rowStmt, rc0)
}

// int sqlite3_bind_double(sqlite3_stmt*, int, double);
751
func (s *stmt) bindDouble(pstmt uintptr, idx1 int, value float64) (err error) {
cznic's avatar
cznic committed
752 753 754 755
	var rc int32
	if _, err = s.FFI1(
		bindDouble,
		virtual.Int32Result{&rc},
756
		virtual.Ptr(pstmt), virtual.Int32(int32(idx1)), virtual.Float64(value),
cznic's avatar
cznic committed
757 758 759 760 761 762 763 764 765 766 767 768
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int(sqlite3_stmt*, int, int);
769
func (s *stmt) bindInt(pstmt uintptr, idx1, value int) (err error) {
cznic's avatar
cznic committed
770 771 772 773
	var rc int32
	if _, err = s.FFI1(
		bindInt,
		virtual.Int32Result{&rc},
774
		virtual.Ptr(pstmt), virtual.Int32(int32(idx1)), virtual.Int32(int32(value)),
cznic's avatar
cznic committed
775 776 777 778 779 780 781 782 783 784 785 786
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
787
func (s *stmt) bindInt64(pstmt uintptr, idx1 int, value int64) (err error) {
cznic's avatar
cznic committed
788 789 790 791
	var rc int32
	if _, err = s.FFI1(
		bindInt64,
		virtual.Int32Result{&rc},
792
		virtual.Ptr(pstmt), virtual.Int32(int32(idx1)), virtual.Int64(value),
cznic's avatar
cznic committed
793 794 795 796 797 798 799 800 801 802 803 804
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
805
func (s *stmt) bindBlob(pstmt uintptr, idx1 int, value []byte) (err error) {
cznic's avatar
cznic committed
806 807 808 809 810 811 812 813 814 815 816
	p, err := s.malloc(len(value))
	if err != nil {
		return err
	}

	s.allocs = append(s.allocs, p)
	virtual.CopyBytes(p, value, false)
	var rc int32
	if _, err = s.FFI1(
		bindBlob,
		virtual.Int32Result{&rc},
817
		virtual.Ptr(pstmt), virtual.Int32(int32(idx1)), virtual.Ptr(p), virtual.Int32(int32(len(value))), null,
cznic's avatar
cznic committed
818 819 820 821 822 823 824 825 826 827 828 829
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
830
func (s *stmt) bindText(pstmt uintptr, idx1 int, value string) (err error) {
cznic's avatar
cznic committed
831 832 833 834 835 836 837 838 839 840
	p, err := s.cString(value)
	if err != nil {
		return err
	}

	s.allocs = append(s.allocs, p)
	var rc int32
	if _, err = s.FFI1(
		bindText,
		virtual.Int32Result{&rc},
841
		virtual.Ptr(pstmt), virtual.Int32(int32(idx1)), virtual.Ptr(p), virtual.Int32(int32(len(value))), null,
cznic's avatar
cznic committed
842 843 844 845 846 847 848 849 850 851 852
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return s.errstr(rc)
	}

	return nil
}

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
func (s *stmt) bind(pstmt uintptr, n int, args []namedValue) error {
	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:])
			} else {
				return fmt.Errorf("missing argument with %d index", i)
			}
		}
cznic's avatar
cznic committed
885

886
		switch x := v.Value.(type) {
cznic's avatar
cznic committed
887
		case int64:
888
			if err := s.bindInt64(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
889 890 891
				return err
			}
		case float64:
892
			if err := s.bindDouble(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
893 894 895 896 897 898 899
				return err
			}
		case bool:
			v := 0
			if x {
				v = 1
			}
900
			if err := s.bindInt(pstmt, i, v); err != nil {
cznic's avatar
cznic committed
901 902 903
				return err
			}
		case []byte:
904
			if err := s.bindBlob(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
905 906 907
				return err
			}
		case string:
908
			if err := s.bindText(pstmt, i, x); err != nil {
cznic's avatar
cznic committed
909 910 911
				return err
			}
		case time.Time:
912
			if err := s.bindText(pstmt, i, x.String()); err != nil {
cznic's avatar
cznic committed
913 914 915 916 917 918 919 920 921 922
				return err
			}
		default:
			return fmt.Errorf("invalid driver.Value type %T", x)
		}
	}
	return nil
}

// int sqlite3_bind_parameter_count(sqlite3_stmt*);
923
func (s *stmt) bindParameterCount(pstmt uintptr) (_ int, err error) {
cznic's avatar
cznic committed
924 925 926 927
	var r int32
	_, err = s.FFI1(
		bindParameterCount,
		virtual.Int32Result{&r},
928
		virtual.Ptr(pstmt),
cznic's avatar
cznic committed
929 930 931 932
	)
	return int(r), err
}

933 934 935 936 937 938 939 940 941 942 943 944
// const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
func (s *stmt) bindParameterName(pstmt uintptr, i int) (string, error) {
	var p uintptr
	_, err := s.FFI1(
		bindParameterName,
		virtual.PtrResult{&p},
		virtual.Ptr(pstmt),
		virtual.Int32(i),
	)
	return virtual.GoString(p), err
}

cznic's avatar
cznic committed
945
// int sqlite3_finalize(sqlite3_stmt *pStmt);
946
func (s *stmt) finalize(pstmt uintptr) error {
cznic's avatar
cznic committed
947 948 949 950
	var rc int32
	if _, err := s.FFI1(
		finalize,
		virtual.Int32Result{&rc},
951
		virtual.Ptr(pstmt),
cznic's avatar
cznic committed
952 953 954 955 956 957 958 959 960 961 962 963
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return s.errstr(rc)
	}

	return nil
}

// int sqlite3_step(sqlite3_stmt*);
964
func (s *stmt) step(pstmt uintptr) (int, error) {
cznic's avatar
cznic committed
965 966 967 968
	var rc int32
	_, err := s.FFI1(
		step,
		virtual.Int32Result{&rc},
969
		virtual.Ptr(pstmt),
cznic's avatar
cznic committed
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
	)
	return int(rc), err
}

// 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 */
// );
func (s *stmt) prepareV2(zSql uintptr) error {
	var rc int32
	if _, err := s.FFI1(
		prepareV2,
		virtual.Int32Result{&rc},
986
		virtual.Ptr(s.pdb()), virtual.Ptr(zSql), virtual.Int32(-1), virtual.Ptr(s.ppstmt), virtual.Ptr(s.pzTail),
cznic's avatar
cznic committed
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return s.errstr(rc)
	}

	return nil
}

type tx struct {
	*conn
}

func (t *tx) String() string { return fmt.Sprintf("&%T@%p{conn: %p}", *t, t, t.conn) }

func newTx(c *conn) (*tx, error) {
	t := &tx{conn: c}
1006
	if err := t.exec(context.Background(), "begin"); err != nil {
cznic's avatar
cznic committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
		return nil, err
	}

	return t, nil
}

// Commit implements driver.Tx.
func (t *tx) Commit() (err error) {
	if trace {
		defer func() {
			tracer(t, "Commit(): %v", err)
		}()
	}
1020
	return t.exec(context.Background(), "commit")
cznic's avatar
cznic committed
1021 1022 1023 1024 1025 1026 1027 1028 1029
}

// Rollback implements driver.Tx.
func (t *tx) Rollback() (err error) {
	if trace {
		defer func() {
			tracer(t, "Rollback(): %v", err)
		}()
	}
1030
	return t.exec(context.Background(), "rollback")
cznic's avatar
cznic committed
1031 1032 1033 1034 1035 1036 1037 1038 1039
}

// 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 */
// );
1040
func (t *tx) exec(ctx context.Context, sql string) (err error) {
1041
	psql, err := t.cString(sql)
cznic's avatar
cznic committed
1042 1043 1044 1045
	if err != nil {
		return err
	}

1046
	defer t.free(psql)
cznic's avatar
cznic committed
1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
	// TODO: use t.conn.ExecContext() instead
	donech := make(chan struct{})
	defer close(donech)
	go func() {
		select {
		case <-ctx.Done():
			t.interrupt(t.pdb())
		case <-donech:
		}
	}()

cznic's avatar
cznic committed
1059 1060 1061 1062
	var rc int32
	if _, err = t.FFI1(
		exec,
		virtual.Int32Result{&rc},
1063
		virtual.Ptr(t.pdb()), virtual.Ptr(psql), null, null, null,
cznic's avatar
cznic committed
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return t.errstr(rc)
	}

	return nil
}

type conn struct {
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
1076
	*Driver
cznic's avatar
cznic committed
1077
	*virtual.Thread
1078
	ppdb uintptr
cznic's avatar
cznic committed
1079 1080 1081
}

func (c *conn) String() string {
Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
1082
	return fmt.Sprintf("&%T@%p{sqlite: %p, Thread: %p, ppdb: %#x}", *c, c, c.Driver, c.Thread, c.ppdb)
cznic's avatar
cznic committed
1083 1084
}

Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
1085 1086
func newConn(s *Driver, name string) (_ *conn, err error) {
	c := &conn{Driver: s}
cznic's avatar
cznic committed
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

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

	c.Lock()

	defer c.Unlock()

	c.conns++
	if c.conns == 1 {
		stderr := ioutil.Discard
		if trace {
			stderr = debugWriter{}
		}
		m, status, err2 := virtual.New(&binary, []string{"", fmt.Sprint(vmHeapSize - vmHeapReserve)}, nil, nil, stderr, vmHeapSize, vmMainStackSize, "")
		if status != 0 || err2 != nil {
			return nil, fmt.Errorf("virtual.New: %v, %v", status, err2)
		}

		vm = m
	}
	c.Thread, err = vm.NewThread(vmStackSize)
	if err != nil {
		return nil, err
	}

	if err = c.openV2(
		name,
		bin.XSQLITE_OPEN_READWRITE|bin.XSQLITE_OPEN_CREATE|
			bin.XSQLITE_OPEN_FULLMUTEX|
			bin.XSQLITE_OPEN_URI,
	); 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) {
1134 1135 1136 1137
	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
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	if trace {
		defer func() {
			tracer(c, "Prepare(%s): (%v, %v)", query, s, err)
		}()
	}
	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) {
	if trace {
		defer func() {
			tracer(c, "Close(): %v", err)
		}()
	}
	return c.close()
}

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
// 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
1173 1174
	if trace {
		defer func() {
1175
			tracer(c, "BeginTx(): (%v, %v)", t, err)
cznic's avatar
cznic committed
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
		}()
	}
	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.
1187 1188 1189 1190 1191
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) {
cznic's avatar
cznic committed
1192 1193
	if trace {
		defer func() {
1194
			tracer(c, "ExecContext(%s, %v): (%v, %v)", query, args, r, err)
cznic's avatar
cznic committed
1195 1196
		}()
	}
1197 1198

	s, err := c.PrepareContext(ctx, query)
cznic's avatar
cznic committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
	if err != nil {
		return nil, err
	}

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

1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
	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
1226 1227 1228 1229 1230 1231 1232 1233
}

// 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.
1234 1235 1236 1237 1238
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) {
cznic's avatar
cznic committed
1239 1240 1241 1242 1243
	if trace {
		defer func() {
			tracer(c, "Query(%s, %v): (%v, %v)", query, args, r, err)
		}()
	}
1244
	s, err := c.PrepareContext(ctx, query)
cznic's avatar
cznic committed
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
	if err != nil {
		return nil, err
	}

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

1255
	return s.(*stmt).query(ctx, args)
cznic's avatar
cznic committed
1256 1257
}

1258
func (c *conn) pdb() uintptr { return readPtr(c.ppdb) }
cznic's avatar
cznic committed
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268

// int sqlite3_extended_result_codes(sqlite3*, int onoff);
func (c *conn) extendedResultCodes(on bool) (err error) {
	var v, rc int32
	if on {
		v = 1
	}
	if _, err = c.FFI1(
		extendedResultCodes,
		virtual.Int32Result{&rc},
1269
		virtual.Ptr(c.pdb()), virtual.Int32(v),
cznic's avatar
cznic committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return c.errstr(rc)
	}

	return nil
}

// void *sqlite3_malloc(int);
func (c *conn) malloc(n int) (r uintptr, err error) {
	_, err = c.FFI1(
		maloc,
		virtual.PtrResult{&r},
		virtual.Int32(int32(n)),
	)
	return r, err
}

func (c *conn) cString(s string) (p uintptr, err error) {
	n := len(s)
	if p, err = c.malloc(n + 1); err != nil {
		return 0, err
	}

	virtual.CopyString(p, s, true)
	return p, nil
}

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

	defer c.free(filename)

1315
	ppdb, err := c.malloc(ptrSize)
cznic's avatar
cznic committed
1316 1317 1318 1319
	if err != nil {
		return err
	}

1320
	c.ppdb = ppdb
cznic's avatar
cznic committed
1321 1322 1323 1324
	var rc int32
	if _, err = c.FFI1(
		openV2,
		virtual.Int32Result{&rc},
1325
		virtual.Ptr(filename), virtual.Ptr(ppdb), virtual.Int32(flags), null,
cznic's avatar
cznic committed
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return c.errstr(rc)
	}

	return nil
}

// const char *sqlite3_errstr(int);
func (c *conn) errstr(rc int32) (err error) {
	var p uintptr
	if _, err = c.FFI1(
		errstr,
		virtual.PtrResult{&p},
		virtual.Int32(rc),
	); err != nil {
		return err
	}

	str := virtual.GoString(p)
	if _, err = c.FFI1(
		errmsg,
		virtual.PtrResult{&p},
1352
		virtual.Ptr(c.pdb()),
cznic's avatar
cznic committed
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
	); err != nil {
		return err
	}

	switch msg := virtual.GoString(p); {
	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) {
	var rc int32
	if _, err = c.FFI1(
		closeV2,
		virtual.Int32Result{&rc},
1371
		virtual.Ptr(c.pdb()),
cznic's avatar
cznic committed
1372 1373 1374 1375 1376 1377 1378 1379
	); err != nil {
		return err
	}

	if rc != bin.XSQLITE_OK {
		return c.errstr(rc)
	}

1380 1381
	err = c.free(c.ppdb)
	c.ppdb = 0
cznic's avatar
cznic committed
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
	return err
}

// void sqlite3_free(void*);
func (c *conn) free(p uintptr) (err error) {
	_, err = c.FFI0(
		free,
		virtual.Ptr(p),
	)
	return err
}

1394 1395 1396 1397 1398 1399 1400 1401 1402
// void sqlite3_interrupt(sqlite3*);
func (c *conn) interrupt(pdb uintptr) (err error) {
	_, err = c.FFI0(
		interrupt,
		virtual.Ptr(pdb),
	)
	return err
}

cznic's avatar
cznic committed
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
func (c *conn) close() (err error) {
	c.Lock()

	defer func() {
		c.conns--
		if c.conns == 0 {
			if err2 := vm.Close(); err2 != nil && err == nil {
				err = err2
			}
			vm = nil
		}
		c.Unlock()
	}()

1417
	if c.ppdb != 0 {
cznic's avatar
cznic committed
1418 1419 1420 1421 1422
		err = c.closeV2()
	}
	return err
}

Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
1423
type Driver struct {
cznic's avatar
cznic committed
1424 1425 1426 1427
	conns int
	sync.Mutex
}

Aliaksand Mianzhynski's avatar
Aliaksand Mianzhynski committed
1428
func newDrv() *Driver { return &Driver{} }
cznic's avatar
cznic committed
1429 1430 1431 1432 1433 1434 1435 1436 1437

// 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
1438
func (s *Driver) Open(name string) (c driver.Conn, err error) {
cznic's avatar
cznic committed
1439 1440 1441 1442 1443 1444 1445
	if trace {
		defer func() {
			tracer(s, "Open(%s): (%v, %v)", name, c, err)
		}()
	}
	return newConn(s, name)
}