sql

package
v0.0.0-...-ecee8c2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sql is the SQL port of platform: SQLite in the embedded profile and Postgres in the cloud profile, selected by URL (ADR-0004). Migrations come from an fs.FS (typically embed.FS). Repository code built on this store is expected to read the tenant from context (REQ-SQL-010 through REQ-SQL-012); this package does not enforce tenancy by itself.

URLs

Open accepts sqlite://… and postgres://… URLs. The legacy postgresql scheme and any other scheme are invalid_argument. SQLite forms include sqlite:///absolute/path, sqlite://relative/path, sqlite://host/path (RFC 3986 host plus path, for example sqlite://data/kit.db), and sqlite://:memory: or sqlite:///:memory:. A relative path is resolved against the working directory. Query and fragment on SQLite URLs are rejected. The path :memory: is never passed through filepath.Abs. Postgres URLs must include a database path; otherwise nothing is created.

Migrations and locking

Concurrent opens run migrations under an advisory flock on <dbpath>.migrate.lock beside the database for SQLite; schema version is checked again inside that critical section, then goose runs. On Postgres, a session pg_advisory_lock on one dedicated pool connection is held for the whole migrate and schema version is re-checked under that lock. A schema version newer than the migration set's newest file is refused with unsupported before anything is written.

SQLite files and DSN

New SQLite database files are created mode 0600; missing parent directories are created mode 0700 (existing directories are not chmodded). The SQLite driver DSN sets busy_timeout before journal_mode=WAL, foreign_keys, and _txlock=immediate, matching the embedded Temporal store.

Errors

Operations return *core.Error with fixed messages. Driver and vendor text is not forwarded in messages or details; stable codes such as SQLSTATE or SQLite result codes may appear in details. Connection refused, DNS failure, or timeout while opening map to unavailable with Retryable true. Postgres serialization failure and deadlock (40001, 40P01), connection and resource classes (08xxx, 53xxx, 57P01), and SQLite SQLITE_BUSY / SQLITE_LOCKED map to unavailable with Retryable true. Unique and foreign-key violations map to conflict; not-null and check violations map to invalid_argument. Store.ParsedURLRedacted and error details replace the userinfo password and the values of the credential query parameters (password, sslpassword, passfile, sslcert, sslkey, sslrootcert) with the literal ***. When the URL carried any of them, driver text is replaced by the fixed cause "driver error withheld". MapError applies the same mapping to a driver error taken straight from database/sql row iteration, which bypasses Execer and Row; repository code calls it on database/sql.Rows.Scan and database/sql.Rows.Err results.

Transactions and SQL

Store.InTx rejects a nested InTx on the same store when fn uses the ctx InTx provides. Execer documents the ? placeholder contract on both dialects. TextOrderClause takes a simple SQL identifier for the column name.

Postgres ?-to-$n scanning follows the dialect lexer for strings, comments, and dollar quotes, including standard single-quote rules for U&'…' strings; plain single-quoted strings always assume standard_conforming_strings = on. Jsonb operators ?, ?|, and ?& are out of contract for SQL passed through the store.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExcludeMigrationVersion

func ExcludeMigrationVersion(all fs.FS, ver int) (fs.FS, error)

ExcludeMigrationVersion drops one migration version from the set.

func FilterMigrations

func FilterMigrations(all fs.FS, maxVer int) (fs.FS, error)

FilterMigrations returns an fs.FS containing only migrations with version <= maxVer.

func MapError

func MapError(err error) error

MapError maps a driver error to the same core error Execer and Row return. Platform code calls it on errors that come straight from database/sql row iteration (Rows.Scan, Rows.Err): those bypass Execer.Query, so an unmapped driver error would reach callers with the wrong code and driver text.

func TextOrderClause

func TextOrderClause(dialectName, col string) (string, error)

TextOrderClause returns an ORDER BY column expression with dialect collation (REQ-SQL-017). col must be a simple identifier matching [A-Za-z_][A-Za-z0-9_]*; otherwise invalid_argument. On Postgres the result appends COLLATE "C"; on SQLite it appends COLLATE BINARY.

func TruncateMicrosecond

func TruncateMicrosecond(t time.Time) time.Time

TruncateMicrosecond converts to UTC and truncates to whole microseconds (REQ-SQL-016).

func ValidateText

func ValidateText(s string) error

ValidateText rejects strings that contain a NUL byte (REQ-SQL-018).

Types

type Execer

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

Execer runs SQL with dialect-correct placeholders for either the pool or an active transaction when created by Store.InTx. Repository SQL uses ? on both dialects; on Postgres each ? outside single- and double-quoted text, line and block comments, and dollar-quoted bodies becomes $n in order. Authored $n markers are rejected with invalid_argument. Any ? outside those regions is a bind marker, so Postgres jsonb operators ?, ?|, and ?& cannot appear in SQL; use jsonb_exists, jsonb_exists_any, and jsonb_exists_all instead. A driver.Valuer bind argument is converted once for this check and once by database/sql, so Valuers must be side-effect free.

func (*Execer) Exec

func (e *Execer) Exec(ctx context.Context, q string, args ...any) (sql.Result, error)

Exec runs q with args rewritten for the store dialect. String arguments must not contain NUL (REQ-SQL-018). Driver errors are mapped by mapExecErr.

func (*Execer) Query

func (e *Execer) Query(ctx context.Context, q string, args ...any) (*sql.Rows, error)

Query runs a read query on the pool or transaction, rejecting NUL in string arguments.

func (*Execer) QueryRow

func (e *Execer) QueryRow(ctx context.Context, q string, args ...any) *Row

QueryRow runs a single-row read, rejecting NUL in string arguments before touching the database.

type Row

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

Row holds the result of Execer.QueryRow; Scan reads the row and maps driver errors.

func (*Row) Scan

func (r *Row) Scan(dest ...any) error

Scan reads one row and maps driver errors.

type Store

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

Store is an opened SQL database with migrations applied.

func Open

func Open(ctx context.Context, rawURL string, migrations fs.FS) (*Store, error)

Open parses rawURL, connects, applies migrations from migrations, and returns a Store. See package documentation for supported URL forms, migration locking, SQLite file modes, and error mapping during open and migrate.

func (*Store) Close

func (s *Store) Close() error

Close releases the database.

func (*Store) Dialect

func (s *Store) Dialect() string

Dialect reports sqlite or postgres.

func (*Store) Execer

func (s *Store) Execer() *Execer

Execer returns the query layer for the store.

func (*Store) InTx

func (s *Store) InTx(ctx context.Context, fn func(ctx context.Context, exec *Execer) error) (err error)

InTx runs fn inside one transaction on this store. The transaction rolls back when fn returns an error or panics, and commits only when fn returns nil. A nested InTx on the same store returns invalid_argument when fn passes the ctx InTx injects into each InTx on that store; passing a different ctx will not see the marker and can deadlock on SQLite (one connection). Different stores may nest independently.

func (*Store) ParsedURLRedacted

func (s *Store) ParsedURLRedacted() string

ParsedURLRedacted returns the store URL with userinfo and credential query parameters (password, sslpassword, and other libpq secret keys) replaced for safe logging and errors.

func (*Store) SchemaVersion

func (s *Store) SchemaVersion(ctx context.Context) (int64, error)

SchemaVersion returns the newest applied goose migration version, or zero when none apply.

Jump to

Keyboard shortcuts

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