driver

package
v0.49.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Overview

Example (NamedDriverAccess)

Example_namedDriverAccess demonstrates that all three Open helpers use the same registered driver name and produce a working *sql.DB.

package main

import (
	"database/sql"
	"fmt"

	tsqldriver "github.com/SimonWaldherr/tinySQL/driver"
)

func main() {
	db, err := sql.Open(tsqldriver.DriverName, "mem://?tenant=named_test")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer db.Close()

	if err := db.Ping(); err != nil {
		fmt.Println("ping error:", err)
		return
	}
	fmt.Println("driver name:", tsqldriver.DriverName)
	fmt.Println("ping: ok")

}
Output:
driver name: tinysql
ping: ok

Index

Examples

Constants

View Source
const DriverName = "tinysql"

DriverName is the registered database/sql driver name for tinySQL.

Variables

View Source
var ErrTransactionConflict = id.ErrTransactionConflict

ErrTransactionConflict indicates a retryable optimistic-concurrency conflict while committing a transaction. Use errors.Is to check it.

Functions

func CurrentDefaultDB added in v0.14.0

func CurrentDefaultDB() *tinysql.DB

CurrentDefaultDB returns the public tinySQL database currently backing the driver's default server, if one exists.

func Open

func Open(dsn string) (*sql.DB, error)

Open is a convenience wrapper around `sql.Open(DriverName, dsn)`.

Example

ExampleOpen demonstrates opening a tinySQL in-memory database via database/sql.

package main

import (
	"fmt"

	tsqldriver "github.com/SimonWaldherr/tinySQL/driver"
)

func main() {
	db, err := tsqldriver.Open("mem://?tenant=default")
	if err != nil {
		fmt.Println("open error:", err)
		return
	}
	defer db.Close()

	if _, err := db.Exec(`CREATE TABLE products (id INT, name TEXT, price FLOAT)`); err != nil {
		fmt.Println("create error:", err)
		return
	}
	if _, err := db.Exec(`INSERT INTO products VALUES (?, ?, ?)`, 1, "Widget", 9.99); err != nil {
		fmt.Println("insert error:", err)
		return
	}

	var name string
	var price float64
	row := db.QueryRow(`SELECT name, price FROM products WHERE id = ?`, 1)
	if err := row.Scan(&name, &price); err != nil {
		fmt.Println("scan error:", err)
		return
	}
	fmt.Printf("%s: $%.2f\n", name, price)

}
Output:
Widget: $9.99
Example (Transaction)

ExampleOpen_transaction demonstrates wrapping multiple operations in a database/sql transaction.

package main

import (
	"context"
	"fmt"

	tsqldriver "github.com/SimonWaldherr/tinySQL/driver"
)

func main() {
	db, err := tsqldriver.Open("mem://?tenant=txdemo")
	if err != nil {
		fmt.Println("open error:", err)
		return
	}
	defer db.Close()

	if _, err := db.Exec(`CREATE TABLE accounts (id INT, balance FLOAT)`); err != nil {
		fmt.Println("create error:", err)
		return
	}
	if _, err := db.Exec(`INSERT INTO accounts VALUES (1, 1000.0)`); err != nil {
		fmt.Println("insert error:", err)
		return
	}
	if _, err := db.Exec(`INSERT INTO accounts VALUES (2, 500.0)`); err != nil {
		fmt.Println("insert error:", err)
		return
	}

	ctx := context.Background()
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		fmt.Println("begin error:", err)
		return
	}

	if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance = balance - ? WHERE id = ?`, 200.0, 1); err != nil {
		_ = tx.Rollback()
		fmt.Println("update error:", err)
		return
	}
	if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance = balance + ? WHERE id = ?`, 200.0, 2); err != nil {
		_ = tx.Rollback()
		fmt.Println("update error:", err)
		return
	}
	if err := tx.Commit(); err != nil {
		fmt.Println("commit error:", err)
		return
	}

	rows, err := db.Query(`SELECT id, balance FROM accounts ORDER BY id`)
	if err != nil {
		fmt.Println("query error:", err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var id int
		var bal float64
		if err := rows.Scan(&id, &bal); err != nil {
			fmt.Println("scan error:", err)
			return
		}
		fmt.Printf("account %d: %.0f\n", id, bal)
	}

}
Output:
account 1: 800
account 2: 700

func OpenFile

func OpenFile(path string) (*sql.DB, error)

OpenFile is a convenience wrapper that opens a file-backed tinySQL database by constructing a `file:` DSN for `sql.Open`.

func OpenInMemory

func OpenInMemory(tenant string) (*sql.DB, error)

OpenInMemory returns a database/sql handle backed by an in-memory tinySQL server. If tenant is empty, the default tenant is used.

Example

ExampleOpenInMemory demonstrates the OpenInMemory convenience helper.

package main

import (
	"fmt"

	tsqldriver "github.com/SimonWaldherr/tinySQL/driver"
)

func main() {
	db, err := tsqldriver.OpenInMemory("demo")
	if err != nil {
		fmt.Println("open error:", err)
		return
	}
	defer db.Close()

	if _, err := db.Exec(`CREATE TABLE kv (k TEXT, v TEXT)`); err != nil {
		fmt.Println("create error:", err)
		return
	}
	if _, err := db.Exec(`INSERT INTO kv VALUES (?, ?)`, "hello", "world"); err != nil {
		fmt.Println("insert error:", err)
		return
	}

	var v string
	if err := db.QueryRow(`SELECT v FROM kv WHERE k = ?`, "hello").Scan(&v); err != nil {
		fmt.Println("scan error:", err)
		return
	}
	fmt.Println(v)

}
Output:
world

func OpenWithConfig added in v0.10.0

func OpenWithConfig(ctx context.Context, cfg OpenConfig) (*sql.DB, error)

OpenWithConfig opens a tinySQL database using explicit settings and validates connectivity with PingContext.

Example

ExampleOpenWithConfig demonstrates config-driven setup with explicit pool and timeout settings, then executes a query via database/sql.

package main

import (
	"context"
	"fmt"
	"time"

	tsqldriver "github.com/SimonWaldherr/tinySQL/driver"
)

