This commit is contained in:
Yasuhiro Matsumoto 2016-11-07 16:16:47 +09:00
commit 51f43971ab
10 changed files with 386 additions and 126 deletions

View File

@ -19,10 +19,12 @@ import (
"unsafe" "unsafe"
) )
// SQLiteBackup implement interface of Backup.
type SQLiteBackup struct { type SQLiteBackup struct {
b *C.sqlite3_backup b *C.sqlite3_backup
} }
// Backup make backup from src to dest.
func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error) { func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error) {
destptr := C.CString(dest) destptr := C.CString(dest)
defer C.free(unsafe.Pointer(destptr)) defer C.free(unsafe.Pointer(destptr))
@ -37,10 +39,10 @@ func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteB
return nil, c.lastError() return nil, c.lastError()
} }
// Backs up for one step. Calls the underlying `sqlite3_backup_step` function. // Step to backs up for one step. Calls the underlying `sqlite3_backup_step`
// This function returns a boolean indicating if the backup is done and // function. This function returns a boolean indicating if the backup is done
// an error signalling any other error. Done is returned if the underlying C // and an error signalling any other error. Done is returned if the underlying
// function returns SQLITE_DONE (Code 101) // C function returns SQLITE_DONE (Code 101)
func (b *SQLiteBackup) Step(p int) (bool, error) { func (b *SQLiteBackup) Step(p int) (bool, error) {
ret := C.sqlite3_backup_step(b.b, C.int(p)) ret := C.sqlite3_backup_step(b.b, C.int(p))
if ret == C.SQLITE_DONE { if ret == C.SQLITE_DONE {
@ -51,18 +53,22 @@ func (b *SQLiteBackup) Step(p int) (bool, error) {
return false, nil return false, nil
} }
// Remaining return whether have the rest for backup.
func (b *SQLiteBackup) Remaining() int { func (b *SQLiteBackup) Remaining() int {
return int(C.sqlite3_backup_remaining(b.b)) return int(C.sqlite3_backup_remaining(b.b))
} }
// PageCount return count of pages.
func (b *SQLiteBackup) PageCount() int { func (b *SQLiteBackup) PageCount() int {
return int(C.sqlite3_backup_pagecount(b.b)) return int(C.sqlite3_backup_pagecount(b.b))
} }
// Finish close backup.
func (b *SQLiteBackup) Finish() error { func (b *SQLiteBackup) Finish() error {
return b.Close() return b.Close()
} }
// Close close backup.
func (b *SQLiteBackup) Close() error { func (b *SQLiteBackup) Close() error {
ret := C.sqlite3_backup_finish(b.b) ret := C.sqlite3_backup_finish(b.b)

View File

@ -7,12 +7,16 @@ package sqlite3
import "C" import "C"
// ErrNo inherit errno.
type ErrNo int type ErrNo int
// ErrNoMask is mask code.
const ErrNoMask C.int = 0xff const ErrNoMask C.int = 0xff
// ErrNoExtended is extended errno.
type ErrNoExtended int type ErrNoExtended int
// Error implement sqlite error code.
type Error struct { type Error struct {
Code ErrNo /* The error code returned by SQLite */ Code ErrNo /* The error code returned by SQLite */
ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */ ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */
@ -52,18 +56,22 @@ var (
ErrWarning = ErrNo(28) /* Warnings from sqlite3_log() */ ErrWarning = ErrNo(28) /* Warnings from sqlite3_log() */
) )
// Error return error message from errno.
func (err ErrNo) Error() string { func (err ErrNo) Error() string {
return Error{Code: err}.Error() return Error{Code: err}.Error()
} }
// Extend return extended errno.
func (err ErrNo) Extend(by int) ErrNoExtended { func (err ErrNo) Extend(by int) ErrNoExtended {
return ErrNoExtended(int(err) | (by << 8)) return ErrNoExtended(int(err) | (by << 8))
} }
// Error return error message that is extended code.
func (err ErrNoExtended) Error() string { func (err ErrNoExtended) Error() string {
return Error{Code: ErrNo(C.int(err) & ErrNoMask), ExtendedCode: err}.Error() return Error{Code: ErrNo(C.int(err) & ErrNoMask), ExtendedCode: err}.Error()
} }
// Error return error message.
func (err Error) Error() string { func (err Error) Error() string {
if err.err != "" { if err.err != "" {
return err.err return err.err
@ -121,7 +129,7 @@ var (
ErrConstraintTrigger = ErrConstraint.Extend(7) ErrConstraintTrigger = ErrConstraint.Extend(7)
ErrConstraintUnique = ErrConstraint.Extend(8) ErrConstraintUnique = ErrConstraint.Extend(8)
ErrConstraintVTab = ErrConstraint.Extend(9) ErrConstraintVTab = ErrConstraint.Extend(9)
ErrConstraintRowId = ErrConstraint.Extend(10) ErrConstraintRowID = ErrConstraint.Extend(10)
ErrNoticeRecoverWAL = ErrNotice.Extend(1) ErrNoticeRecoverWAL = ErrNotice.Extend(1)
ErrNoticeRecoverRollback = ErrNotice.Extend(2) ErrNoticeRecoverRollback = ErrNotice.Extend(2)
ErrWarningAutoIndex = ErrWarning.Extend(1) ErrWarningAutoIndex = ErrWarning.Extend(1)

View File

@ -114,12 +114,14 @@ import (
"strings" "strings"
"time" "time"
"unsafe" "unsafe"
"golang.org/x/net/context"
) )
// Timestamp formats understood by both this module and SQLite. // SQLiteTimestampFormats is timestamp formats understood by both this module
// The first format in the slice will be used when saving time values // and SQLite. The first format in the slice will be used when saving time
// into the database. When parsing a string from a timestamp or // values into the database. When parsing a string from a timestamp or datetime
// datetime column, the formats are tried in order. // column, the formats are tried in order.
var SQLiteTimestampFormats = []string{ var SQLiteTimestampFormats = []string{
// By default, store timestamps with whatever timezone they come with. // By default, store timestamps with whatever timezone they come with.
// When parsed, they will be returned with the same timezone. // When parsed, they will be returned with the same timezone.
@ -139,20 +141,20 @@ func init() {
} }
// Version returns SQLite library version information. // Version returns SQLite library version information.
func Version() (libVersion string, libVersionNumber int, sourceId string) { func Version() (libVersion string, libVersionNumber int, sourceID string) {
libVersion = C.GoString(C.sqlite3_libversion()) libVersion = C.GoString(C.sqlite3_libversion())
libVersionNumber = int(C.sqlite3_libversion_number()) libVersionNumber = int(C.sqlite3_libversion_number())
sourceId = C.GoString(C.sqlite3_sourceid()) sourceID = C.GoString(C.sqlite3_sourceid())
return libVersion, libVersionNumber, sourceId return libVersion, libVersionNumber, sourceID
} }
// Driver struct. // SQLiteDriver implement sql.Driver.
type SQLiteDriver struct { type SQLiteDriver struct {
Extensions []string Extensions []string
ConnectHook func(*SQLiteConn) error ConnectHook func(*SQLiteConn) error
} }
// Conn struct. // SQLiteConn implement sql.Conn.
type SQLiteConn struct { type SQLiteConn struct {
db *C.sqlite3 db *C.sqlite3
loc *time.Location loc *time.Location
@ -161,35 +163,34 @@ type SQLiteConn struct {
aggregators []*aggInfo aggregators []*aggInfo
} }
// Tx struct. // SQLiteTx implemen sql.Tx.
type SQLiteTx struct { type SQLiteTx struct {
c *SQLiteConn c *SQLiteConn
} }
// Stmt struct. // SQLiteStmt implement sql.Stmt.
type SQLiteStmt struct { type SQLiteStmt struct {
c *SQLiteConn c *SQLiteConn
s *C.sqlite3_stmt s *C.sqlite3_stmt
nv int
nn []string
t string t string
closed bool closed bool
cls bool cls bool
} }
// Result struct. // SQLiteResult implement sql.Result.
type SQLiteResult struct { type SQLiteResult struct {
id int64 id int64
changes int64 changes int64
} }
// Rows struct. // SQLiteRows implement sql.Rows.
type SQLiteRows struct { type SQLiteRows struct {
s *SQLiteStmt s *SQLiteStmt
nc int nc int
cols []string cols []string
decltype []string decltype []string
cls bool cls bool
done chan struct{}
} }
type functionInfo struct { type functionInfo struct {
@ -295,19 +296,19 @@ func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
// Commit transaction. // Commit transaction.
func (tx *SQLiteTx) Commit() error { func (tx *SQLiteTx) Commit() error {
_, err := tx.c.exec("COMMIT") _, err := tx.c.execQuery("COMMIT")
if err != nil && err.(Error).Code == C.SQLITE_BUSY { if err != nil && err.(Error).Code == C.SQLITE_BUSY {
// sqlite3 will leave the transaction open in this scenario. // sqlite3 will leave the transaction open in this scenario.
// However, database/sql considers the transaction complete once we // However, database/sql considers the transaction complete once we
// return from Commit() - we must clean up to honour its semantics. // return from Commit() - we must clean up to honour its semantics.
tx.c.exec("ROLLBACK") tx.c.execQuery("ROLLBACK")
} }
return err return err
} }
// Rollback transaction. // Rollback transaction.
func (tx *SQLiteTx) Rollback() error { func (tx *SQLiteTx) Rollback() error {
_, err := tx.c.exec("ROLLBACK") _, err := tx.c.execQuery("ROLLBACK")
return err return err
} }
@ -401,12 +402,24 @@ func (c *SQLiteConn) lastError() Error {
} }
} }
// Implements Execer // Exec implements Execer.
func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) { func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
if len(args) == 0 { if len(args) == 0 {
return c.exec(query) return c.execQuery(query)
} }
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return c.exec(context.Background(), query, list)
}
func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
start := 0
for { for {
s, err := c.Prepare(query) s, err := c.Prepare(query)
if err != nil { if err != nil {
@ -418,12 +431,16 @@ func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, err
if len(args) < na { if len(args) < na {
return nil, fmt.Errorf("Not enough args to execute query. Expected %d, got %d.", na, len(args)) return nil, fmt.Errorf("Not enough args to execute query. Expected %d, got %d.", na, len(args))
} }
res, err = s.Exec(args[:na]) for i := 0; i < na; i++ {
args[i].Ordinal -= start
}
res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
if err != nil && err != driver.ErrSkip { if err != nil && err != driver.ErrSkip {
s.Close() s.Close()
return nil, err return nil, err
} }
args = args[na:] args = args[na:]
start += na
} }
tail := s.(*SQLiteStmt).t tail := s.(*SQLiteStmt).t
s.Close() s.Close()
@ -434,8 +451,26 @@ func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, err
} }
} }
// Implements Queryer type namedValue struct {
Name string
Ordinal int
Value driver.Value
}
// Query implements Queryer.
func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) { func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return c.query(context.Background(), query, list)
}
func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
start := 0
for { for {
s, err := c.Prepare(query) s, err := c.Prepare(query)
if err != nil { if err != nil {
@ -446,12 +481,16 @@ func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, erro
if len(args) < na { if len(args) < na {
return nil, fmt.Errorf("Not enough args to execute query. Expected %d, got %d.", na, len(args)) return nil, fmt.Errorf("Not enough args to execute query. Expected %d, got %d.", na, len(args))
} }
rows, err := s.Query(args[:na]) for i := 0; i < na; i++ {
args[i].Ordinal -= start
}
rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
if err != nil && err != driver.ErrSkip { if err != nil && err != driver.ErrSkip {
s.Close() s.Close()
return nil, err return nil, err
} }
args = args[na:] args = args[na:]
start += na
tail := s.(*SQLiteStmt).t tail := s.(*SQLiteStmt).t
if tail == "" { if tail == "" {
return rows, nil return rows, nil
@ -462,7 +501,7 @@ func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, erro
} }
} }
func (c *SQLiteConn) exec(cmd string) (driver.Result, error) { func (c *SQLiteConn) execQuery(cmd string) (driver.Result, error) {
pcmd := C.CString(cmd) pcmd := C.CString(cmd)
defer C.free(unsafe.Pointer(pcmd)) defer C.free(unsafe.Pointer(pcmd))
@ -476,7 +515,11 @@ func (c *SQLiteConn) exec(cmd string) (driver.Result, error) {
// Begin transaction. // Begin transaction.
func (c *SQLiteConn) Begin() (driver.Tx, error) { func (c *SQLiteConn) Begin() (driver.Tx, error) {
if _, err := c.exec(c.txlock); err != nil { return c.begin(context.Background())
}
func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
if _, err := c.execQuery(c.txlock); err != nil {
return nil, err return nil, err
} }
return &SQLiteTx{c}, nil return &SQLiteTx{c}, nil
@ -507,7 +550,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
var loc *time.Location var loc *time.Location
txlock := "BEGIN" txlock := "BEGIN"
busy_timeout := 5000 busyTimeout := 5000
pos := strings.IndexRune(dsn, '?') pos := strings.IndexRune(dsn, '?')
if pos >= 1 { if pos >= 1 {
params, err := url.ParseQuery(dsn[pos+1:]) params, err := url.ParseQuery(dsn[pos+1:])
@ -533,7 +576,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err) return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
} }
busy_timeout = int(iv) busyTimeout = int(iv)
} }
// _txlock // _txlock
@ -570,7 +613,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
return nil, errors.New("sqlite succeeded without returning a database") return nil, errors.New("sqlite succeeded without returning a database")
} }
rv = C.sqlite3_busy_timeout(db, C.int(busy_timeout)) rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
if rv != C.SQLITE_OK { if rv != C.SQLITE_OK {
return nil, Error{Code: ErrNo(rv)} return nil, Error{Code: ErrNo(rv)}
} }
@ -606,6 +649,10 @@ func (c *SQLiteConn) Close() error {
// Prepare the query string. Return a new statement. // Prepare the query string. Return a new statement.
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) { func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
return c.prepare(context.Background(), query)
}
func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
pquery := C.CString(query) pquery := C.CString(query)
defer C.free(unsafe.Pointer(pquery)) defer C.free(unsafe.Pointer(pquery))
var s *C.sqlite3_stmt var s *C.sqlite3_stmt
@ -618,15 +665,7 @@ func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
if tail != nil && *tail != '\000' { if tail != nil && *tail != '\000' {
t = strings.TrimSpace(C.GoString(tail)) t = strings.TrimSpace(C.GoString(tail))
} }
nv := int(C.sqlite3_bind_parameter_count(s)) ss := &SQLiteStmt{c: c, s: s, t: t}
var nn []string
for i := 0; i < nv; i++ {
pn := C.GoString(C.sqlite3_bind_parameter_name(s, C.int(i+1)))
if len(pn) > 1 && pn[0] == '$' && 48 <= pn[1] && pn[1] <= 57 {
nn = append(nn, C.GoString(C.sqlite3_bind_parameter_name(s, C.int(i+1))))
}
}
ss := &SQLiteStmt{c: c, s: s, nv: nv, nn: nn, t: t}
runtime.SetFinalizer(ss, (*SQLiteStmt).Close) runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
return ss, nil return ss, nil
} }
@ -648,9 +687,9 @@ func (s *SQLiteStmt) Close() error {
return nil return nil
} }
// Return a number of parameters. // NumInput return a number of parameters.
func (s *SQLiteStmt) NumInput() int { func (s *SQLiteStmt) NumInput() int {
return s.nv return int(C.sqlite3_bind_parameter_count(s.s))
} }
type bindArg struct { type bindArg struct {
@ -658,31 +697,23 @@ type bindArg struct {
v driver.Value v driver.Value
} }
func (s *SQLiteStmt) bind(args []driver.Value) error { func (s *SQLiteStmt) bind(args []namedValue) error {
rv := C.sqlite3_reset(s.s) rv := C.sqlite3_reset(s.s)
if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE { if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
return s.c.lastError() return s.c.lastError()
} }
var vargs []bindArg
narg := len(args)
vargs = make([]bindArg, narg)
if len(s.nn) > 0 {
for i, v := range s.nn {
if pi, err := strconv.Atoi(v[1:]); err == nil {
vargs[i] = bindArg{pi, args[i]}
}
}
} else {
for i, v := range args { for i, v := range args {
vargs[i] = bindArg{i + 1, v} if v.Name != "" {
cname := C.CString(v.Name)
args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
C.free(unsafe.Pointer(cname))
} }
} }
for _, varg := range vargs { for _, arg := range args {
n := C.int(varg.n) n := C.int(arg.Ordinal)
v := varg.v switch v := arg.Value.(type) {
switch v := v.(type) {
case nil: case nil:
rv = C.sqlite3_bind_null(s.s, n) rv = C.sqlite3_bind_null(s.s, n)
case string: case string:
@ -722,29 +753,81 @@ func (s *SQLiteStmt) bind(args []driver.Value) error {
// Query the statement with arguments. Return records. // Query the statement with arguments. Return records.
func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) { func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return s.query(context.Background(), list)
}
func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
if err := s.bind(args); err != nil { if err := s.bind(args); err != nil {
return nil, err return nil, err
} }
return &SQLiteRows{s, int(C.sqlite3_column_count(s.s)), nil, nil, s.cls}, nil
rows := &SQLiteRows{
s: s,
nc: int(C.sqlite3_column_count(s.s)),
cols: nil,
decltype: nil,
cls: s.cls,
done: make(chan struct{}),
}
go func() {
select {
case <-ctx.Done():
C.sqlite3_interrupt(s.c.db)
rows.Close()
case <-rows.done:
}
}()
return rows, nil
} }
// Return last inserted ID. // LastInsertId teturn last inserted ID.
func (r *SQLiteResult) LastInsertId() (int64, error) { func (r *SQLiteResult) LastInsertId() (int64, error) {
return r.id, nil return r.id, nil
} }
// Return how many rows affected. // RowsAffected return how many rows affected.
func (r *SQLiteResult) RowsAffected() (int64, error) { func (r *SQLiteResult) RowsAffected() (int64, error) {
return r.changes, nil return r.changes, nil
} }
// Execute the statement with arguments. Return result object. // Exec execute the statement with arguments. Return result object.
func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) { func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return s.exec(context.Background(), list)
}
func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
if err := s.bind(args); err != nil { if err := s.bind(args); err != nil {
C.sqlite3_reset(s.s) C.sqlite3_reset(s.s)
C.sqlite3_clear_bindings(s.s) C.sqlite3_clear_bindings(s.s)
return nil, err return nil, err
} }
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
C.sqlite3_interrupt(s.c.db)
case <-done:
}
}()
var rowid, changes C.longlong var rowid, changes C.longlong
rv := C._sqlite3_step(s.s, &rowid, &changes) rv := C._sqlite3_step(s.s, &rowid, &changes)
if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE { if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
@ -753,6 +836,7 @@ func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
C.sqlite3_clear_bindings(s.s) C.sqlite3_clear_bindings(s.s)
return nil, err return nil, err
} }
return &SQLiteResult{int64(rowid), int64(changes)}, nil return &SQLiteResult{int64(rowid), int64(changes)}, nil
} }
@ -761,6 +845,10 @@ func (rc *SQLiteRows) Close() error {
if rc.s.closed { if rc.s.closed {
return nil return nil
} }
if rc.done != nil {
close(rc.done)
rc.done = nil
}
if rc.cls { if rc.cls {
return rc.s.Close() return rc.s.Close()
} }
@ -771,7 +859,7 @@ func (rc *SQLiteRows) Close() error {
return nil return nil
} }
// Return column names. // Columns return column names.
func (rc *SQLiteRows) Columns() []string { func (rc *SQLiteRows) Columns() []string {
if rc.nc != len(rc.cols) { if rc.nc != len(rc.cols) {
rc.cols = make([]string, rc.nc) rc.cols = make([]string, rc.nc)
@ -782,7 +870,7 @@ func (rc *SQLiteRows) Columns() []string {
return rc.cols return rc.cols
} }
// Return column types. // DeclTypes return column types.
func (rc *SQLiteRows) DeclTypes() []string { func (rc *SQLiteRows) DeclTypes() []string {
if rc.decltype == nil { if rc.decltype == nil {
rc.decltype = make([]string, rc.nc) rc.decltype = make([]string, rc.nc)
@ -793,7 +881,7 @@ func (rc *SQLiteRows) DeclTypes() []string {
return rc.decltype return rc.decltype
} }
// Move cursor to next. // Next move cursor to next.
func (rc *SQLiteRows) Next(dest []driver.Value) error { func (rc *SQLiteRows) Next(dest []driver.Value) error {
rv := C.sqlite3_step(rc.s.s) rv := C.sqlite3_step(rc.s.s)
if rv == C.SQLITE_DONE { if rv == C.SQLITE_DONE {

69
sqlite3_go18.go Normal file
View File

@ -0,0 +1,69 @@
// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build go1.8
package sqlite3
import (
"database/sql/driver"
"errors"
"context"
)
// Ping implement Pinger.
func (c *SQLiteConn) Ping(ctx context.Context) error {
if c.db == nil {
return errors.New("Connection was closed")
}
return nil
}
// QueryContext implement QueryerContext.
func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return c.query(ctx, query, list)
}
// ExecContext implement ExecerContext.
func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return c.exec(ctx, query, list)
}
// PrepareContext implement ConnPrepareContext.
func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
return c.prepare(ctx, query)
}
// BeginContext implement ConnBeginContext.
func (c *SQLiteConn) BeginContext(ctx context.Context) (driver.Tx, error) {
return c.begin(ctx)
}
// QueryContext implement QueryerContext.
func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return s.query(ctx, list)
}
// ExecContext implement ExecerContext.
func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, nv := range args {
list[i] = namedValue(nv)
}
return s.exec(ctx, list)
}

50
sqlite3_go18_test.go Normal file
View File

@ -0,0 +1,50 @@
// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build go1.8
package sqlite3
import (
"database/sql"
"os"
"testing"
)
func TestNamedParams(t *testing.T) {
tempFilename := TempFilename(t)
defer os.Remove(tempFilename)
db, err := sql.Open("sqlite3", tempFilename)
if err != nil {
t.Fatal("Failed to open database:", err)
}
defer db.Close()
_, err = db.Exec(`
create table foo (id integer, name text, extra text);
`)
if err != nil {
t.Error("Failed to call db.Query:", err)
}
_, err = db.Exec(`insert into foo(id, name, extra) values(:id, :name, :name)`, sql.Param(":name", "foo"), sql.Param(":id", 1))
if err != nil {
t.Error("Failed to call db.Exec:", err)
}
row := db.QueryRow(`select id, extra from foo where id = :id and extra = :extra`, sql.Param(":id", 1), sql.Param(":extra", "foo"))
if row == nil {
t.Error("Failed to call db.QueryRow")
}
var id int
var extra string
err = row.Scan(&id, &extra)
if err != nil {
t.Error("Failed to db.Scan:", err)
}
if id != 1 || extra != "foo" {
t.Error("Failed to db.QueryRow: not matched results")
}
}

View File

@ -42,6 +42,7 @@ func (c *SQLiteConn) loadExtensions(extensions []string) error {
return nil return nil
} }
// LoadExtension load the sqlite3 extension.
func (c *SQLiteConn) LoadExtension(lib string, entry string) error { func (c *SQLiteConn) LoadExtension(lib string, entry string) error {
rv := C.sqlite3_enable_load_extension(c.db, 1) rv := C.sqlite3_enable_load_extension(c.db, 1)
if rv != C.SQLITE_OK { if rv != C.SQLITE_OK {

View File

@ -207,12 +207,12 @@ func TestUpdate(t *testing.T) {
if err != nil { if err != nil {
t.Fatal("Failed to update record:", err) t.Fatal("Failed to update record:", err)
} }
lastId, err := res.LastInsertId() lastID, err := res.LastInsertId()
if err != nil { if err != nil {
t.Fatal("Failed to get LastInsertId:", err) t.Fatal("Failed to get LastInsertId:", err)
} }
if expected != lastId { if expected != lastID {
t.Errorf("Expected %q for last Id, but %q:", expected, lastId) t.Errorf("Expected %q for last Id, but %q:", expected, lastID)
} }
affected, _ = res.RowsAffected() affected, _ = res.RowsAffected()
if err != nil { if err != nil {
@ -272,12 +272,12 @@ func TestDelete(t *testing.T) {
if err != nil { if err != nil {
t.Fatal("Failed to delete record:", err) t.Fatal("Failed to delete record:", err)
} }
lastId, err := res.LastInsertId() lastID, err := res.LastInsertId()
if err != nil { if err != nil {
t.Fatal("Failed to get LastInsertId:", err) t.Fatal("Failed to get LastInsertId:", err)
} }
if expected != lastId { if expected != lastID {
t.Errorf("Expected %q for last Id, but %q:", expected, lastId) t.Errorf("Expected %q for last Id, but %q:", expected, lastID)
} }
affected, err = res.RowsAffected() affected, err = res.RowsAffected()
if err != nil { if err != nil {
@ -993,42 +993,6 @@ func TestVersion(t *testing.T) {
} }
} }
func TestNumberNamedParams(t *testing.T) {
tempFilename := TempFilename(t)
defer os.Remove(tempFilename)
db, err := sql.Open("sqlite3", tempFilename)
if err != nil {
t.Fatal("Failed to open database:", err)
}
defer db.Close()
_, err = db.Exec(`
create table foo (id integer, name text, extra text);
`)
if err != nil {
t.Error("Failed to call db.Query:", err)
}
_, err = db.Exec(`insert into foo(id, name, extra) values($1, $2, $2)`, 1, "foo")
if err != nil {
t.Error("Failed to call db.Exec:", err)
}
row := db.QueryRow(`select id, extra from foo where id = $1 and extra = $2`, 1, "foo")
if row == nil {
t.Error("Failed to call db.QueryRow")
}
var id int
var extra string
err = row.Scan(&id, &extra)
if err != nil {
t.Error("Failed to db.Scan:", err)
}
if id != 1 || extra != "foo" {
t.Error("Failed to db.QueryRow: not matched results")
}
}
func TestStringContainingZero(t *testing.T) { func TestStringContainingZero(t *testing.T) {
tempFilename := TempFilename(t) tempFilename := TempFilename(t)
defer os.Remove(tempFilename) defer os.Remove(tempFilename)
@ -1106,12 +1070,12 @@ func TestDateTimeNow(t *testing.T) {
} }
func TestFunctionRegistration(t *testing.T) { func TestFunctionRegistration(t *testing.T) {
addi_8_16_32 := func(a int8, b int16) int32 { return int32(a) + int32(b) } addi8_16_32 := func(a int8, b int16) int32 { return int32(a) + int32(b) }
addi_64 := func(a, b int64) int64 { return a + b } addi64 := func(a, b int64) int64 { return a + b }
addu_8_16_32 := func(a uint8, b uint16) uint32 { return uint32(a) + uint32(b) } addu8_16_32 := func(a uint8, b uint16) uint32 { return uint32(a) + uint32(b) }
addu_64 := func(a, b uint64) uint64 { return a + b } addu64 := func(a, b uint64) uint64 { return a + b }
addiu := func(a int, b uint) int64 { return int64(a) + int64(b) } addiu := func(a int, b uint) int64 { return int64(a) + int64(b) }
addf_32_64 := func(a float32, b float64) float64 { return float64(a) + b } addf32_64 := func(a float32, b float64) float64 { return float64(a) + b }
not := func(a bool) bool { return !a } not := func(a bool) bool { return !a }
regex := func(re, s string) (bool, error) { regex := func(re, s string) (bool, error) {
return regexp.MatchString(re, s) return regexp.MatchString(re, s)
@ -1143,22 +1107,22 @@ func TestFunctionRegistration(t *testing.T) {
sql.Register("sqlite3_FunctionRegistration", &SQLiteDriver{ sql.Register("sqlite3_FunctionRegistration", &SQLiteDriver{
ConnectHook: func(conn *SQLiteConn) error { ConnectHook: func(conn *SQLiteConn) error {
if err := conn.RegisterFunc("addi_8_16_32", addi_8_16_32, true); err != nil { if err := conn.RegisterFunc("addi8_16_32", addi8_16_32, true); err != nil {
return err return err
} }
if err := conn.RegisterFunc("addi_64", addi_64, true); err != nil { if err := conn.RegisterFunc("addi64", addi64, true); err != nil {
return err return err
} }
if err := conn.RegisterFunc("addu_8_16_32", addu_8_16_32, true); err != nil { if err := conn.RegisterFunc("addu8_16_32", addu8_16_32, true); err != nil {
return err return err
} }
if err := conn.RegisterFunc("addu_64", addu_64, true); err != nil { if err := conn.RegisterFunc("addu64", addu64, true); err != nil {
return err return err
} }
if err := conn.RegisterFunc("addiu", addiu, true); err != nil { if err := conn.RegisterFunc("addiu", addiu, true); err != nil {
return err return err
} }
if err := conn.RegisterFunc("addf_32_64", addf_32_64, true); err != nil { if err := conn.RegisterFunc("addf32_64", addf32_64, true); err != nil {
return err return err
} }
if err := conn.RegisterFunc("not", not, true); err != nil { if err := conn.RegisterFunc("not", not, true); err != nil {
@ -1189,12 +1153,12 @@ func TestFunctionRegistration(t *testing.T) {
query string query string
expected interface{} expected interface{}
}{ }{
{"SELECT addi_8_16_32(1,2)", int32(3)}, {"SELECT addi8_16_32(1,2)", int32(3)},
{"SELECT addi_64(1,2)", int64(3)}, {"SELECT addi64(1,2)", int64(3)},
{"SELECT addu_8_16_32(1,2)", uint32(3)}, {"SELECT addu8_16_32(1,2)", uint32(3)},
{"SELECT addu_64(1,2)", uint64(3)}, {"SELECT addu64(1,2)", uint64(3)},
{"SELECT addiu(1,2)", int64(3)}, {"SELECT addiu(1,2)", int64(3)},
{"SELECT addf_32_64(1.5,1.5)", float64(3)}, {"SELECT addf32_64(1.5,1.5)", float64(3)},
{"SELECT not(1)", false}, {"SELECT not(1)", false},
{"SELECT not(0)", true}, {"SELECT not(0)", true},
{`SELECT regex("^foo.*", "foobar")`, true}, {`SELECT regex("^foo.*", "foobar")`, true},
@ -1315,6 +1279,22 @@ func TestDeclTypes(t *testing.T) {
} }
} }
func TestPinger(t *testing.T) {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatal(err)
}
err = db.Ping()
if err != nil {
t.Fatal(err)
}
db.Close()
err = db.Ping()
if err == nil {
t.Fatal("Should be closed")
}
}
var customFunctionOnce sync.Once var customFunctionOnce sync.Once
func BenchmarkCustomFunctions(b *testing.B) { func BenchmarkCustomFunctions(b *testing.B) {

57
sqlite3_type.go Normal file
View File

@ -0,0 +1,57 @@
package sqlite3
/*
#ifndef USE_LIBSQLITE3
#include <sqlite3-binding.h>
#else
#include <sqlite3.h>
#endif
*/
import "C"
import (
"reflect"
"time"
)
// ColumnTypeDatabaseTypeName implement RowsColumnTypeDatabaseTypeName.
func (rc *SQLiteRows) ColumnTypeDatabaseTypeName(i int) string {
return C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i)))
}
/*
func (rc *SQLiteRows) ColumnTypeLength(index int) (length int64, ok bool) {
return 0, false
}
func (rc *SQLiteRows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
return 0, 0, false
}
*/
// ColumnTypeNullable implement RowsColumnTypeNullable.
func (rc *SQLiteRows) ColumnTypeNullable(i int) (nullable, ok bool) {
return true, true
}
// ColumnTypeScanType implement RowsColumnTypeScanType.
func (rc *SQLiteRows) ColumnTypeScanType(i int) reflect.Type {
switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
case C.SQLITE_INTEGER:
switch C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))) {
case "timestamp", "datetime", "date":
return reflect.TypeOf(time.Time{})
case "boolean":
return reflect.TypeOf(false)
}
return reflect.TypeOf(int64(0))
case C.SQLITE_FLOAT:
return reflect.TypeOf(float64(0))
case C.SQLITE_BLOB:
return reflect.SliceOf(reflect.TypeOf(byte(0)))
case C.SQLITE_NULL:
return reflect.TypeOf(nil)
case C.SQLITE_TEXT:
return reflect.TypeOf("")
}
return reflect.SliceOf(reflect.TypeOf(byte(0)))
}

View File

@ -4,6 +4,7 @@ package sqlite3
import "errors" import "errors"
// RegisterAggregator register the aggregator.
func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error { func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error {
return errors.New("This feature is not implemented") return errors.New("This feature is not implemented")
} }