litesql

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: BSD-3-Clause Imports: 7 Imported by: 0

README

litesql

The litesql Go library provides a convenient interface for working with SQLite3 in Go programs, so that they are reliable and performant, by making use of reasonable defaults and providing an easy API to build on top of.

Documentation

Overview

Package litesql implements a SQLite3 interface with reasonable defaults, making interacting with sqlite3 databases easy, reliable, and performant in Go programs.

Index

Constants

View Source
const (
	// ExpectAnything indicates there is no expectation for the number of
	// rows that will be updated as a result of executing a statement.
	ExpectAnything = -(iota + 1)

	// ExpectNonZero indicates the expectation for the number of rows that will
	// be updated is non-zero.
	ExpectNonZero

	// ExpectOneOrZero indicates the expectation for the number of rows that
	// will be updated is exactly 0 or 1 (e.g. insert or ignore)
	ExpectOneOrZero
)
View Source
const (
	// ExecFailure is a sentinel value used when an Exec statement did not
	// complete correctly and we have no resulting row ID.
	ExecFailure = -1
)

Variables

View Source
var (
	// ReadConsistency provides options for general use transactional reads.
	//
	// Do not modify unless you are fully aware of the consequences.
	ReadConsistency = &sql.TxOptions{
		ReadOnly:  true,
		Isolation: sql.LevelReadCommitted,
	}

	// WriteConsistency provides options for general use transactional writes.
	//
	// Do not modify unless you are fully aware of the consequences.
	WriteConsistency = &sql.TxOptions{
		ReadOnly:  false,
		Isolation: sql.LevelWriteCommitted,
	}
)
View Source
var TypicalConfiguration = &Configuration{
	Mode:               "rwc",
	Encoding:           "utf8",
	BusyTimeout:        5000,
	TransactionLock:    "immediate",
	ForeignKeys:        true,
	JournalMode:        "WAL",
	CacheSize:          -65536,
	AutoVacuum:         "incremental",
	Synchronous:        "normal",
	MemoryMapSize:      67108864,
	MaxConnectionsOpen: 4,
}

TypicalConfiguration should be suitable for use by most applications, such as web servers, api servers, and other general purpose scenarios. In particular it sets these parameter values:

  • encoding: utf8
  • journal_mode: WAL
  • foreign_keys: true
  • transaction_lock: immediate
  • auto_vacuum: incremental
  • synchronous: normal
  • cache_size: 64 megabytes
  • mmap_size: 64 megabytes

Do not modify.

Functions

func QueryRow

func QueryRow[T any](ctx scope.C, tx *sql.Tx, scan func(ScanFunc) (T, error), stmt string, args ...any) (T, error)

QueryRow uses the given transaction tx and the scan function to extract a single row from the database, using the given stmnt query with args.

The scan function is provided by the caller for custom extraction of column values into some type T.

func QueryRows

func QueryRows[T any](ctx scope.C, tx *sql.Tx, scan func(ScanFunc) (T, error), stmt string, args ...any) ([]T, error)

QueryRows uses the given transaction tx and the scan function to extract a set of rows from the database, using the given stmnt query with args.

The scan function is provided by the caller for custom extraction of column values into some type T.

Types

type CloseFunc

type CloseFunc func()

CloseFunc should always be called before a transaction goes out of scope, even if the transaction has been committed (which turns into no-op).

type Configuration

type Configuration struct {
	// Mode configures the read/write/create capability.
	//
	// Use "rwc" for most use cases.
	Mode string

	// Encoding configures the encoding pragma. Value must be one of:
	//
	//  - UTF-8
	//  - UTF-16
	//  - UTF-16le
	//  - UTF-16be
	//
	// https://sqlite.org/pragma.html#pragma_encoding
	Encoding string

	// BusyTimeout configures the busy_timeout pragma. Value in milliseconds.
	//
	// https://sqlite.org/pragma.html#pragma_busy_timeout
	BusyTimeout int

	// TransactionLock configures the locking_mode pragma. Value must be one of:
	//
	//  - NORMAL
	//  - EXCLUSIVE
	//
	// https://sqlite.org/pragma.html#pragma_locking_mode
	TransactionLock string

	// ForeighKeys configures the foreign_keys pragma. Value must be one of:
	//
	//  - true
	//  - false
	//
	// https://sqlite.org/pragma.html#pragma_foreign_keys
	ForeignKeys bool

	// JournalMode configures the journal_mode pragma. Value must be one of:
	//
	//  - DELETE
	//  - TRUNCATE
	//  - PERSIST
	//  - MEMORY
	//  - WAL
	//  - OFF
	//
	// https://sqlite.org/pragma.html#pragma_journal_mode
	JournalMode string

	// CacheSize configures the cache_size pragma.
	//
	// When set to a positive value, the size is interpreted in pages.
	// When set to a negative value, the size is interpreted in kibibytes.
	//
	// e.g. 100 => 4kb page size * 100 => 400,000 bytes of memory
	// e.g. -2000 => 2048000 bytes of memory
	//
	// https://sqlite.org/pragma.html#pragma_cache_size
	CacheSize int

	// AutoVacuum configures the auto_vacuum pragma. Value must be one of:
	//
	//  - NONE
	//  - FULL
	//  - INCREMENTAL
	//
	// https://sqlite.org/pragma.html#pragma_auto_vacuum
	AutoVacuum string

	// Synchronous configures the synchronous pragma. Value must be one of:
	//
	//  - OFF
	//  - NORMAL
	//  - FULL
	//  - EXTRA
	//
	// https://sqlite.org/pragma.html#pragma_synchronous
	Synchronous string

	// MemoryMapSize configures the mmap_size pragma.
	//
	// Using mmap bypasses the kernel memory buffer, reducing the amount of
	// memory copying and syscall overhead. Understand the risks before using.
	//
	// Not used for in-memory databases.
	//
	// https://sqlite.org/pragma.html#pragma_mmap_size
	MemoryMapSize int

	// MaxConnectionsOpen configures the maximum number of concurrent users
	// of the database.
	MaxConnectionsOpen int
}

