sqlite

package module
v0.0.0-...-12c801b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2019 License: BSD-3-Clause Imports: 20 Imported by: 0

README

GoDoc Build Status Go Report Card

Yet another SQLite binding based on:

There are two layers:

  • one matching the SQLite API (with Backup, Blob, user-defined Function/Module, ...).
  • and another implementing the "database/sql/driver" interface.

Caveat

With Go 1.6, some features do not work anymore without GODEBUG=cgocheck=0 (see Cgo major change). It seems that the solution is a global variable/lock (see here). "I would prefer not to" do this.

Custom build

If your OS does not bundle SQLite3 development files (or old ones):

  • download and copy SQLite3 files
$ cp ~/Downloads/sqlite-amalgamation-xxx/sqlite3.{c,h} $GOPATH/src/github.com/gwenn/gosqlite
  • patch sqlite.go file
-#cgo linux freebsd pkg-config: sqlite3
-#cgo !linux,!freebsd LDFLAGS: -lsqlite3
+#cgo CFLAGS: -I.
+#cgo CFLAGS: -DSQLITE_ENABLE_COLUMN_METADATA=1

Features (not supported by database/sql/driver):

  • Named bind parameters.
  • Partial scan: scan values may be partially scanned (by index or name) or skipped/ignored by passing nil pointer(s).
  • Null value: by default, empty string and zero time are bound to NULL for prepared statement's parameters (no need for NullString, NullTime but still supported).
  • Null value: Stmt.Scan methods return default Go zero value (0, "", ...) for SQL NULL (no need for NullInt64, NullString, NullTime but still supported).
  • Correctly retrieve the time returns by select current_timestamp statement or others expressions: in SQLite, expression affinity is NONE.
  • Full control over connection pool
  • No restrictive converter
  • Support for metadata
  • Nested transaction support

Changes:

Open supports flags.
Conn.Exec handles multiple statements (separated by semicolons) properly.
Conn.Prepare can optionally bind as well.
Conn.Prepare can reuse already prepared Stmt.
Conn.Close ensures that all dangling statements are finalized.
Stmt.Exec is renamed in Stmt.Bind and a new Stmt.Exec method is introduced to bind and step.
Stmt.Bind uses native sqlite3_bind_x methods and failed if unsupported type.
Stmt.NamedBind can be used to bind by name.
Stmt.Next returns a (bool, os.Error) couple like Reader.Read.
Stmt.Scan uses native sqlite3_column_x methods.
Stmt.NamedScan is added. It's compliant with go-dbi.
Stmt.ScanByIndex/ScanByName are added to test NULL value.

Currently, the weak point of the binding is the Scan methods: The original implementation is using this strategy:

  • convert the stored value to a []byte by calling sqlite3_column_blob,
  • convert the bytes to the desired Go type with correct feedback in case of illegal conversion,
  • but apparently no support for NULL value.

Using the native sqlite3_column_x implies:

  • optimal conversion from the storage type to Go type (when they match),
  • lossy conversion when types mismatch (select cast('M' as int); --> 0),
  • NULL value can be returned only for **type, otherwise a default value (0, false, "") is returned.

SQLite logs (SQLITE_CONFIG_LOG) can be activated by:

  • ConfigLog function
  • or export SQLITE_LOG=1

Similar projects created after Jul 17, 2011:

https://github.com/mattn/go-sqlite3 (Nov 11, 2011)
https://github.com/mxk/go-sqlite (Feb 12, 2013)
https://github.com/crawshaw/sqlite (Mar 28, 2018)

Additions:

Conn.Exists
Conn.OneValue

Conn.OpenVfs
Conn.EnableFkey/IsFKeyEnabled
Conn.Changes/TotalChanges
Conn.LastInsertRowid
Conn.Interrupt
Conn.Begin/BeginTransaction(type)/Commit/Rollback
Conn.GetAutocommit
Conn.EnableLoadExtension/LoadExtension
Conn.IntegrityCheck

Stmt.Insert/ExecDml/Select/SelectOneRow
Stmt.BindParameterCount/BindParameterIndex(name)/BindParameterName(index)
Stmt.ClearBindings
Stmt.ColumnCount/ColumnNames/ColumnIndex(name)/ColumnName(index)/ColumnType(index)
Stmt.ReadOnly
Stmt.Busy

Blob:
ZeroBlobLength
Conn.NewBlobReader
Conn.NewBlobReadWriter

Meta:
Conn.Databases
Conn.Tables/Views/Indexes
Conn.Columns
Conn.ForeignKeys
Conn.TableIndexes/IndexColumns

Time:
JulianDay
JulianDayToUTC
JulianDayToLocalTime
UnixTime, JulianTime and TimeStamp used to persist go time in formats supported by SQLite3 date functions.

Trace:
Conn.BusyHandler
Conn.Profile
Conn.ProgressHandler
Conn.SetAuthorizer
Conn.Trace
Stmt.Status

Hook:
Conn.CommitHook
Conn.RollbackHook
Conn.UpdateHook

Function:
Conn.CreateScalarFunction
Conn.CreateAggregateFunction

Virtual Table (partial support):
Conn.CreateModule
Conn.DeclareVTab

GC:

Although Go is gced, there is no destructor (see http://www.airs.com/blog/archives/362).
In the gosqlite wrapper, no finalizer is used.
So users must ensure that C resources (database connections, prepared statements, BLOBs, Backups) are destroyed/deallocated by calling Conn.Close, Stmt.Finalize, BlobReader.Close, Backup.Close.

Therefore, sqlite3_close/sqlite3_next_stmt are used by Conn.Close to free the database connection and all dangling statements (not sqlite3_close_v2) (see http://sqlite.org/c3ref/close.html).

Benchmarks:

$ go test -bench . -benchmem

BenchmarkValuesScan	  500000	      6265 ns/op	      74 B/op	       3 allocs/op
BenchmarkScan	  500000	      4994 ns/op	      41 B/op	       4 allocs/op
BenchmarkNamedScan	  500000	      4960 ns/op	      93 B/op	       7 allocs/op

BenchmarkInsert	  500000	      4085 ns/op	      16 B/op	       1 allocs/op
BenchmarkNamedInsert	  500000	      4798 ns/op	      64 B/op	       4 allocs/op

BenchmarkDisabledCache	  100000	     19841 ns/op	     117 B/op	       3 allocs/op
BenchmarkEnabledCache	 2000000	       790 ns/op	      50 B/op	       1 allocs/op

BenchmarkLike	 1000000	      2605 ns/op	       0 B/op	       0 allocs/op
BenchmarkHalf	  500000	      4988 ns/op	      33 B/op	       1 allocs/op
BenchmarkRegexp	  500000	      5557 ns/op	       8 B/op	       1 allocs/op

Documentation

Overview

Package sqlite provides access to the SQLite library, version 3.

Example
db, err := sqlite.Open(":memory:") // path to db or "" for temp db
check(err)
defer db.Close()
err = db.Exec("CREATE TABLE test(id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL UNIQUE); -- ... and other ddls separated by semi-colon")
check(err)
ins, err := db.Prepare("INSERT INTO test (name) VALUES (?)")
check(err)
defer ins.Finalize()
_, err = ins.Insert("gosqlite driver")
check(err)
var name string
err = db.Select("SELECT name FROM test WHERE name LIKE ?", func(s *sqlite.Stmt) (err error) {
	if err = s.Scan(&name); err != nil {
		return
	}
	fmt.Println(name)
	return
}, "%go%")
check(err)
Output:

gosqlite driver

Index

Examples

Constants

View Source
const (
	Integral  = Affinity("INTEGER") // Integer affinity
	Real      = Affinity("REAL")
	Numerical = Affinity("NUMERIC")
	None      = Affinity("NONE")
	Textual   = Affinity("TEXT")
)

SQLite column type affinities

View Source
const (
	ErrError      = Errno(C.SQLITE_ERROR)      /* SQL error or missing database */
	ErrInternal   = Errno(C.SQLITE_INTERNAL)   /* Internal logic error in SQLite */
	ErrPerm       = Errno(C.SQLITE_PERM)       /* Access permission denied */
	ErrAbort      = Errno(C.SQLITE_ABORT)      /* Callback routine requested an abort */
	ErrBusy       = Errno(C.SQLITE_BUSY)       /* The database file is locked */
	ErrLocked     = Errno(C.SQLITE_LOCKED)     /* A table in the database is locked */
	ErrNoMem      = Errno(C.SQLITE_NOMEM)      /* A malloc() failed */
	ErrReadOnly   = Errno(C.SQLITE_READONLY)   /* Attempt to write a readonly database */
	ErrInterrupt  = Errno(C.SQLITE_INTERRUPT)  /* Operation terminated by sqlite3_interrupt()*/
	ErrIOErr      = Errno(C.SQLITE_IOERR)      /* Some kind of disk I/O error occurred */
	ErrCorrupt    = Errno(C.SQLITE_CORRUPT)    /* The database disk image is malformed */
	ErrNotFound   = Errno(C.SQLITE_NOTFOUND)   /* Unknown opcode in sqlite3_file_control() */
	ErrFull       = Errno(C.SQLITE_FULL)       /* Insertion failed because database is full */
	ErrCantOpen   = Errno(C.SQLITE_CANTOPEN)   /* Unable to open the database file */
	ErrProtocol   = Errno(C.SQLITE_PROTOCOL)   /* Database lock protocol error */
	ErrEmpty      = Errno(C.SQLITE_EMPTY)      /* Database is empty */
	ErrSchema     = Errno(C.SQLITE_SCHEMA)     /* The database schema changed */
	ErrTooBig     = Errno(C.SQLITE_TOOBIG)     /* String or BLOB exceeds size limit */
	ErrConstraint = Errno(C.SQLITE_CONSTRAINT) /* Abort due to constraint violation */
	ErrMismatch   = Errno(C.SQLITE_MISMATCH)   /* Data type mismatch */
	ErrMisuse     = Errno(C.SQLITE_MISUSE)     /* Library used incorrectly */
	ErrNolfs      = Errno(C.SQLITE_NOLFS)      /* Uses OS features not supported on host */
	ErrAuth       = Errno(C.SQLITE_AUTH)       /* Authorization denied */
	ErrFormat     = Errno(C.SQLITE_FORMAT)     /* Auxiliary database format error */
	ErrRange      = Errno(C.SQLITE_RANGE)      /* 2nd parameter to sqlite3_bind out of range */
	ErrNotDB      = Errno(C.SQLITE_NOTADB)     /* File opened that is not a database file */

	Row         = Errno(C.SQLITE_ROW)  /* sqlite3_step() has another row ready */
	Done        = Errno(C.SQLITE_DONE) /* sqlite3_step() has finished executing */
	ErrSpecific = Errno(-1)            /* Wrapper specific error */
)

SQLite result codes

View Source
const (
	Integer = Type(C.SQLITE_INTEGER)
	Float   = Type(C.SQLITE_FLOAT)
	Blob    = Type(C.SQLITE_BLOB)
	Null    = Type(C.SQLITE_NULL)
	Text    = Type(C.SQLITE3_TEXT)
)

SQLite fundamental datatypes

Variables

View Source
var CheckTypeMismatch = true

CheckTypeMismatch enables type check in Scan methods (default true)

View Source
var NullIfEmptyString = true

NullIfEmptyString transforms empty string to null when true (true by default)

View Source
var NullIfZeroTime = true

NullIfZeroTime transforms zero time (time.Time.IsZero) to null when true (true by default)

Functions

func CompileOptionUsed

func CompileOptionUsed(optName string) bool

CompileOptionUsed returns false or true indicating whether the specified option was defined at compile time. (See http://sqlite.org/c3ref/compileoption_get.html)

func Complete

func Complete(sql string) (bool, error)

Complete determines if an SQL statement is complete. (See http://sqlite.org/c3ref/complete.html)

func ConfigLog

func ConfigLog(f Logger, udp interface{}) error

ConfigLog configures the logger of the SQLite library. Only one logger can be registered at a time for the whole program. The logger must be threadsafe. Cannot be used with Go >= 1.6 and cgocheck enabled when udp is not nil. (See sqlite3_config(SQLITE_CONFIG_LOG,...): http://sqlite.org/c3ref/config.html and http://www.sqlite.org/errlog.html)

func ConfigMemStatus

func ConfigMemStatus(b bool) error

ConfigMemStatus enables or disables the collection of memory allocation statistics. (See sqlite3_config(SQLITE_CONFIG_MEMSTATUS): http://sqlite.org/c3ref/config.html)

func ConfigThreadingMode

func ConfigThreadingMode(mode ThreadingMode) error

ConfigThreadingMode alters threading mode. (See sqlite3_config(SQLITE_CONFIG_SINGLETHREAD|SQLITE_CONFIG_MULTITHREAD|SQLITE_CONFIG_SERIALIZED): http://sqlite.org/c3ref/config.html)

func ConfigURI

func ConfigURI(b bool) error

ConfigURI enables or disables URI handling. (See sqlite3_config(SQLITE_CONFIG_URI): http://sqlite.org/c3ref/config.html)

func EnableSharedCache

func EnableSharedCache(b bool) error

EnableSharedCache enables or disables shared pager cache (See http://sqlite.org/c3ref/enable_shared_cache.html)

func JulianDay

func JulianDay(t time.Time) float64

JulianDay converts a Time into a julian day number.

func JulianDayToLocalTime

func JulianDayToLocalTime(jd float64) time.Time

JulianDayToLocalTime transforms a julian day number into a local Time.

func JulianDayToUTC

func JulianDayToUTC(jd float64) time.Time

JulianDayToUTC transforms a julian day number into an UTC Time.

func LoadCsvModule

func LoadCsvModule(db *Conn) error

LoadCsvModule loads CSV virtual table module.

CREATE VIRTUAL TABLE vtab USING csv('test.csv', USE_HEADER_ROW, NO_QUOTE)

func Log

func Log(err int32, msg string)

Log writes a message into the error log established by ConfigLog method. (See http://sqlite.org/c3ref/log.html and http://www.sqlite.org/errlog.html)

Applications can use the sqlite3_log(E,F,..) API to send new messages to the log, if desired, but this is discouraged.

func MemoryHighwater

func MemoryHighwater(reset bool) int64

MemoryHighwater returns the maximum value of MemoryUsed() since the high-water mark was last reset. (See sqlite3_memory_highwater: http://sqlite.org/c3ref/memory_highwater.html)

func MemoryUsed

func MemoryUsed() int64

MemoryUsed returns the number of bytes of memory currently outstanding (malloced but not freed). (See sqlite3_memory_used: http://sqlite.org/c3ref/memory_highwater.html)

func Mprintf

func Mprintf(format string, arg string) string

Mprintf is like fmt.Printf but implements some additional formatting options that are useful for constructing SQL statements. (See http://sqlite.org/c3ref/mprintf.html)

func NewDriver

func NewDriver(open func(name string) (*Conn, error), configure func(*Conn) error) driver.Driver

NewDriver creates a new driver with specialized connection creation/configuration.

NewDriver(customOpen, nil) // no post-creation hook
NewDriver(nil, customConfigure) // default connection creation but specific configuration step

func SetSoftHeapLimit

func SetSoftHeapLimit(n int64) int64

SetSoftHeapLimit imposes a limit on heap size. (See http://sqlite.org/c3ref/soft_heap_limit64.html)

func SoftHeapLimit

func SoftHeapLimit() int64

SoftHeapLimit returns the limit on heap size. (See http://sqlite.org/c3ref/soft_heap_limit64.html)

func Version

func Version() string

Version returns the run-time library version number (See http://sqlite.org/c3ref/libversion.html)

func VersionNumber

func VersionNumber() int32

VersionNumber returns the run-time library version number as 300X00Y (See http://sqlite.org/c3ref/libversion.html)

Types

type Action

type Action int32

Action enumerates Authorizer action codes

Authorizer action codes

func (Action) String

func (a Action) String() string

type Affinity

type Affinity string

Affinity enumerates SQLite column type affinity

type AggregateContext

type AggregateContext struct {
	FunctionContext
	Aggregate interface{}
}

AggregateContext is used to represent context associated to aggregate function

type Auth

type Auth int32

Auth enumerates Authorizer return codes

const (
	AuthOk     Auth = C.SQLITE_OK
	AuthDeny   Auth = C.SQLITE_DENY
	AuthIgnore Auth = C.SQLITE_IGNORE
)

Authorizer return codes

type Authorizer

type Authorizer func(udp interface{}, action Action, arg1, arg2, dbName, triggerName string) Auth

Authorizer is the signature of an access authorization function. See Conn.SetAuthorizer

type Backup

type Backup struct {
	// contains filtered or unexported fields
}

The Backup object records state information about an ongoing online backup operation. (See http://sqlite.org/c3ref/backup.html)

func NewBackup

func NewBackup(dst *Conn, dstName string, src *Conn, srcName string) (*Backup, error)

NewBackup initializes the backup/copy of the content of one database (source) to another (destination). The database name is "main", "temp", or the name specified in an ATTACH statement.

(See http://sqlite.org/c3ref/backup_finish.html#sqlite3backupinit)

Example
dst, err := sqlite.Open(":memory:")
check(err)
defer dst.Close()
src, err := sqlite.Open(":memory:")
check(err)
defer src.Close()
err = src.Exec("CREATE TABLE test (content BLOB); INSERT INTO test VALUES (zeroblob(100))")
check(err)

bck, err := sqlite.NewBackup(dst, "main", src, "main")
check(err)
defer bck.Close()

cbs := make(chan sqlite.BackupStatus)
defer close(cbs)
var wg sync.WaitGroup
wg.Add(1)
go func() {
	for {
		s := <-cbs
		fmt.Printf("backup progress (remaining: %d)\n", s.Remaining)
		if s.Remaining == 0 {
			wg.Done()
			break
		}
	}
}()
err = bck.Run(100, 250000, cbs)
check(err)
wg.Wait()
Output:

backup progress (remaining: 0)

func (*Backup) Close

func (b *Backup) Close() error

Close finishes/stops the backup. (See http://sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish)

func (*Backup) Run

func (b *Backup) Run(npage int32, sleepNs time.Duration, c chan<- BackupStatus) error

Run starts the backup: - copying up to 'npage' pages between the source and destination at each step, - sleeping 'sleepNs' between steps, - notifying the caller of backup progress throw the channel 'c', - closing the backup when done or when an error happens. Sleeping is disabled if 'sleepNs' is zero or negative. Notification is disabled if 'c' is null. (See http://sqlite.org/c3ref/backup_finish.html#sqlite3backupstep, sqlite3_backup_remaining and sqlite3_backup_pagecount)

func (*Backup) Status

func (b *Backup) Status() BackupStatus

Status returns the number of pages still to be backed up and the total number of pages in the source database file. (See http://sqlite.org/c3ref/backup_finish.html#sqlite3backupremaining)

func (*Backup) Step

func (b *Backup) Step(npage int32) error

Step copies up to N pages between the source and destination databases. (See http://sqlite.org/c3ref/backup_finish.html#sqlite3backupstep)

type BackupStatus

type BackupStatus struct {
	Remaining int
	PageCount int
}

BackupStatus reports backup progression

type BlobReadWriter

type BlobReadWriter struct {
	BlobReader
}

BlobReadWriter is an io.ReadWriteCloser adapter for BLOB

func (*BlobReadWriter) Write

func (w *BlobReadWriter) Write(v []byte) (int, error)

Write writes data into a BLOB incrementally. (See http://sqlite.org/c3ref/blob_write.html)

type BlobReader

type BlobReader struct {
	// contains filtered or unexported fields
}

BlobReader is an io.ReadCloser adapter for BLOB (See http://sqlite.org/c3ref/blob.html)

func (*BlobReader) Close

func (r *BlobReader) Close() error

Close closes a BLOB handle. (See http://sqlite.org/c3ref/blob_close.html)

func (*BlobReader) Read

func (r *BlobReader) Read(v []byte) (int, error)

Read reads data from a BLOB incrementally. (See http://sqlite.org/c3ref/blob_read.html)

func (*BlobReader) Reopen

func (r *BlobReader) Reopen(rowid int64) error

Reopen moves a BLOB handle to a new row. (See http://sqlite.org/c3ref/blob_reopen.html)

func (*BlobReader) Seek

func (r *BlobReader) Seek(offset int64, whence int) (int64, error)

Seek sets the offset for the next Read or Write to offset. Tell is possible with Seek(0, os.SEEK_CUR). SQLite is limited to 32-bits offset.

func (*BlobReader) Size

func (r *BlobReader) Size() (int32, error)

Size returns the size of an opened BLOB. (See http://sqlite.org/c3ref/blob_bytes.html)

type BusyHandler

type BusyHandler func(udp interface{}, count int) bool

BusyHandler is the signature of callback to handle SQLITE_BUSY errors. Returns true to try again. Returns false to abort. See Conn.BusyHandler

type Column

type Column struct {
	Cid       int
	Name      string
	DataType  string
	NotNull   bool
	DfltValue string // FIXME type ?
	Pk        int
	Autoinc   bool
	CollSeq   string
}

Column is the description of one table's column See Conn.Columns/IndexColumns

func (Column) Affinity

func (c Column) Affinity() Affinity

Affinity returns the type affinity of the column.

type CommitHook

type CommitHook func(udp interface{}) (rollback bool)

CommitHook is the callback function signature. If the callback on a commit hook function returns true, then the commit is converted into a rollback.

type Conn

type Conn struct {

	// DefaultTimeLayout specifies the layout used to persist time ("2006-01-02 15:04:05.000Z07:00" by default).
	// When set to "", time is persisted as integer (unix time).
	// Using type alias implementing the Scanner/Valuer interfaces is suggested...
	DefaultTimeLayout string
	// ScanNumericalAsTime tells the driver to try to parse column with NUMERIC affinity as time.Time (using the DefaultTimeLayout)
	ScanNumericalAsTime bool
	// contains filtered or unexported fields
}

Conn represents a database connection handle. (See http://sqlite.org/c3ref/sqlite3.html)

func Open

func Open(filename string, flags ...OpenFlag) (*Conn, error)

Open opens a new database connection. ":memory:" for memory db, "" for temp file db

(See sqlite3_open_v2: http://sqlite.org/c3ref/open.html)

Example
db, err := sqlite.Open(":memory:")
check(err)
defer db.Close()
fmt.Printf("db path: %q\n", db.Filename("main"))
Output:

db path: ""

func OpenVfs

func OpenVfs(filename string, vfsname string, flags ...OpenFlag) (*Conn, error)

OpenVfs opens a new database with a specified virtual file system.

func Unwrap

func Unwrap(db *sql.DB) *Conn

Unwrap gives access to underlying driver connection.

func (*Conn) ApplicationID

func (c *Conn) ApplicationID(dbName string) (int, error)

ApplicationID queries the "Application ID" integer located into the database header. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_application_id)

func (*Conn) AreTriggersEnabled

func (c *Conn) AreTriggersEnabled() (bool, error)

AreTriggersEnabled checks if triggers are enabled. Calls sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_TRIGGER, -1)

(See http://sqlite.org/c3ref/c_dbconfig_enable_fkey.html)

func (*Conn) Begin

func (c *Conn) Begin() error

Begin begins a transaction in deferred mode. (See http://www.sqlite.org/lang_transaction.html)

func (*Conn) BeginTransaction

func (c *Conn) BeginTransaction(t TransactionType) error

BeginTransaction begins a transaction of the specified type. (See http://www.sqlite.org/lang_transaction.html)

func (*Conn) BusyHandler

func (c *Conn) BusyHandler(f BusyHandler, udp interface{}) error

BusyHandler registers a callback to handle SQLITE_BUSY errors. There can only be a single busy handler defined for each database connection. Setting a new busy handler clears any previously set handler. If f is nil, the current handler is removed. Cannot be used with Go >= 1.6 and cgocheck enabled. (See http://sqlite.org/c3ref/busy_handler.html)

func (*Conn) BusyTimeout

func (c *Conn) BusyTimeout(d time.Duration) error

BusyTimeout sets a busy timeout and clears any previously set handler. If duration is zero or negative, turns off busy handler. (See http://sqlite.org/c3ref/busy_timeout.html)

func (*Conn) CacheSize

func (c *Conn) CacheSize() (current int, max int)

CacheSize returns (current, max) sizes. Prepared statements cache is turned off when max size is 0

func (*Conn) Changes

func (c *Conn) Changes() int

Changes returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection. If a separate thread makes changes on the same database connection while Changes() is running then the value returned is unpredictable and not meaningful. (See http://sqlite.org/c3ref/changes.html)

func (*Conn) Close

func (c *Conn) Close() error

Close closes a database connection and any dangling statements. (See http://sqlite.org/c3ref/close.html)

func (*Conn) Columns

func (c *Conn) Columns(dbName, table string) ([]Column, error)

Columns returns a description for each column in the named table/view. Column.Autoinc and Column.CollSeq are left unspecified. No error is returned if the table does not exist. (See http://www.sqlite.org/pragma.html#pragma_table_info)

func (*Conn) Commit

func (c *Conn) Commit() error

Commit commits transaction. It is strongly discouraged to defer Commit without checking the error returned.

func (*Conn) CommitHook

func (c *Conn) CommitHook(f CommitHook, udp interface{})

CommitHook registers a callback function to be invoked whenever a transaction is committed. Cannot be used with Go >= 1.6 and cgocheck enabled. (See http://sqlite.org/c3ref/commit_hook.html)

func (*Conn) CreateAggregateFunction

func (c *Conn) CreateAggregateFunction(functionName string, nArg int32, pApp interface{},
	step StepFunction, final FinalFunction, d DestroyDataFunction) error

CreateAggregateFunction creates or redefines SQL aggregate functions. Cannot be used with Go >= 1.6 and cgocheck enabled. TODO Make possible to specify the preferred encoding (See http://sqlite.org/c3ref/create_function.html)

func (*Conn) CreateIntArray

func (c *Conn) CreateIntArray(name string) (IntArray, error)

CreateIntArray create a specific instance of an intarray object.

Each intarray object corresponds to a virtual table in the TEMP database with the specified name.

Destroy the intarray object by dropping the virtual table. If not done explicitly by the application, the virtual table will be dropped implicitly by the system when the database connection is closed.

func (*Conn) CreateModule

func (c *Conn) CreateModule(moduleName string, module Module) error

CreateModule registers a virtual table implementation. Cannot be used with Go >= 1.6 and cgocheck enabled. (See http://sqlite.org/c3ref/create_module.html)

func (*Conn) CreateScalarFunction

func (c *Conn) CreateScalarFunction(functionName string, nArg int32, deterministic bool, pApp interface{},
	f ScalarFunction, d DestroyDataFunction) error

CreateScalarFunction creates or redefines SQL scalar functions. Cannot be used with Go >= 1.6 and cgocheck enabled. TODO Make possible to specify the preferred encoding (See http://sqlite.org/c3ref/create_function.html)

func (*Conn) Databases

func (c *Conn) Databases() (map[string]string, error)

Databases returns one couple (name, file) for each database attached to the current database connection. (See http://www.sqlite.org/pragma.html#pragma_database_list)

func (*Conn) DeclareVTab

func (c *Conn) DeclareVTab(sql string) error

DeclareVTab declares the Schema of a virtual table. (See http://sqlite.org/c3ref/declare_vtab.html)

func (*Conn) EnableExtendedResultCodes

func (c *Conn) EnableExtendedResultCodes(b bool) error

EnableExtendedResultCodes enables or disables the extended result codes feature of SQLite. (See http://sqlite.org/c3ref/extended_result_codes.html)

func (*Conn) EnableFKey

func (c *Conn) EnableFKey(b bool) (bool, error)

EnableFKey enables or disables the enforcement of foreign key constraints. Calls sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_FKEY, b). Another way is PRAGMA foreign_keys = boolean;

(See http://sqlite.org/c3ref/c_dbconfig_enable_fkey.html)

func (*Conn) EnableTriggers

func (c *Conn) EnableTriggers(b bool) (bool, error)

EnableTriggers enables or disables triggers. Calls sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_TRIGGER, b).

(See http://sqlite.org/c3ref/c_dbconfig_enable_fkey.html)

func (*Conn) Encoding

func (c *Conn) Encoding(dbName string) (string, error)

Encoding returns the text encoding used by the specified database. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_encoding)

func (*Conn) Exec

func (c *Conn) Exec(cmd string, args ...interface{}) error

Exec prepares and executes one or many parameterized statement(s) (separated by semi-colon). Don't use it with SELECT or anything that returns data.

Example
db, err := sqlite.Open(":memory:")
check(err)
defer db.Close()

err = db.Exec("CREATE TABLE test1 (content TEXT); CREATE TABLE test2 (content TEXT); INSERT INTO test1 VALUES ('DATA')")
check(err)
tables, err := db.Tables("")
check(err)
fmt.Printf("%d tables\n", len(tables))
Output:

2 tables

func (*Conn) ExecDml

func (c *Conn) ExecDml(cmd string, args ...interface{}) (changes int, err error)

ExecDml helps executing DML statement: (1) it binds the specified args, (2) it executes the statement, (3) it returns the number of rows that were changed or inserted or deleted.

func (*Conn) Exists

func (c *Conn) Exists(query string, args ...interface{}) (bool, error)

Exists returns true if the specified query returns at least one row.

func (*Conn) ExportTableToCSV

func (db *Conn) ExportTableToCSV(dbName, table string, nullvalue string, headers bool, w *yacr.Writer) error

ExportTableToCSV exports table or view content to CSV. 'headers' flag turns output of headers on or off. NULL values are output as specified by 'nullvalue' parameter.

func (*Conn) FastExec

func (c *Conn) FastExec(sql string) error

FastExec executes one or many non-parameterized statement(s) (separated by semi-colon) with no control and no stmt cache.

func (*Conn) Filename

func (c *Conn) Filename(dbName string) string

Filename returns the filename for a database connection. (See http://sqlite.org/c3ref/db_filename.html)

func (*Conn) ForeignKeyCheck

func (c *Conn) ForeignKeyCheck(dbName, table string) ([]FkViolation, error)

ForeignKeyCheck checks the database, or the table, for foreign key constraints that are violated and returns one row of output for each violation. Database name is optional (default is 'main'). Table name is optional (default is all tables). (See http://sqlite.org/pragma.html#pragma_foreign_key_check)

func (*Conn) ForeignKeys

func (c *Conn) ForeignKeys(dbName, table string) (map[int]*ForeignKey, error)

ForeignKeys returns one description for each foreign key that references a column in the argument table. No error is returned if the table does not exist. (See http://www.sqlite.org/pragma.html#pragma_foreign_key_list)

func (*Conn) GetAutocommit

func (c *Conn) GetAutocommit() bool

GetAutocommit tests for auto-commit mode. (See http://sqlite.org/c3ref/get_autocommit.html)

func (*Conn) ImportCSV

func (db *Conn) ImportCSV(in io.Reader, ic ImportConfig, dbName, table string) error

ImportCSV imports CSV data into the specified table (which may not exist yet). Code is adapted from .import command implementation in SQLite3 shell sources.

func (*Conn) IndexColumns

func (c *Conn) IndexColumns(dbName, index string) ([]Column, error)

IndexColumns returns one description for each column in the named index. Only Column.Cid and Column.Name are specified. All other fields are unspecified. No error is returned if the index does not exist. (See http://www.sqlite.org/pragma.html#pragma_index_info)

func (*Conn) Indexes

func (c *Conn) Indexes(dbName string) (map[string]string, error)

Indexes returns indexes from 'sqlite_master'/'sqlite_temp_master'. As the index name is unique by database, (index name, table name) couples are returned. The database name can be empty, "main", "temp" or the name of an attached database.

func (*Conn) Insert

func (c *Conn) Insert(cmd string, args ...interface{}) (rowid int64, err error)

Insert is like ExecDml but returns the autoincremented rowid.

func (*Conn) IntegrityCheck

func (c *Conn) IntegrityCheck(dbName string, max int, quick bool) error

IntegrityCheck checks database integrity. Database name is optional (default is 'main'). (See http://www.sqlite.org/pragma.html#pragma_integrity_check and http://www.sqlite.org/pragma.html#pragma_quick_check)

func (*Conn) Interrupt

func (c *Conn) Interrupt()

Interrupt interrupts a long-running query. (See http://sqlite.org/c3ref/interrupt.html)

func (*Conn) IsClosed

func (c *Conn) IsClosed() bool

IsClosed tells if the database connection has been closed.

func (*Conn) IsFKeyEnabled

func (c *Conn) IsFKeyEnabled() (bool, error)

IsFKeyEnabled reports if the enforcement of foreign key constraints is enabled or not. Calls sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_FKEY, -1). Another way is PRAGMA foreign_keys;

(See http://sqlite.org/c3ref/c_dbconfig_enable_fkey.html)

func (*Conn) JournalMode

func (c *Conn) JournalMode(dbName string) (string, error)

JournalMode queries the current journaling mode for database. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_journal_mode)

func (*Conn) LastError

func (c *Conn) LastError() error

LastError returns the error for the most recent failed sqlite3_* API call associated with a database connection. (See http://sqlite.org/c3ref/errcode.html) FIXME it might be the case that a second error occurs on a separate thread in between the time of the first error and the call to this method.

func (*Conn) LastInsertRowid

func (c *Conn) LastInsertRowid() int64

LastInsertRowid returns the rowid of the most recent successful INSERT into the database. If a separate thread performs a new INSERT on the same database connection while the LastInsertRowid() function is running and thus changes the last insert rowid, then the value returned by LastInsertRowid() is unpredictable and might not equal either the old or the new last insert rowid. (See http://sqlite.org/c3ref/last_insert_rowid.html)

func (*Conn) Limit

func (c *Conn) Limit(id Limit) int32

Limit queries the current value of a limit. (See http://www.sqlite.org/c3ref/limit.html)

func (*Conn) LockingMode

func (c *Conn) LockingMode(dbName string) (string, error)

LockingMode queries the database connection locking-mode. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_locking_mode)

func (*Conn) MMapSize

func (c *Conn) MMapSize(dbName string) (int64, error)

MMapSize queries the maximum number of bytes that are set aside for memory-mapped I/O. Database name is optional (default is 'main'). (See http://www.sqlite.org/pragma.html#pragma_mmap_size and http://sqlite.org/mmap.html)

func (*Conn) NewBlobReadWriter

func (c *Conn) NewBlobReadWriter(db, table, column string, row int64) (*BlobReadWriter, error)

NewBlobReadWriter opens a BLOB for incremental I/O. (See http://sqlite.org/c3ref/blob_open.html)

func (*Conn) NewBlobReader

func (c *Conn) NewBlobReader(db, table, column string, row int64) (*BlobReader, error)

NewBlobReader opens a BLOB for incremental I/O in read-only mode.

(See http://sqlite.org/c3ref/blob_open.html)

Example
db, err := sqlite.Open(":memory:")
check(err)
err = db.Exec("CREATE TABLE test (content BLOB); INSERT INTO test VALUES (zeroblob(10))")
check(err)
rowid := db.LastInsertRowid()

br, err := db.NewBlobReader("main", "test", "content", rowid)
check(err)
defer br.Close()
size, err := br.Size()
check(err)
// TODO A real 'incremental' example...
content := make([]byte, size)
n, err := br.Read(content)
check(err)
fmt.Printf("blob (size: %d, read: %d, content: %q)\n", size, n, content)
Output:

blob (size: 10, read: 10, content: "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")

func (*Conn) OneValue

func (c *Conn) OneValue(query string, value interface{}, args ...interface{}) error

OneValue is used with SELECT that returns only one row with only one column. Returns io.EOF when there is no row. No check is performed to ensure that there is no more than one row.

func (*Conn) Prepare

func (c *Conn) Prepare(sql string, args ...interface{}) (*Stmt, error)

Prepare first looks in the statement cache or compiles the SQL statement. And optionally bind values. (See sqlite3_prepare_v2: http://sqlite.org/c3ref/prepare.html)

func (*Conn) Profile

func (c *Conn) Profile(f Profiler, udp interface{})

Profile registers or clears a profile function. Prepared statement placeholders are not logged with their assigned values. There can only be a single profiler defined for each database connection. Setting a new profiler clears the old one. If f is nil, the current profiler is removed. Cannot be used with Go >= 1.6 and cgocheck enabled. (See sqlite3_profile, http://sqlite.org/c3ref/profile.html)

func (*Conn) ProgressHandler

func (c *Conn) ProgressHandler(f ProgressHandler, numOps int32, udp interface{})

ProgressHandler registers or clears a query progress callback. The progress callback will be invoked every numOps opcodes. Only a single progress handler may be defined at one time per database connection. Setting a new progress handler cancels the old one. If f is nil, the current handler is removed. Cannot be used with Go >= 1.6 and cgocheck enabled. (See http://sqlite.org/c3ref/progress_handler.html)

func (*Conn) QueryOnly

func (c *Conn) QueryOnly(dbName string) (bool, error)

QueryOnly queries the status of the database. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_query_only)

func (*Conn) Readonly

func (c *Conn) Readonly(dbName string) (bool, error)

Readonly determines if a database is read-only. (See http://sqlite.org/c3ref/db_readonly.html)

func (*Conn) ReleaseSavepoint

func (c *Conn) ReleaseSavepoint(name string) error

ReleaseSavepoint causes all savepoints back to and including the most recent savepoint with a matching name to be removed from the transaction stack. (See http://sqlite.org/lang_savepoint.html)

func (*Conn) Rollback

func (c *Conn) Rollback() error

Rollback rollbacks transaction

func (*Conn) RollbackHook

func (c *Conn) RollbackHook(f RollbackHook, udp interface{})

RollbackHook registers a callback to be invoked each time a transaction is rolled back. Cannot be used with Go >= 1.6 and cgocheck enabled. (See http://sqlite.org/c3ref/commit_hook.html)

func (*Conn) RollbackSavepoint

func (c *Conn) RollbackSavepoint(name string) error

RollbackSavepoint reverts the state of the database back to what it was just before the corresponding SAVEPOINT. (See http://sqlite.org/lang_savepoint.html)

func (*Conn) Savepoint

func (c *Conn) Savepoint(name string) error

Savepoint starts a new transaction with a name. (See http://sqlite.org/lang_savepoint.html)

func (*Conn) SchemaVersion

func (c *Conn) SchemaVersion(dbName string) (int, error)

SchemaVersion gets the value of the schema-version. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_schema_version)

func (*Conn) Select

func (c *Conn) Select(query string, rowCallbackHandler func(s *Stmt) error, args ...interface{}) error

Select helps executing SELECT statement: (1) it binds the specified args, (2) it steps on the rows returned, (3) it delegates scanning to a callback function. The callback function is invoked for each result row coming out of the statement.

func (*Conn) SelectByID

func (c *Conn) SelectByID(query string, id interface{}, args ...interface{}) (found bool, err error)

SelectByID helps executing SELECT statement that is expected to return only one row. Args are for scanning (not binding). Returns false if there is no matching row. No check is done to ensure that no more than one row is returned by the statement.

func (*Conn) SetApplicationID

func (c *Conn) SetApplicationID(dbName string, id int) error

SetApplicationID changes the "Application ID". Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_application_id)

func (*Conn) SetAuthorizer

func (c *Conn) SetAuthorizer(f Authorizer, udp interface{}) error

SetAuthorizer sets or clears the access authorization function. Cannot be used with Go >= 1.6 and cgocheck enabled. (See http://sqlite.org/c3ref/set_authorizer.html)

func (*Conn) SetCacheSize

func (c *Conn) SetCacheSize(size int)

SetCacheSize sets the size of prepared statements cache. Cache is turned off (and flushed) when size <= 0

func (*Conn) SetJournalMode

func (c *Conn) SetJournalMode(dbName, mode string) (string, error)

SetJournalMode changes the journaling mode for database. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_journal_mode)

func (*Conn) SetLimit

func (c *Conn) SetLimit(id Limit, newVal int32) int32

SetLimit changes the value of a limit. (See http://www.sqlite.org/c3ref/limit.html)

func (*Conn) SetLockingMode

func (c *Conn) SetLockingMode(dbName, mode string) (string, error)

SetLockingMode changes the database connection locking-mode. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_locking_mode)

func (*Conn) SetMMapSize

func (c *Conn) SetMMapSize(dbName string, size int64) (int64, error)

SetMMapSize changes the maximum number of bytes that are set aside for memory-mapped I/O. Database name is optional (default is 'main'). If the specified size is zero then memory mapped I/O is disabled. If the specified size is negative, then the limit reverts to the default value. The size of the memory-mapped I/O region cannot be changed while the memory-mapped I/O region is in active use. (See http://www.sqlite.org/pragma.html#pragma_mmap_size and http://sqlite.org/mmap.html)

func (*Conn) SetQueryOnly

func (c *Conn) SetQueryOnly(dbName string, mode bool) error

SetQueryOnly prevents all changes to database files when enabled. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_query_only)

func (*Conn) SetRecursiveTriggers

func (c *Conn) SetRecursiveTriggers(dbName string, on bool) error

SetRecursiveTriggers sets or clears the recursive trigger capability. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_recursive_triggers)

func (*Conn) SetSynchronous

func (c *Conn) SetSynchronous(dbName string, mode int) error

SetSynchronous changes the synchronous flag. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_synchronous)

func (*Conn) Synchronous

func (c *Conn) Synchronous(dbName string) (int, error)

Synchronous queries the synchronous flag. Database name is optional (default is 'main'). (See http://sqlite.org/pragma.html#pragma_synchronous)

func (*Conn) TableIndexes

func (c *Conn) TableIndexes(dbName, table string) ([]Index, error)

TableIndexes returns one description for each index associated with the given table. No error is returned if the table does not exist. (See http://www.sqlite.org/pragma.html#pragma_index_list)

func (*Conn) Tables

func (c *Conn) Tables(dbName string) ([]string, error)

Tables returns tables (no view) from 'sqlite_master'/'sqlite_temp_master' and filters system tables out. The database name can be empty, "main", "temp" or the name of an attached database.

func (*Conn) TotalChanges

func (c *Conn) TotalChanges() int

TotalChanges returns the number of row changes caused by INSERT, UPDATE or DELETE statements since the database connection was opened. (See http://sqlite.org/c3ref/total_changes.html)

func (*Conn) Trace

func (c *Conn) Trace(f Tracer, udp interface{})

Trace registers or clears a trace function. Prepared statement placeholders are replaced/logged with their assigned values. There can only be a single tracer defined for each database connection. Setting a new tracer clears the old one. If f is nil, the current tracer is removed. Cannot be used with Go >= 1.6 and cgocheck enabled. (See sqlite3_trace, http://sqlite.org/c3ref/profile.html)

func (*Conn) Transaction

func (c *Conn) Transaction(t TransactionType, f func(c *Conn) error) error

Transaction is used to execute a function inside an SQLite database transaction. The transaction is committed when the function completes (with no error), or it rolls back if the function fails. If the transaction occurs within another transaction (only one that is started using this method) a Savepoint is created. Two errors may be returned: the first is the one returned by the f function, the second is the one returned by begin/commit/rollback. (See http://sqlite.org/tclsqlite.html#transaction)

func (*Conn) UpdateHook

func (c *Conn) UpdateHook(f UpdateHook, udp interface{})

UpdateHook registers a callback to be invoked each time a row is updated, inserted or deleted using this database connection. Cannot be used with Go >= 1.6 and cgocheck enabled. (See http://sqlite.org/c3ref/update_hook.html)

func (*Conn) Views

func (c *Conn) Views(dbName string) ([]string, error)

Views returns views from 'sqlite_master'/'sqlite_temp_master'. The database name can be empty, "main", "temp" or the name of an attached database.

type ConnError

type ConnError struct {
	// contains filtered or unexported fields
}

ConnError is a wrapper for all SQLite connection related error.

func (ConnError) Code

func (e ConnError) Code() Errno

Code returns the original SQLite error code (or -1 for errors generated by the Go wrapper)

func (ConnError) Error

func (e ConnError) Error() string

func (ConnError) ExtendedCode

func (e ConnError) ExtendedCode() int

ExtendedCode returns the SQLite extended error code. (See http://www.sqlite.org/c3ref/errcode.html) FIXME it might be the case that a second error occurs on a separate thread in between the time of the first error and the call to this method.

func (ConnError) Filename

func (e ConnError) Filename() string

Filename returns database file name from which the error comes from.

type Context

type Context C.sqlite3_context

Context common to function and virtual table (See http://sqlite.org/c3ref/context.html)

func (*Context) ResultBlob

func (c *Context) ResultBlob(b []byte)

ResultBlob sets the result of an SQL function. (See sqlite3_result_blob, http://sqlite.org/c3ref/result_blob.html)

func (*Context) ResultBool

func (c *Context) ResultBool(b bool)

ResultBool sets the result of an SQL function.

func (*Context) ResultDouble

func (c *Context) ResultDouble(d float64)

ResultDouble sets the result of an SQL function. (See sqlite3_result_double, http://sqlite.org/c3ref/result_blob.html)

func (*Context) ResultInt

func (c *Context) ResultInt(i int)

ResultInt sets the result of an SQL function. (See sqlite3_result_int, http://sqlite.org/c3ref/result_blob.html)

func (*Context) ResultInt64

func (c *Context) ResultInt64(i int64)

ResultInt64 sets the result of an SQL function. (See sqlite3_result_int64, http://sqlite.org/c3ref/result_blob.html)

func (*Context) ResultNull

func (c *Context) ResultNull()

ResultNull sets the result of an SQL function. (See sqlite3_result_null, http://sqlite.org/c3ref/result_blob.html)

func (*Context) ResultText

func (c *Context) ResultText(s string)

ResultText sets the result of an SQL function. (See sqlite3_result_text, http://sqlite.org/c3ref/result_blob.html)

func (*Context) ResultZeroblob

func (c *Context) ResultZeroblob(n ZeroBlobLength)

ResultZeroblob sets the result of an SQL function. (See sqlite3_result_zeroblob, http://sqlite.org/c3ref/result_blob.html)

type DestroyDataFunction

type DestroyDataFunction func(pApp interface{})

DestroyDataFunction is the expected signature of function used to finalize user data.

type Errno

type Errno int32

Errno enumerates SQLite result codes

func (Errno) Error

func (e Errno) Error() string

type FinalFunction

type FinalFunction func(ctx *AggregateContext)

FinalFunction is the expected signature of final function implemented in Go

type FkViolation

type FkViolation struct {
	Table  string
	RowID  int64
	Parent string
	FkID   int
}

FkViolation is the description of one foreign key constraint violation.

type ForeignKey

type ForeignKey struct {
	Table string
	From  []string
	To    []string
}

ForeignKey is the description of one table's foreign key See Conn.ForeignKeys

type FunctionContext

type FunctionContext struct {
	// contains filtered or unexported fields
}

FunctionContext common to scalar and aggregate functions (See http://sqlite.org/c3ref/context.html)

func (*FunctionContext) Blob

func (c *FunctionContext) Blob(i int) []byte

Blob obtains a SQL function parameter value. The leftmost value is number 0. (See sqlite3_value_blob and sqlite3_value_bytes, http://sqlite.org/c3ref/value_blob.html)

func (*FunctionContext) Bool

func (c *FunctionContext) Bool(i int) bool

Bool obtains a SQL function parameter value. The leftmost value is number 0.

func (*FunctionContext) Double

func (c *FunctionContext) Double(i int) float64

Double obtains a SQL function parameter value. The leftmost value is number 0. (See sqlite3_value_double, http://sqlite.org/c3ref/value_blob.html)

func (*FunctionContext) Int

func (c *FunctionContext) Int(i int) int

Int obtains a SQL function parameter value. The leftmost value is number 0. (See sqlite3_value_int, http://sqlite.org/c3ref/value_blob.html)

func (*FunctionContext) Int64

func (c *FunctionContext) Int64(i int) int64

Int64 obtains a SQL function parameter value. The leftmost value is number 0. (See sqlite3_value_int64, http://sqlite.org/c3ref/value_blob.html)

func (*FunctionContext) NumericType

func (c *FunctionContext) NumericType(i int) Type

NumericType obtains a SQL function parameter value numeric type (with possible conversion). The leftmost value is number 0. (See sqlite3_value_numeric_type, http://sqlite.org/c3ref/value_blob.html)

func (*FunctionContext) Result

func (c *FunctionContext) Result(r interface{})

Result sets the result of an SQL function.

func (*FunctionContext) ResultBlob

func (c *FunctionContext) ResultBlob(b []byte)

ResultBlob sets the result of an SQL function.

func (*FunctionContext) ResultBool

func (c *FunctionContext) ResultBool(b bool)

ResultBool sets the result of an SQL function.

func (*FunctionContext) ResultDouble

func (c *FunctionContext) ResultDouble(d float64)

ResultDouble sets the result of an SQL function.

func (*FunctionContext) ResultError

func (c *FunctionContext) ResultError(msg string)

ResultError sets the result of an SQL function. (See sqlite3_result_error, http://sqlite.org/c3ref/result_blob.html)

func (*FunctionContext) ResultErrorCode

func (c *FunctionContext) ResultErrorCode(e Errno)

ResultErrorCode sets the result of an SQL function. (See sqlite3_result_error_code, http://sqlite.org/c3ref/result_blob.html)

func (*FunctionContext) ResultErrorNoMem

func (c *FunctionContext) ResultErrorNoMem()

ResultErrorNoMem sets the result of an SQL function. (See sqlite3_result_error_nomem, http://sqlite.org/c3ref/result_blob.html)

func (*FunctionContext) ResultErrorTooBig

func (c *FunctionContext) ResultErrorTooBig()

ResultErrorTooBig sets the result of an SQL function. (See sqlite3_result_error_toobig, http://sqlite.org/c3ref/result_blob.html)

func (*FunctionContext) ResultInt

func (c *FunctionContext) ResultInt(i int)

ResultInt sets the result of an SQL function.

func (*FunctionContext) ResultInt64

func (c *FunctionContext) ResultInt64(i int64)

ResultInt64 sets the result of an SQL function.

func (*FunctionContext) ResultNull

func (c *FunctionContext) ResultNull()

ResultNull sets the result of an SQL function.

func (*FunctionContext) ResultText

func (c *FunctionContext) ResultText(s string)

ResultText sets the result of an SQL function.

func (*FunctionContext) ResultValue

func (c *FunctionContext) ResultValue(i int)

ResultValue sets the result of an SQL function. The leftmost value is number 0. (See sqlite3_result_value, http://sqlite.org/c3ref/result_blob.html)

func (*FunctionContext) ResultZeroblob

func (c *FunctionContext) ResultZeroblob(n ZeroBlobLength)

ResultZeroblob sets the result of an SQL function.

func (*FunctionContext) Text

func (c *FunctionContext) Text(i int) string

Text obtains a SQL function parameter value. The leftmost value is number 0. (See sqlite3_value_text, http://sqlite.org/c3ref/value_blob.html)

func (*FunctionContext) Type

func (c *FunctionContext) Type(i int) Type

Type obtains a SQL function parameter value type. The leftmost value is number 0. (See sqlite3_value_type, http://sqlite.org/c3ref/value_blob.html)

func (*FunctionContext) UserData

func (c *FunctionContext) UserData() interface{}

UserData returns the user data for functions. (See http://sqlite.org/c3ref/user_data.html)

func (*FunctionContext) Value

func (c *FunctionContext) Value(i int) interface{}

Value obtains a SQL function parameter value depending on its type.

type ImportConfig

type ImportConfig struct {
	Name      string     // the name of the input; used only for error reports
	Separator byte       // CSV separator
	Quoted    bool       // CSV fields are quoted or not
	Guess     bool       // guess separator
	Trim      bool       // optional, trim spaces
	Comment   byte       // optinal, comment marker
	Headers   bool       // skip headers (first line)
	Types     []Affinity // optional, when target table does not exist, specify columns type
	Log       io.Writer  // optional, used to trace lines in error
}

ImportConfig gathers import parameters.

type Index

type Index struct {
	Name   string
	Unique bool
}

Index is the description of one table's index See Conn.Indexes

type IntArray

type IntArray interface {
	Bind(elements []int64)
	Drop() error
}

IntArray is the Go-language interface definition for the "intarray" or integer array virtual table for SQLite.

The intarray virtual table is designed to facilitate using an array of integers as the right-hand side of an IN operator. So instead of doing a prepared statement like this:

SELECT * FROM table WHERE x IN (?,?,?,...,?);

And then binding indivdual integers to each of ? slots, a Go-language application can create an intarray object (named "ex1" in the following example), prepare a statement like this:

SELECT * FROM table WHERE x IN ex1;

Then bind an ordinary Go slice of integer values to the ex1 object to run the statement.

USAGE:

One or more intarray objects can be created as follows:

var p1, p2, p3 IntArray
p1, err = db.CreateIntArray("ex1")
p2, err = db.CreateIntArray("ex2")
p3, err = db.CreateIntArray("ex3")

Each call to CreateIntArray() generates a new virtual table module and a singleton of that virtual table module in the TEMP database. Both the module and the virtual table instance use the name given by the second parameter. The virtual tables can then be used in prepared statements:

SELECT * FROM t1, t2, t3
 WHERE t1.x IN ex1
  AND t2.y IN ex2
  AND t3.z IN ex3;

Each integer array is initially empty. New arrays can be bound to an integer array as follows:

p1.Bind([]int64{ 1, 2, 3, 4 })
p2.Bind([]int64{ 5, 6, 7, 8, 9, 10, 11 })
a3 := make([]int64, 100)
// Fill in content of a3
p3.Bind(a3)

A single intarray object can be rebound multiple times. But do not attempt to change the bindings of an intarray while it is in the middle of a query.

The application must not change the intarray values while an intarray is in the middle of a query.

The intarray object is automatically destroyed when its corresponding virtual table is dropped. Since the virtual tables are created in the TEMP database, they are automatically dropped when the database connection closes so the application does not normally need to take any special action to free the intarray objects (except if connections are pooled...).

type JulianTime

type JulianTime struct {
	time.Time
}

JulianTime is an alias used to persist time as float64 (max precision is 1s and timezone is lost)

func (*JulianTime) Scan

func (t *JulianTime) Scan(src interface{}) error

Scan implements the database/sql/Scanner interface.

func (JulianTime) Value

func (t JulianTime) Value() (driver.Value, error)

Value implements the database/sql/driver/Valuer interface

type Limit

type Limit int32

Limit enumerates run-time limit categories (See http://www.sqlite.org/c3ref/c_limit_attached.html)

const (
	LimitLength            Limit = C.SQLITE_LIMIT_LENGTH // The maximum size of any string or BLOB or table row, in bytes.
	LimitColumn            Limit = C.SQLITE_LIMIT_COLUMN
	LimitExprDepth         Limit = C.SQLITE_LIMIT_EXPR_DEPTH
	LimitCompoundSelect    Limit = C.SQLITE_LIMIT_COMPOUND_SELECT
	LimitVdbeOp            Limit = C.SQLITE_LIMIT_VDBE_OP
	LimitFunctionArg       Limit = C.SQLITE_LIMIT_FUNCTION_ARG
	LimitAttached          Limit = C.SQLITE_LIMIT_ATTACHED
	LimitLikePatternLength Limit = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
	LimitVariableNumber    Limit = C.SQLITE_LIMIT_VARIABLE_NUMBER
	LimitTriggerLength     Limit = C.SQLITE_LIMIT_TRIGGER_DEPTH
)

Run-time limit categories

type Logger

type Logger func(udp interface{}, err error, msg string)

Logger is the signature of SQLite logger implementation. See ConfigLog

type Module

type Module interface {
	Create(c *Conn, args []string) (VTab, error)  // See http://sqlite.org/vtab.html#xcreate
	Connect(c *Conn, args []string) (VTab, error) // See http://sqlite.org/vtab.html#xconnect
	DestroyModule()                               // See http://sqlite.org/c3ref/create_module.html
}

Module is a "virtual table module", it defines the implementation of a virtual tables. (See http://sqlite.org/c3ref/module.html)

type OpenError

type OpenError struct {
	Code         Errno // thread safe error code
	ExtendedCode int
	Msg          string
	Filename     string
}

OpenError is for detailed report on SQLite open failure.

func (OpenError) Error

func (e OpenError) Error() string

type OpenFlag

type OpenFlag int32

OpenFlag enumerates flags for file open operations

const (
	OpenReadOnly     OpenFlag = C.SQLITE_OPEN_READONLY
	OpenReadWrite    OpenFlag = C.SQLITE_OPEN_READWRITE
	OpenCreate       OpenFlag = C.SQLITE_OPEN_CREATE
	OpenURI          OpenFlag = C.SQLITE_OPEN_URI
	OpenNoMutex      OpenFlag = C.SQLITE_OPEN_NOMUTEX
	OpenFullMutex    OpenFlag = C.SQLITE_OPEN_FULLMUTEX
	OpenSharedCache  OpenFlag = C.SQLITE_OPEN_SHAREDCACHE
	OpenPrivateCache OpenFlag = C.SQLITE_OPEN_PRIVATECACHE
)

Flags for file open operations

type Profiler

type Profiler func(udp interface{}, sql string, duration time.Duration)

Profiler is the signature of a profile function. See Conn.Profile

type ProgressHandler

type ProgressHandler func(udp interface{}) (interrupt bool)

ProgressHandler is the signature of query progress callback. Returns true to interrupt. For example, to cancel long-running queries. See Conn.ProgressHandler

type RollbackHook

type RollbackHook func(udp interface{})

RollbackHook is the callback function signature.

type ScalarContext

type ScalarContext struct {
	FunctionContext
	// contains filtered or unexported fields
}

ScalarContext is used to represent context associated to scalar function

func (*ScalarContext) GetAuxData

func (c *ScalarContext) GetAuxData(n int) interface{}

GetAuxData returns function auxiliary data. (See sqlite3_get_auxdata, http://sqlite.org/c3ref/get_auxdata.html)

func (*ScalarContext) SetAuxData

func (c *ScalarContext) SetAuxData(n int, ad interface{})

SetAuxData sets function auxiliary data. No destructor is needed a priori (See sqlite3_set_auxdata, http://sqlite.org/c3ref/get_auxdata.html)

type ScalarFunction

type ScalarFunction func(ctx *ScalarContext, nArg int)

ScalarFunction is the expected signature of scalar function implemented in Go

type StepFunction

type StepFunction func(ctx *AggregateContext, nArg int)

StepFunction is the expected signature of step function implemented in Go

type Stmt

type Stmt struct {

	// Tell if the stmt should be cached (default true)
	Cacheable bool
	// contains filtered or unexported fields
}

Stmt represents a single SQL statement. (See http://sqlite.org/c3ref/stmt.html)

func (*Stmt) Bind

func (s *Stmt) Bind(args ...interface{}) error

Bind binds parameters by their index. Calls sqlite3_bind_parameter_count and sqlite3_bind_(blob|double|int|int64|null|text) depending on args type/kind. (See http://sqlite.org/c3ref/bind_blob.html)

func (*Stmt) BindByIndex

func (s *Stmt) BindByIndex(index int, value interface{}) error

BindByIndex binds value to the specified host parameter of the prepared statement. Value's type/kind is used to find the storage class. The leftmost SQL parameter has an index of 1.

func (*Stmt) BindParameterCount

func (s *Stmt) BindParameterCount() int

BindParameterCount returns the number of SQL parameters. FIXME If parameters of the ?NNN form are used, there may be gaps in the list. (See http://sqlite.org/c3ref/bind_parameter_count.html)

func (*Stmt) BindParameterIndex

func (s *Stmt) BindParameterIndex(name string) (int, error)

BindParameterIndex returns the index of a parameter with a given name (cached). The first host parameter has an index of 1, not 0. (See http://sqlite.org/c3ref/bind_parameter_index.html)

func (*Stmt) BindParameterName

func (s *Stmt) BindParameterName(index int) (string, error)

BindParameterName returns the name of a wildcard parameter (not cached). Returns "" if the index is out of range or if the wildcard is unnamed. The first host parameter has an index of 1, not 0. (See http://sqlite.org/c3ref/bind_parameter_name.html)

func (*Stmt) BindReflect

func (s *Stmt) BindReflect(index int, value interface{}) error

BindReflect binds value to the specified host parameter of the prepared statement. Value's (reflect) Kind is used to find the storage class. The leftmost SQL parameter has an index of 1.

func (*Stmt) Busy

func (s *Stmt) Busy() bool

Busy returns true if the prepared statement is in need of being reset. (See http://sqlite.org/c3ref/stmt_busy.html)

func (*Stmt) ClearBindings

func (s *Stmt) ClearBindings() error

ClearBindings resets all bindings on a prepared statement. (See http://sqlite.org/c3ref/clear_bindings.html)

func (*Stmt) ColumnCount

func (s *Stmt) ColumnCount() int

ColumnCount returns the number of columns in the result set for the statement (with or without row). (See http://sqlite.org/c3ref/column_count.html)

func (*Stmt) ColumnDeclaredType

func (s *Stmt) ColumnDeclaredType(index int) string

ColumnDeclaredType returns the declared type of the table column of a particular result column in SELECT statement. If the result column is an expression or subquery, then an empty string is returned. The left-most column is column 0. (See http://www.sqlite.org/c3ref/column_decltype.html)

func (*Stmt) ColumnIndex

func (s *Stmt) ColumnIndex(name string) (int, error)

ColumnIndex returns the column index in a result set for a given column name. The leftmost column is number 0. Must scan all columns (but result is cached). (See http://sqlite.org/c3ref/column_name.html)

func (*Stmt) ColumnName

func (s *Stmt) ColumnName(index int) string

ColumnName returns the name of the Nth column of the result set returned by the SQL statement. (not cached) The leftmost column is number 0. (See http://sqlite.org/c3ref/column_name.html)

func (*Stmt) ColumnNames

func (s *Stmt) ColumnNames() []string

ColumnNames returns the name of the columns of the result set returned by the SQL statement. (not cached)

func (*Stmt) ColumnType

func (s *Stmt) ColumnType(index int) Type

ColumnType returns the datatype code for the initial data type of the result column. The leftmost column is number 0. Should not be cached (valid only for one row) (see dynamic type http://www.sqlite.org/datatype3.html)

After a type conversion, the value returned by sqlite3_column_type() is undefined. (See sqlite3_column_type: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ColumnTypeAffinity

func (s *Stmt) ColumnTypeAffinity(index int) Affinity

ColumnTypeAffinity returns the type affinity of the table column of a particular result column in SELECT statement. If the result column is an expression or subquery, then None is returned. The left-most column is column 0. (See http://sqlite.org/datatype3.html)

func (*Stmt) Conn

func (s *Stmt) Conn() *Conn

Conn finds the database handle of a prepared statement. (Like http://sqlite.org/c3ref/db_handle.html)

func (*Stmt) DataCount

func (s *Stmt) DataCount() int

DataCount returns the number of values available from the current row of the currently executing statement. Same as ColumnCount() except when there is no (more) row, it returns 0. (See http://sqlite.org/c3ref/data_count.html)

func (*Stmt) Empty

func (s *Stmt) Empty() bool

Empty returns true when then input text contains no SQL (if the input is an empty string or a comment)

func (*Stmt) Exec

func (s *Stmt) Exec(args ...interface{}) error

Exec is a one-step statement execution. Don't use it with SELECT or anything that returns data. The Stmt is reset at each call. (See http://sqlite.org/c3ref/bind_blob.html, http://sqlite.org/c3ref/step.html)

func (*Stmt) ExecDml

func (s *Stmt) ExecDml(args ...interface{}) (changes int, err error)

ExecDml is like Exec but returns the number of rows that were changed or inserted or deleted. Don't use it with SELECT or anything that returns data. The Stmt is reset at each call.

Example
db, err := sqlite.Open(":memory:")
check(err)
defer db.Close()
err = db.Exec("CREATE TABLE test (content TEXT); INSERT INTO test VALUES ('Go'); INSERT INTO test VALUES ('SQLite')")
check(err)

s, err := db.Prepare("UPDATE test SET content = content || 'lang' WHERE content LIKE ?")
check(err)
defer s.Finalize()
changes, err := s.ExecDml("%o")
check(err)
fmt.Printf("%d change(s)\n", changes)
Output:

1 change(s)

func (*Stmt) ExplainQueryPlan

func (s *Stmt) ExplainQueryPlan(w io.Writer) error

ExplainQueryPlan outputs the corresponding EXPLAIN QUERY PLAN report to the specified writer (See http://sqlite.org/eqp.html)

func (*Stmt) ExportToCSV

func (s *Stmt) ExportToCSV(nullvalue string, headers bool, w *yacr.Writer) error

ExportToCSV exports statement result to CSV. 'headers' flag turns output of headers on or off. NULL values are output as specified by 'nullvalue' parameter.

func (*Stmt) Finalize

func (s *Stmt) Finalize() error

Finalize destroys a prepared statement. (See http://sqlite.org/c3ref/finalize.html)

func (*Stmt) Insert

func (s *Stmt) Insert(args ...interface{}) (rowid int64, err error)

Insert is like ExecDml but returns the autoincremented rowid. Don't use it with SELECT or anything that returns data. The Stmt is reset at each call.

Example
db, err := sqlite.Open(":memory:")
check(err)
defer db.Close()
err = db.Exec("CREATE TABLE test (content TEXT)")
check(err)

s, err := db.Prepare("INSERT INTO test VALUES (?)")
check(err)
defer s.Finalize()
data := []string{"Go", "SQLite", "Driver"}
for _, d := range data {
	rowID, err := s.Insert(d)
	check(err)
	fmt.Println(rowID)
}
Output:

1
2
3

func (*Stmt) NamedBind

func (s *Stmt) NamedBind(args ...interface{}) error

NamedBind binds parameters by their name (name1, value1, ...)

func (*Stmt) NamedScan

func (s *Stmt) NamedScan(args ...interface{}) error

NamedScan scans result values from a query by name (name1, value1, ...).

NULL value is converted to 0 if arg type is *int,*int64,*float,*float64, to "" for *string, to []byte{} for *[]byte and to false for *bool. To avoid NULL conversion, arg type must be **T. Calls sqlite3_column_(blob|double|int|int64|text) depending on args type. (See http://sqlite.org/c3ref/column_blob.html)

Example
db, err := sqlite.Open(":memory:")
check(err)
defer db.Close()

s, err := db.Prepare("SELECT 1 AS id, 'Go' AS name UNION SELECT 2, 'SQLite'")
check(err)
defer s.Finalize()

var id int
var name string
err = s.Select(func(s *sqlite.Stmt) (err error) {
	if err = s.NamedScan("name", &name, "id", &id); err != nil {
		return
	}
	fmt.Println(id, name)
	return
})
check(err)
Output:

1 Go
2 SQLite

func (*Stmt) Next

func (s *Stmt) Next() (bool, error)

Next evaluates an SQL statement

With custom error handling:

for {
	if ok, err := s.Next(); err != nil {
		return nil, err
	} else if !ok {
		break
	}
	err = s.Scan(&fnum, &inum, &sstr)
}

(See http://sqlite.org/c3ref/step.html)

func (*Stmt) ReadOnly

func (s *Stmt) ReadOnly() bool

ReadOnly returns true if the prepared statement is guaranteed to not modify the database. (See http://sqlite.org/c3ref/stmt_readonly.html)

func (*Stmt) Reset

func (s *Stmt) Reset() error

Reset terminates the current execution of an SQL statement and reset it back to its starting state so that it can be reused. (See http://sqlite.org/c3ref/reset.html)

func (*Stmt) SQL

func (s *Stmt) SQL() string

SQL returns the SQL associated with a prepared statement. (See http://sqlite.org/c3ref/sql.html)

func (*Stmt) Scan

func (s *Stmt) Scan(args ...interface{}) error

Scan scans result values from a query.

NULL value is converted to 0 if arg type is *int,*int64,*float,*float64, to "" for *string, to []byte{} for *[]byte and to false for *bool. To avoid NULL conversion, arg type must be **T. Calls sqlite3_column_(blob|double|int|int64|text) depending on args type/kind. (See http://sqlite.org/c3ref/column_blob.html)

Example
db, err := sqlite.Open(":memory:")
check(err)
defer db.Close()

s, err := db.Prepare("SELECT 1 AS id, 'Go' AS name, 'Y' AS status UNION SELECT 2, 'SQLite', 'yes'")
check(err)
defer s.Finalize()

var id int
var name string
var status YesOrNo

err = s.Select(func(s *sqlite.Stmt) (err error) {
	if err = s.Scan(&id, &name, &status); err != nil {
		return
	}
	fmt.Println(id, name, status)
	return
})
check(err)
Output:

1 Go true
2 SQLite true

func (*Stmt) ScanBlob

func (s *Stmt) ScanBlob(index int) (value []byte, isNull bool)

ScanBlob scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_blob: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanBool

func (s *Stmt) ScanBool(index int) (value bool, isNull bool, err error)

ScanBool scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_int: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanByIndex

func (s *Stmt) ScanByIndex(index int, value interface{}) (isNull bool, err error)

ScanByIndex scans result value from a query. The leftmost column/index is number 0.

Destination type is specified by the caller (except when value type is *interface{}). The value must be of one of the following types/kinds:

(*)*string
(*)*int,int8,int16,int32,int64
(*)*uint,uint8,uint16,uint32,uint64
(*)*bool
(*)*float32,float64
(*)*[]byte
*time.Time
sql.Scanner
*interface{}

Returns true when column is null. Calls sqlite3_column_(blob|double|int|int64|text) depending on arg type/kind. (See http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanByName

func (s *Stmt) ScanByName(name string, value interface{}) (isNull bool, err error)

ScanByName scans result value from a query. Returns true when column is null. Calls sqlite3_column_(blob|double|int|int64|text) depending on arg type/kind. (See http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanByte

func (s *Stmt) ScanByte(index int) (value byte, isNull bool, err error)

ScanByte scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_int: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanDouble

func (s *Stmt) ScanDouble(index int) (value float64, isNull bool, err error)

ScanDouble scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_double: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanInt

func (s *Stmt) ScanInt(index int) (value int, isNull bool, err error)

ScanInt scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_int: http://sqlite.org/c3ref/column_blob.html) TODO Factorize with ScanByte, ScanBool

func (*Stmt) ScanInt32

func (s *Stmt) ScanInt32(index int) (value int32, isNull bool, err error)

ScanInt32 scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_int: http://sqlite.org/c3ref/column_blob.html) TODO Factorize with ScanByte, ScanBool

func (*Stmt) ScanInt64

func (s *Stmt) ScanInt64(index int) (value int64, isNull bool, err error)

ScanInt64 scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_int64: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanRawBytes

func (s *Stmt) ScanRawBytes(index int) (value []byte, isNull bool)

ScanRawBytes scans result value from a query without making any copy. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_blob: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanReflect

func (s *Stmt) ScanReflect(index int, v interface{}) (isNull bool, err error)

ScanReflect scans result value from a query. The leftmost column/index is number 0.

Destination type is specified by the caller. The value must be of one of the following kinds:

*string
*int,int8,int16,int32,int64
*uint,uint8,uint16,uint32,uint64
*bool
*float32,float64

Returns true when column is null.

func (*Stmt) ScanText

func (s *Stmt) ScanText(index int) (value string, isNull bool)

ScanText scans result value from a query. The leftmost column/index is number 0. Returns true when column is null. (See sqlite3_column_text: http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanTime

func (s *Stmt) ScanTime(index int) (value time.Time, isNull bool, err error)

ScanTime scans result value from a query. If time is persisted as string without timezone, UTC is used. If time is persisted as numeric, local is used. The leftmost column/index is number 0. Returns true when column is null. The column type affinity must be consistent with the format used (INTEGER or NUMERIC or NONE for unix time, REAL or NONE for julian day).

func (*Stmt) ScanValue

func (s *Stmt) ScanValue(index int, blob bool) (value interface{}, isNull bool)

ScanValue scans result value from a query. The leftmost column/index is number 0.

Destination type is decided by SQLite. The returned value will be of one of the following types:

nil
string (exception if blob is true)
int64
float64
[]byte

Calls sqlite3_column_(blob|double|int|int64|text) depending on columns type. (See http://sqlite.org/c3ref/column_blob.html)

func (*Stmt) ScanValues

func (s *Stmt) ScanValues(values []interface{})

ScanValues is like ScanValue on several columns.

func (*Stmt) Select

func (s *Stmt) Select(rowCallbackHandler func(s *Stmt) error, args ...interface{}) error

Select helps executing SELECT statement: (1) it binds the specified args, (2) it steps on the rows returned, (3) it delegates scanning to a callback function. The callback function is invoked for each result row coming out of the statement.

 s, err := db.Prepare(...)
	// TODO error handling
 defer s.Finalize()
 err = s.Select(func(s *Stmt) error {
 	//Scan
 })
	// TODO error handling

func (*Stmt) SelectOneRow

func (s *Stmt) SelectOneRow(args ...interface{}) (found bool, err error)

SelectOneRow helps executing SELECT statement that is expected to return only one row. Args are for scanning (not binding). Returns false if there is no matching row. No check is done to ensure that no more than one row is returned by the statement. TODO Create a SelectUniqueRow that checks that the row is unique.

func (*Stmt) Status

func (s *Stmt) Status(op StmtStatus, reset bool) int

Status returns the value of a status counter for a prepared statement. (See http://sqlite.org/c3ref/stmt_status.html)

func (*Stmt) Tail

func (s *Stmt) Tail() string

Tail returns the unused portion of the original SQL statement.

type StmtError

type StmtError struct {
	ConnError
	// contains filtered or unexported fields
}

StmtError is a wrapper for all SQLite statement related error.

func (StmtError) SQL

func (e StmtError) SQL() string

SQL returns the SQL associated with the prepared statement in error.

type StmtStatus

type StmtStatus int32

StmtStatus enumerates status parameters for prepared statements

const (
	StmtStatusFullScanStep StmtStatus = C.SQLITE_STMTSTATUS_FULLSCAN_STEP
	StmtStatusSort         StmtStatus = C.SQLITE_STMTSTATUS_SORT
	StmtStatusAutoIndex    StmtStatus = C.SQLITE_STMTSTATUS_AUTOINDEX
)

Status counters for prepared statements

type ThreadingMode

type ThreadingMode int32

ThreadingMode enumerates SQLite threading mode See ConfigThreadingMode

SQLite threading modes

type TimeStamp

type TimeStamp struct {
	time.Time
}

TimeStamp is an alias used to persist time as '2006-01-02T15:04:05.000Z07:00' string

func (TimeStamp) MarshalText

func (t TimeStamp) MarshalText() ([]byte, error)

MarshalText encoding.TextMarshaler interface. TimeStamp is formatted as null when zero or RFC3339.

func (*TimeStamp) Scan

func (t *TimeStamp) Scan(src interface{}) error

Scan implements the database/sql/Scanner interface.

func (*TimeStamp) UnmarshalText

func (t *TimeStamp) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. Date is expected in RFC3339 format or null.

func (TimeStamp) Value

func (t TimeStamp) Value() (driver.Value, error)

Value implements the database/sql/driver/Valuer interface

type Tracer

type Tracer func(udp interface{}, sql string)

Tracer is the signature of a trace function. See Conn.Trace

type TransactionType

type TransactionType uint8

TransactionType enumerates the different transaction behaviors See Conn.BeginTransaction

const (
	Deferred  TransactionType = 0
	Immediate TransactionType = 1
	Exclusive TransactionType = 2
)

Transaction types

type Type

type Type uint8

Type enumerates SQLite fundamental datatypes

func (Type) String

func (t Type) String() string

type UnixTime

type UnixTime struct {
	time.Time
}

UnixTime is an alias used to persist time as int64 (max precision is 1s and timezone is lost)

func (*UnixTime) Scan

func (t *UnixTime) Scan(src interface{}) error

Scan implements the database/sql/Scanner interface.

func (UnixTime) Value

func (t UnixTime) Value() (driver.Value, error)

Value implements the database/sql/driver/Valuer interface

type UpdateHook

type UpdateHook func(udp interface{}, a Action, dbName, tableName string, rowID int64)

UpdateHook is the callback function signature.

type VTab

VTab describes a particular instance of the virtual table. (See http://sqlite.org/c3ref/vtab.html)

type VTabCursor

type VTabCursor interface {
	Close() error  // See http://sqlite.org/vtab.html#xclose
	Filter() error // See http://sqlite.org/vtab.html#xfilter
	Next() error   // See http://sqlite.org/vtab.html#xnext
	EOF() bool     // See http://sqlite.org/vtab.html#xeof
	// col is zero-based so the first column is numbered 0
	Column(c *Context, col int) error // See http://sqlite.org/vtab.html#xcolumn
	Rowid() (int64, error)            // See http://sqlite.org/vtab.html#xrowid
}

VTabCursor describes cursors that point into the virtual table and are used to loop through the virtual table. (See http://sqlite.org/c3ref/vtab_cursor.html)

type VTabExtended

type VTabExtended interface {
	VTab
	Update(rowid int64) error

	Begin() error
	Sync() error
	Commit() error
	Rollback() error

	//FindFunction(nArg int, name string /*, void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), void **ppArg*/) error
	Rename(newName string) error

	Savepoint(i int) error
	Release(i int) error
	RollbackTo(i int) error
}

VTabExtended lists optional/extended functions. (See http://sqlite.org/c3ref/vtab.html)

type ZeroBlobLength

type ZeroBlobLength int32

ZeroBlobLength is used to reserve space for a BLOB that is later written.

stmt.Bind(..., ZeroBlobLength(1000), ...)

(See http://sqlite.org/lang_corefunc.html#zeroblob)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL