sqlite

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MPL-2.0 Imports: 16 Imported by: 0 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 sqlite keeps events and projections in SQLite: an event store, a projection store and an automation store that share one database file, or one in-memory database.

It needs no server, which suits local development, tutorials and tests that need real transactions, and it serves single-process production services as well (WAL mode, replicated with a tool such as Litestream). Use Postgres or KurrentDB when several processes share the log.

Open a database with Open and apply Schema:

db, err := sqlite.Open("events.db") // or ":memory:"
if err != nil {
	return err
}
if _, err := db.ExecContext(ctx, sqlite.Schema); err != nil {
	return err
}
store := sqlite.NewEventStore(db)

The driver is modernc.org/sqlite, which is pure Go, so no C toolchain is needed.

One connection

Open limits the database to one connection, so writers never meet SQLITE_BUSY and an in-memory database is one database rather than one per connection. Every call therefore runs alone, which has one consequence for projections: a handler runs inside the projection store's transaction and must write through Tx. A handler that uses the *sql.DB directly waits for a connection that its own batch holds, and never returns.

Index

Constants

This section is empty.

Variables

View Source
var Schema string

Schema creates every table the package uses: the events table of EventStore, the segment and dead-letter tables of ProjectionStore, and the three tables of AutomationStore: automation_segments, automation_controls and automation_instances. It is idempotent; run it with your migrations, or once at startup. The same SQL ships as schema.sql in this package's directory.

Schema has the tables as this release uses them, and only creates what is missing: it adds no column to a table an earlier release created. The changelog lists the ALTER TABLE statements to run when upgrading.

Functions

func Import

func Import(ctx context.Context, src eventsourcing.GlobalReader, dst *EventStore) (int, error)

Import copies every event src holds into dst, in global order, keeping each event's ID, stream, order within its stream, metadata and time. It returns the number of events copied.

It moves a log from another store to SQLite: src is any eventsourcing.GlobalReader, so the memory, Postgres and KurrentDB stores and another SQLite database all serve as a source. Run it from the program that defines the events, after registering them with eventsourcing.RegisterEvent, since reading src decodes every event. dst should be empty: an event whose stream position is already taken in dst fails the import with a eventsourcing.StreamRevisionConflictError, and the events copied before it stay.

Global positions are assigned anew by dst, so they match src's only when src's positions start at 1 without gaps.

func Open

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

Open opens the SQLite database at path, creating the file if it does not exist; ":memory:" opens a database that lives as long as the returned *sql.DB. It limits the pool to one connection (see the package docs), turns on foreign keys, and for a file uses WAL journaling, begins every transaction with the write lock, and waits up to five seconds for a lock held by another process.

func Tx

func Tx(ctx context.Context) *sql.Tx

Tx returns the transaction a projection.Runner opened for the batch being processed under ctx. Handlers and reset functions write the read model through it, so their writes commit together with the checkpoint.

A handler must not use the *sql.DB itself: with the one connection Open allows, the batch's transaction holds it; see the package docs.

Tx panics if ctx carries no transaction, which means it was called outside a projection that uses ProjectionStore: a wiring mistake, not a condition to handle at run time.

Types

type AutomationStore added in v0.6.0

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

AutomationStore is the SQLite automation.Store. It keeps which instance holds each segment of an automation, and the segment's pauses, in the automation_segments table; whether the automation is paused in automation_controls; and what each instance last reported in automation_instances. Schema creates all three. Create the store with NewAutomationStore and pass it as automation.Definition.Store.

Every process that opens the same database file shares the leases, so a segment is worked by one process at a time. Time is SQLite's clock, in milliseconds.

func NewAutomationStore added in v0.6.0

func NewAutomationStore(db *sql.DB) *AutomationStore

NewAutomationStore returns an AutomationStore on db, which must hold the tables Schema creates. Open db with Open.

func (*AutomationStore) Acquire added in v0.6.0

func (s *AutomationStore) Acquire(ctx context.Context, name, owner string, candidates []automation.Segment, max int, ttl time.Duration) (automation.AcquireResult, error)

Acquire implements automation.Store. It runs in one transaction, which holds SQLite's write lock: it records the candidates, reads them in fairness order, and grants the first eligible ones.

func (*AutomationStore) Defer added in v0.6.0

func (s *AutomationStore) Defer(ctx context.Context, name, key string, d time.Duration) error

Defer implements automation.Store. It records key if it is new, and keeps a longer pause that is already set.

func (*AutomationStore) DeferredFor added in v0.6.0

func (s *AutomationStore) DeferredFor(ctx context.Context, name, key string) (time.Duration, error)

DeferredFor implements automation.Store.

func (*AutomationStore) LoadSegments added in v0.6.0