func main() {
	cfg := tsqldriver.DefaultOpenConfig()
	cfg.Tenant = "example"
	cfg.PoolReaders = 2
	cfg.BusyTimeout = 100 * time.Millisecond
	cfg.MaxOpenConns = 4
	cfg.MaxIdleConns = 2
	cfg.PingTimeout = 3 * time.Second

	ctx := context.Background()
	db, err := tsqldriver.OpenWithConfig(ctx, cfg)
	if err != nil {
		fmt.Println("open error:", err)
		return
	}
	defer db.Close()

	if _, err := db.ExecContext(ctx, `CREATE TABLE notes (id INT, body TEXT)`); err != nil {
		fmt.Println("create error:", err)
		return
	}
	if _, err := db.ExecContext(ctx, `INSERT INTO notes VALUES (?, ?)`, 1, "hello tinySQL"); err != nil {
		fmt.Println("insert error:", err)
		return
	}

	rows, err := db.QueryContext(ctx, `SELECT id, body FROM notes ORDER BY id`)
	if err != nil {
		fmt.Println("query error:", err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var id int
		var body string
		if err := rows.Scan(&id, &body); err != nil {
			fmt.Println("scan error:", err)
			return
		}
		fmt.Printf("%d: %s\n", id, body)
	}
	if err := rows.Err(); err != nil {
		fmt.Println("rows error:", err)
	}

}
Output:
1: hello tinySQL

func OpenWithDB

func OpenWithDB(db *tinysql.DB) (*sql.DB, error)

OpenWithDB registers the provided public tinySQL database as the driver's default DB and returns a *sql.DB connected to it. This is useful for embedding or tests without exposing an internal/storage type in the public driver contract.

func SetDefaultDB

func SetDefaultDB(db *tinysql.DB)

SetDefaultDB selects the public tinySQL database used by subsequently opened default driver connections. It is primarily intended for embedding and tests; ordinary applications should prefer OpenWithConfig.

Types

type OpenConfig added in v0.10.0

type OpenConfig struct {
	// Mode controls DSN scheme. Allowed values: "mem" (default) or "file".
	Mode string
	// FilePath is required when Mode is "file".
	FilePath string
	// Tenant maps to DSN option `tenant`. Empty falls back to "default".
	Tenant string
	// Autosave maps to DSN option `autosave=1` for file mode.
	Autosave bool
	// PoolReaders maps to DSN option `pool_readers`.
	PoolReaders int
	// PoolWriters maps to DSN option `pool_writers`.
	PoolWriters int
	// BusyTimeout maps to DSN option `busy_timeout` (e.g. 250ms, 2s).
	BusyTimeout time.Duration
	// StorageMode selects the persistent backend: memory, wal, disk, index,
	// hybrid, advanced_wal, json, paged_index, or sqlite. Empty preserves the
	// legacy file/memory behavior.
	StorageMode string
	// MaxMemoryBytes bounds hybrid/index caches. Zero uses the backend default.
	MaxMemoryBytes int64
	// ReadOnly opens an existing immutable artifact without creating files.
	ReadOnly bool
	// SyncOnMutate flushes disk-backed table mutations immediately.
	SyncOnMutate bool
	// CompressFiles compresses supported table/checkpoint files.
	CompressFiles bool
	// CheckpointEvery and CheckpointInterval control WAL checkpoint cadence.
	CheckpointEvery    uint64
	CheckpointInterval time.Duration
	// CheckpointMaxBytes triggers a checkpoint by WAL size. Zero uses the
	// backend default; -1 disables the size trigger.
	CheckpointMaxBytes int64
	// WALSync is "full" (strongest/default) or "normal" (lower latency).
	WALSync string
	// PersistDebounce coalesces legacy file autosaves. It trades a bounded
	// durability window for higher ingestion throughput.
	PersistDebounce time.Duration

	// database/sql pool settings.
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration

	// PingTimeout is used for startup health-check in OpenWithConfig.
	PingTimeout time.Duration
}

OpenConfig describes connection, DSN and database/sql settings for OpenWithConfig.

Best-practice split:

  • DSN fields configure tinySQL driver/server behavior (tenant, autosave, pools, busy_timeout).
  • database/sql fields configure connection pool behavior (max open/idle/lifetimes).
  • PingTimeout validates startup connectivity with PingContext.

func DefaultOpenConfig added in v0.10.0

func DefaultOpenConfig() OpenConfig

DefaultOpenConfig returns sensible defaults for tinySQL.

func EmbeddedToolOpenConfig added in v0.48.0

func EmbeddedToolOpenConfig(path string) OpenConfig

EmbeddedToolOpenConfig returns an ACID WAL profile for replacing a remote SQL dependency in a single-process Go tool. One writer matches tinySQL's serialized mutation path; several readers preserve concurrent queries.

func OfflineNavigationOpenConfig added in v0.48.0

func OfflineNavigationOpenConfig(path string) OpenConfig

OfflineNavigationOpenConfig returns a read-only, bounded-memory profile for a prebuilt routing/map artifact. ROUTE_WARM should be called at application startup to move graph construction before the first navigation request.

func RAGOpenConfig added in v0.48.0

func RAGOpenConfig(path string) OpenConfig

RAGOpenConfig returns a bounded hybrid-storage profile for vector, FTS and hybrid retrieval. RAG_WARM can populate both retrieval structures after opening or after a corpus update.

func (OpenConfig) DSN added in v0.10.0

func (c OpenConfig) DSN() (string, error)

DSN builds a tinySQL DSN from OpenConfig.

Jump to

Keyboard shortcuts

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