Configuration is the set of PRAGMA values and/or connection parameters used to configure the sqlite database.

Most general purpose applications such as web servers and api servers may want to start with the default values provided in TypicalConfiguration.

type ID

type ID int

type LiteDB

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

LiteDB is an interface over a sqlite3 database providing reasonable default values and an easy-to-use set of APIs for efficient and performant access.

func Open

func Open(filename string, config *Configuration) (*LiteDB, error)

Open the database of the given filename, using config to tune the PRAGMA values and connection string parameters.

func (*LiteDB) Close

func (ldb *LiteDB) Close() error

Close the underlying database.

func (*LiteDB) Exec

func (ldb *LiteDB) Exec(ctx scope.C, tx *sql.Tx, expectation int, stmt string, args ...any) error

Exec executes the given sql query statement with args, and compares the number of rows affected with the given expectation. An error is returned if the number of rows does not match the given expectation. The constant values ExpectAnything, ExpectNonZero, and ExpectOneOrZero can be used for more complex, but common expected behaviors.

func (*LiteDB) ExecID

func (ldb *LiteDB) ExecID(ctx scope.C, tx *sql.Tx, stmt string, args ...any) (ID, error)

ExecID executes the given sql query statement with args, and returns the resulting row id. The query must be intended to insert/modify exactly one row.

func (*LiteDB) Pragmas

func (ldb *LiteDB) Pragmas(ctx scope.C) (map[string]string, error)

Pragmas will query the database for the common set of PRAGMA values, so that one may look at them in all their magnificent glory.

func (*LiteDB) QueryRow

func (ldb *LiteDB) QueryRow(ctx scope.C, tx *sql.Tx, stmt string, args ...any) *sql.Row

QueryRow executes the given sql query statement with the expectation of returning exactly one row.

func (*LiteDB) QueryRows

func (ldb *LiteDB) QueryRows(ctx scope.C, tx *sql.Tx, stmt string, args ...any) (*sql.Rows, CloseFunc, error)

QueryRows executes the given sql query statement with the expectation of returning any number of rows.

Must call the returned CloseFunc when finished; otherwise a connection will be consumed and not returned to the connection pool, causing future operations to hang indefinitely.

func (*LiteDB) StartRead

func (ldb *LiteDB) StartRead(ctx scope.C) (*sql.Tx, CloseFunc, error)

StartRead creates a transaction useful for reading from the database.

No need to call sql.Tx.Commit; allow the rollback to close the transaction.

The sql.Tx must not be used for writing.

The CloseFunc must be called when done with the transaction.

func (*LiteDB) StartWrite

func (ldb *LiteDB) StartWrite(ctx scope.C) (*sql.Tx, CloseFunc, error)

StartWrite creates a transaction useful for writing to the database.

Must call sql.Tx.Commit to complete the transaction.

The sql.Tx may be used for reading and/or writing. Note that using a write transaction just for reading will be slower than a read only transaction.

The CloseFunc must be called when done with the transaction.

type ScanFunc

type ScanFunc func(args ...any) error

ScanFunc represents the sql.Scan function from a sql.Rows object. This is used as the scan argument of the QueryRows package function, invoked on each element in the result set of the query to build the list of resulting items.

Directories

Path Synopsis
Package libsqltest enables convenient testing with a real sqlite3 database backed by memory for use in unit tests.
Package libsqltest enables convenient testing with a real sqlite3 database backed by memory for use in unit tests.

Jump to

Keyboard shortcuts

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