func (s *AutomationStore) LoadSegments(ctx context.Context, name string) ([]automation.SegmentState, error)

LoadSegments implements automation.Store.

func (*AutomationStore) LoadStatuses added in v0.6.0

func (s *AutomationStore) LoadStatuses(ctx context.Context, name string) ([]automation.Status, error)

LoadStatuses implements automation.Store.

func (*AutomationStore) Paused added in v0.6.0

func (s *AutomationStore) Paused(ctx context.Context, name string) (bool, error)

Paused implements automation.Store.

func (*AutomationStore) Release added in v0.6.0

Release implements automation.Store. Each release is fenced on owner and epoch; a lost one changes nothing.

func (*AutomationStore) Renew added in v0.6.0

Renew implements automation.Store. A lease is renewed only while its owner and epoch are current and it has not expired.

func (*AutomationStore) SaveStatus added in v0.6.0

func (s *AutomationStore) SaveStatus(ctx context.Context, name string, st automation.Status, ttl time.Duration) error

SaveStatus implements automation.Store. It also deletes the name's expired statuses, so instances that stopped do not pile up.

func (*AutomationStore) SetPaused added in v0.6.0

func (s *AutomationStore) SetPaused(ctx context.Context, name string, paused bool) error

SetPaused implements automation.Store.

type EventStore

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

EventStore is a SQLite-backed eventsourcing.EventStore that also implements eventsourcing.GlobalReader. The events table's id column is the GlobalPosition that EventStore.ReadAll orders by. Create one with NewEventStore.

SQLite lets one writer at a time commit, and a writer holds its lock from the first insert until it commits, so ids become visible in the order they were assigned, also with several processes on one file. ReadAll needs no visibility filter.

func NewEventStore

func NewEventStore(db *sql.DB) *EventStore

NewEventStore returns an EventStore on db, which must hold the tables Schema creates. Open db with Open.

func (*EventStore) Close

func (s *EventStore) Close() error

Close does nothing: the *sql.DB belongs to the caller, who may share it with a ProjectionStore, and closes it when done.

func (*EventStore) Head

func (s *EventStore) Head(ctx context.Context) (uint64, error)

Head implements eventsourcing.GlobalReader: the highest id in the events table, or 0 if it is empty.

func (*EventStore) LoadCorrelation added in v0.5.0

LoadCorrelation implements eventsourcing.CorrelationLoader, using the index on correlation_id. Like EventStore.LoadStream, it reads the events in full before it returns.

func (*EventStore) LoadStream

LoadStream returns an iterator over all events in the stream identified by id, in the order they were appended. It returns an error wrapping eventsourcing.ErrStreamNotFound if the stream does not exist.

The events are read in full before LoadStream returns, so the one connection is free again while the caller iterates.

func (*EventStore) LoadStreamFrom

LoadStreamFrom returns an iterator over the events in the stream identified by id, starting after the position identified by version. eventsourcing.NoStream requires the stream not to exist; eventsourcing.StreamExists requires that it does; eventsourcing.Any reads from the beginning of the stream. A eventsourcing.Revision of n returns the events after the n-th, so a caller that has processed n events resumes where it left off.

func (*EventStore) ReadAll

ReadAll implements eventsourcing.GlobalReader. Filters run in SQL, on exact event type names and on stream ID prefixes (compared with substr, so % and _ in a prefix are not wildcards).

func (*EventStore) Save

Save appends events to the stream they share, enforcing the concurrency check described by revision: eventsourcing.Any skips it, eventsourcing.NoStream requires the stream not to exist yet, eventsourcing.StreamExists requires that it already does, and a eventsourcing.Revision requires the stream's current length to match exactly. All events must have the same StreamID, or Save returns an error without appending anything. The append runs in one transaction; on a revision mismatch it returns a eventsourcing.StreamRevisionConflictError and nothing is persisted.

On success it returns a eventsourcing.AppendResult whose NextExpectedVersion is the stream's new length and whose GlobalPosition is the id of the last event appended.

type ProjectionStore

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

ProjectionStore is the SQLite projection.Store. Create it with NewProjectionStore.

Each Commit and Reset runs in one transaction, so the read model's writes and the checkpoint move land together, and every call that takes a projection.Lease is fenced by a conditional update on owner and epoch.

func NewProjectionStore

func NewProjectionStore(db *sql.DB) *ProjectionStore

NewProjectionStore returns a ProjectionStore on db, which must hold the tables Schema creates and the read model's tables. Open db with Open.

func (*ProjectionStore) Claim

Claim implements projection.Store. A refresh of the current claim keeps its epoch; a takeover raises it. On the right-hand side of SET, owner and epoch are the row's values before the update, and WHERE judges expiry by the current claim's own ttl_ms.

func (*ProjectionStore) Commit

Commit implements projection.Store. It runs fn and the checkpoint update in one transaction; the update only applies while l is the current claim, and otherwise the transaction rolls back.

func (*ProjectionStore) Declare

func (s *ProjectionStore) Declare(ctx context.Context, name string, segments int, replayUntil uint64) error

Declare implements projection.Store: it creates the segment rows for name on first use, and verifies the count has not changed since.

func (*ProjectionStore) DeleteDeadLetter

func (s *ProjectionStore) DeleteDeadLetter(ctx context.Context, l projection.Lease, position uint64) error

DeleteDeadLetter implements projection.DeadLetterStore. It is called inside the Commit that applies the event again.

func (*ProjectionStore) FailRebuild added in v0.5.0

func (s *ProjectionStore) FailRebuild(ctx context.Context, l projection.Lease, requested uint64, errMsg string) error

FailRebuild implements projection.Store, fenced on l in the same transaction.

func (*ProjectionStore) FinishReplay added in v0.4.0

func (s *ProjectionStore) FinishReplay(ctx context.Context, l projection.Lease, number uint64, errMsg string) error

FinishReplay implements projection.DeadLetterStore, fenced on l in the same transaction.

func (*ProjectionStore) Heartbeat added in v0.4.0

func (s *ProjectionStore) Heartbeat(ctx context.Context, name, owner string, version int, ttl time.Duration) ([]projection.Instance, error)

Heartbeat implements projection.Store, in one transaction that upserts owner's row, deletes the rows whose own ttl has passed, and reads the live ones with the number of segments each one claims.

func (*ProjectionStore) LoadDeadLetters

func (s *ProjectionStore) LoadDeadLetters(ctx context.Context, name string, segment int) ([]projection.DeadLetter, error)

LoadDeadLetters implements projection.DeadLetterStore.

func (*ProjectionStore) LoadInstances added in v0.4.0

func (s *ProjectionStore) LoadInstances(ctx context.Context, name string) ([]projection.Instance, error)

LoadInstances implements projection.Store: it reads the rows whose own ttl has not passed, with the number of segments each one claims.

func (*ProjectionStore) LoadStatuses

func (s *ProjectionStore) LoadStatuses(ctx context.Context, name string) ([]projection.Status, error)

LoadStatuses implements projection.Store.

func (*ProjectionStore) PendingReplays added in v0.4.0

func (s *ProjectionStore) PendingReplays(ctx context.Context, name string) ([]projection.Replay, error)

PendingReplays implements projection.DeadLetterStore.

func (*ProjectionStore) RebuildFailure added in v0.5.0

func (s *ProjectionStore) RebuildFailure(ctx context.Context, name string) (failed uint64, errMsg string, err error)

RebuildFailure implements projection.Store.

func (*ProjectionStore) Rebuilds added in v0.3.0

func (s *ProjectionStore) Rebuilds(ctx context.Context, name string) (requested, done uint64, err error)

Rebuilds implements projection.Store.

func (*ProjectionStore) Release

func (s *ProjectionStore) Release(ctx context.Context, l projection.Lease) error

Release implements projection.Store.

func (*ProjectionStore) ReplayResult added in v0.4.0

func (s *ProjectionStore) ReplayResult(ctx context.Context, name string, number uint64) (int, []string, error)

ReplayResult implements projection.DeadLetterStore.

func (*ProjectionStore) RequestRebuild added in v0.3.0

func (s *ProjectionStore) RequestRebuild(ctx context.Context, name string) (uint64, error)

RequestRebuild implements projection.Store.

func (*ProjectionStore) RequestReplay added in v0.4.0

func (s *ProjectionStore) RequestReplay(ctx context.Context, name, streamID string) (uint64, error)

RequestReplay implements projection.DeadLetterStore, in one transaction that records the request and a row for each segment holding dead letters of streamID. A stream without dead letters records nothing and gets 0.

func (*ProjectionStore) Reset

func (s *ProjectionStore) Reset(ctx context.Context, l projection.Lease, newVersion int, wipe func(ctx context.Context) error) error

Reset implements projection.Store, in one transaction fenced like Commit. The transaction holds the database's write lock, so Commits run before or after it, never during. On the right-hand side of SET, position and owner are the row's values before the update.

func (*ProjectionStore) SaveDeadLetter

SaveDeadLetter implements projection.DeadLetterStore. It is called inside the Commit that moves the checkpoint past the event.

func (*ProjectionStore) SaveStatus

func (s *ProjectionStore) SaveStatus(ctx context.Context, l projection.Lease, status projection.Status) error

SaveStatus implements projection.Store.

Jump to

Keyboard shortcuts

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