store

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: CC0-1.0 Imports: 21 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 store provides SQLite connections and persistence primitives.

Index

Constants

View Source
const (
	// ExportFormat identifies Taskronin's portable JSON export format.
	ExportFormat = "taskronin-export"
	// ExportVersion is the version of the export envelope.
	ExportVersion = 1
)

Variables

View Source
var (
	// ErrSchemaTooNew indicates an applied migration absent from this binary.
	ErrSchemaTooNew = errors.New("store: database schema is newer than this binary")
	// ErrChecksumMismatch indicates that an applied migration's bytes changed.
	ErrChecksumMismatch = errors.New("store: migration checksum mismatch")
)
View Source
var ErrIntegrity = errors.New("store: integrity check failed")

ErrIntegrity marks a consistency check that ran and reported damage (any result other than a single "ok"), as opposed to failing to run at all.

View Source
var ErrNotFound = errors.New("store: not found")

ErrNotFound indicates that a store query found no matching row.

View Source
var ExportSettings = []string{"backup_keep_daily", "backup_keep_weekly", "ai_reviewed_through"}

ExportSettings lists the settings included in portable exports.

View Source
var ExportTables = []string{"tasks", "task_triage", "tags", "task_tags", "log_entries", "time_blocks",
	"focus", "interruptions", "ops", "events", "undo_stack"}

ExportTables lists the tables included in portable exports.

Functions

func ActiveReversal

func ActiveReversal(ctx context.Context, q Q, target domain.OpID) (sql.Null[domain.OpRecord], error)

ActiveReversal returns the active operation reverting target, if one exists.

func AddReason

func AddReason(ctx context.Context, q Q, row domain.TriageRow) (bool, error)

AddReason adds a reason, preserving an existing row's since and sequence. It reports whether a new row was inserted.

func ApplyColumns

func ApplyColumns(ctx context.Context, q Q, ent domain.EntityKind, id int64, cols map[string]any) error

ApplyColumns restores allowed event-payload columns verbatim in one UPDATE. JSON integers retain their precision, booleans become 0/1, and nil writes NULL.

func AutoResolvedOn

func AutoResolvedOn(ctx context.Context, q Q, task domain.TaskID, d civil.Date) ([]domain.TimeBlock, error)

AutoResolvedOn returns live automatically resolved blocks of a task on d.

func BlocksBetween

func BlocksBetween(ctx context.Context, q Q, from, to civil.Date, task sql.Null[domain.TaskID]) ([]domain.TimeBlock, error)

BlocksBetween returns non-deleted blocks in an inclusive date range, optionally restricted to a task. Zero dates leave that side of the range unbounded.

func BlocksOfTask

func BlocksOfTask(ctx context.Context, q Q, task domain.TaskID) ([]domain.TimeBlock, error)

BlocksOfTask returns non-deleted blocks by date, start minute and ID.

func BootstrapDB

func BootstrapDB(ctx context.Context, q Q, b Bootstrap) (domain.TokenID, error)

BootstrapDB initializes a new database without recording operations or events. Callers supply a transaction when atomic initialization is required.

func BumpVersion

func BumpVersion(ctx context.Context, q Q, ref domain.EntityRef, now time.Time) error

BumpVersion increments a task, entry, block or focus version. Only tasks and entries have updated_at, which is set to now without changing other fields.

func ClearIdempotency

func ClearIdempotency(ctx context.Context, q Q) error

ClearIdempotency unconditionally deletes every stored request replay.

func ClearStack

func ClearStack(ctx context.Context, q Q, actor string, s Stack) error

ClearStack removes every row from the actor's selected stack.

func CompleteEntries

func CompleteEntries(ctx context.Context, q Q, task domain.TaskID) ([]domain.LogEntry, error)

CompleteEntries returns every completion entry, including deleted and purged rows, in ascending ID order.

func CountAIOps

func CountAIOps(ctx context.Context, q Q, afterSeq domain.OpSeq) (int, error)

CountAIOps counts token and retention-lowering operations strictly after afterSeq.

func CountEntriesOn

func CountEntriesOn(ctx context.Context, q Q, task domain.TaskID, d civil.Date) (work, complete int, err error)

CountEntriesOn counts non-deleted work and completion entries for a task/day.

func CountOpsSince

func CountOpsSince(ctx context.Context, q Q, actor string, since time.Time) (n int, oldest sql.Null[time.Time], err error)

CountOpsSince counts actor's operations strictly after since and returns their oldest time.

func DSN

func DSN(absPath string, p Pool) string

DSN builds an escaped SQLite file URI for an absolute path and pool. PoolStaging must only be used for new files or staged copies.

func DeleteAllSessions

func DeleteAllSessions(ctx context.Context, q Q) (int64, error)

DeleteAllSessions removes every session and returns the number deleted.

func DeleteExpiredSessions

func DeleteExpiredSessions(ctx context.Context, q Q, now time.Time, idle time.Duration) (int64, error)

DeleteExpiredSessions removes sessions at either absolute or idle expiry, inclusively.

func DeleteIdemBefore

func DeleteIdemBefore(ctx context.Context, q Q, before time.Time) (int64, error)

DeleteIdemBefore deletes records strictly older than before and returns the count.

func DeleteSession

func DeleteSession(ctx context.Context, q Q, idHash [32]byte) error

DeleteSession deletes the session with idHash, if present.

func DeleteStackRow

func DeleteStackRow(ctx context.Context, q Q, actor string, s Stack, seq int64) error

DeleteStackRow removes the specified actor/stack sequence, if present.

func EntriesOfTask

func EntriesOfTask(ctx context.Context, q Q, task domain.TaskID) ([]domain.LogEntry, error)

EntriesOfTask returns a task's non-deleted entries in the ListEntries order.

func EventsOfOp

func EventsOfOp(ctx context.Context, q Q, op domain.OpID) ([]domain.Event, error)

EventsOfOp returns an operation's events in ascending event ID order.

func ExportTable

func ExportTable(ctx context.Context, q Q, table string, fn func(row map[string]any) error) error

ExportTable streams an allowed table in primary-key order. Each callback gets a new column map containing only int64, string or nil values. Callback errors stop the stream and are returned unchanged.

func FTSIntegrityCheck

func FTSIntegrityCheck(ctx context.Context, q Q) error

FTSIntegrityCheck verifies both FTS indexes against their live content views. It issues FTS commands and therefore requires a writable Q.

func ForeignKeyCheck

func ForeignKeyCheck(ctx context.Context, q Q) error

ForeignKeyCheck fails if the database has any foreign key violation.

func GetBlock

func GetBlock(ctx context.Context, q Q, id domain.BlockID) (domain.TimeBlock, error)

GetBlock returns a block, including tombstoned rows.

func GetEntry

func GetEntry(ctx context.Context, q Q, id domain.EntryID) (domain.LogEntry, error)

GetEntry returns an entry, including tombstoned or purged rows.

func GetFocus

func GetFocus(ctx context.Context, q Q) (domain.Focus, error)

GetFocus returns the singleton focus row, initially empty with version 1.

func GetInterruption

func GetInterruption(ctx context.Context, q Q, id domain.InterruptionID) (domain.Interruption, error)

GetInterruption returns an interruption, including tombstoned rows.

func GetOp

func GetOp(ctx context.Context, q Q, id domain.OpID) (domain.OpRecord, error)

GetOp returns an operation, or ErrNotFound if its ID is absent.

func GetSetting

func GetSetting(ctx context.Context, q Q, key string) (string, error)

GetSetting returns a setting's value, or ErrNotFound for a missing key.

func GetTask

func GetTask(ctx context.Context, q Q, id domain.TaskID) (domain.Task, error)

GetTask returns a task, including tombstoned or purged rows.

func GetToken

func GetToken(ctx context.Context, q Q, id domain.TokenID) (domain.Token, error)

GetToken returns a token, including expired or revoked tokens.

func HasPlannedAfter

func HasPlannedAfter(ctx context.Context, q Q, task domain.TaskID, d civil.Date) (bool, error)

HasPlannedAfter reports whether a task has a live planned block strictly after d.

func HasPlannedOn

func HasPlannedOn(ctx context.Context, q Q, task domain.TaskID, d civil.Date) (bool, error)

HasPlannedOn reports whether a task has a live planned block on d.

func ImportData

func ImportData(ctx context.Context, q Q, in ImportIn) (map[string]int, error)

ImportData is A§12.5 step 4a-c in the caller's transaction on the staged store: file rows with their ids and sequence numbers preserved (known columns only), sequence marks raised to max(file, live), then the destination's bootstrap operations with fresh sequence numbers. Step d (the system.import op) is recorded afterwards through the service.

AIDEV-NOTE: SECURITY/PRECISION. Values arrive from json.Decoder.UseNumber: every INTEGER column is converted with strconv.ParseInt (no float64 hop, so ids above 2^53 survive; fractions, exponents and overflow are rejected). Table and column names that reach SQL come from PRAGMA table_info of the fixed importOrder tables, never from the file; unknown file keys are errors.

func InsertBlock

func InsertBlock(ctx context.Context, q Q, b *domain.TimeBlock) error

InsertBlock inserts b with a generated ID and version 1, assigning both on success.

func InsertEntry

func InsertEntry(ctx context.Context, q Q, e *domain.LogEntry) error

InsertEntry inserts e with a generated ID and version 1, assigning both on success.

func InsertEvent

func InsertEvent(ctx context.Context, q Q, e *domain.Event) error

InsertEvent inserts a caller-supplied event, assigning its generated ID. Empty before/after payloads are stored as SQL NULL.

func InsertInterruption

func InsertInterruption(ctx context.Context, q Q, in *domain.Interruption) error

InsertInterruption inserts in, assigning its generated ID on success.

func InsertOp

func InsertOp(ctx context.Context, q Q, r *domain.OpRecord) error

InsertOp inserts r, assigning its generated sequence on success.

func InsertSession

func InsertSession(ctx context.Context, q Q, s Session) error

InsertSession inserts a session without replacing an existing ID hash.

func InsertTask

func InsertTask(ctx context.Context, q Q, t *domain.Task) error

InsertTask inserts t with a generated ID and version 1, assigning both on success.

func InsertToken

func InsertToken(ctx context.Context, q Q, t *domain.Token) error

InsertToken inserts t, assigning its generated ID on success.

func IntegrityCheck

func IntegrityCheck(ctx context.Context, q Q) error

IntegrityCheck requires SQLite's full consistency check to return only "ok".

func InterruptionsOfTask

func InterruptionsOfTask(ctx context.Context, q Q, task domain.TaskID) ([]domain.Interruption, error)

InterruptionsOfTask returns non-deleted interruptions from or to a task, ordered by time then ID.

func InterruptionsOn

func InterruptionsOn(ctx context.Context, q Q, d civil.Date) ([]domain.Interruption, error)

InterruptionsOn returns non-deleted interruptions on d, ordered by time then ID.

func IsCorrupt

func IsCorrupt(err error) bool

IsCorrupt reports whether err shows a damaged database file: SQLite CORRUPT or NOTADB (including extended codes), or a consistency check that ran and failed (ErrIntegrity). Permission, I/O, busy, lock, out-of-memory and every other failure are not corruption: the file may be intact.

func IsInterrupted

func IsInterrupted(err error) bool

IsInterrupted reports SQLite interruption, retaining classification through wrapped domain errors. Callers must check the context cause separately.

func LatestSeq

func LatestSeq(ctx context.Context, q Q) (domain.OpSeq, error)

LatestSeq returns the greatest operation sequence, or zero for an empty store.

func ListEntries

func ListEntries(ctx context.Context, q Q, eq EntryQuery) ([]domain.LogEntry, error)

ListEntries returns entries newest first, placing timed entries before untimed entries on each day. A cursor resumes strictly after its complete sort tuple.

func ListOps

func ListOps(ctx context.Context, q Q, oq OpQuery) ([]domain.OpRecord, error)

ListOps returns matching operations in descending sequence order.

func ListTasks

func ListTasks(ctx context.Context, q Q, tq TaskQuery) ([]domain.Task, error)

ListTasks lists reconciled task classifications in their cursor order. All SQL fragments are constants; filter and cursor values are bound parameters.

func ListTokens

func ListTokens(ctx context.Context, q Q) ([]domain.Token, error)

ListTokens returns every token in ascending ID order.

func MapErr

func MapErr(err error) error

MapErr translates SQLite failures to domain errors while retaining their causes. Cancellation, domain errors and ErrNotFound pass through unchanged.

func OpTaskIDs

func OpTaskIDs(ctx context.Context, q Q, op domain.OpID) ([]domain.TaskID, error)

OpTaskIDs returns the distinct non-NULL task IDs on an operation's events, ascending.

func OtherSlippedSince

func OtherSlippedSince(ctx context.Context, q Q, task domain.TaskID, exclude domain.BlockID, seq int64) (bool, error)

OtherSlippedSince reports whether another live block is slipped with slipped_seq > seq.

func OtherWorkedSince

func OtherWorkedSince(ctx context.Context, q Q, task domain.TaskID, exclude domain.BlockID, seq int64) (bool, error)

OtherWorkedSince reports whether another live block is worked with resolved_seq > seq.

func PlannedBefore

func PlannedBefore(ctx context.Context, q Q, d civil.Date) ([]domain.TimeBlock, error)

PlannedBefore returns live planned blocks strictly before d, by date, start and ID.

func PlannedOfTask

func PlannedOfTask(ctx context.Context, q Q, task domain.TaskID) ([]domain.TimeBlock, error)

PlannedOfTask returns a task's live planned blocks by date, start and ID.

func PlannedOn

func PlannedOn(ctx context.Context, q Q, d civil.Date) ([]domain.TimeBlock, error)

PlannedOn returns live planned blocks on d, by start minute and ID.

func PlannedOverlapping

func PlannedOverlapping(ctx context.Context, q Q, span domain.BlockSpan, exclude ...domain.BlockID) ([]domain.TimeBlock, error)

PlannedOverlapping returns live planned blocks intersecting the half-open span, omitting any explicitly excluded IDs.

func PushStack

func PushStack(ctx context.Context, q Q, actor string, s Stack, op domain.OpID) error

PushStack appends op with one greater than the current maximum actor/stack sequence.

func PutAuthState

func PutAuthState(ctx context.Context, q Q, a AuthState) error

PutAuthState inserts or replaces authentication row 1.

func PutFocus

func PutFocus(ctx context.Context, q Q, f domain.Focus) error

PutFocus replaces the singleton's task, date and set time, preserving its version.

func PutIdem

func PutIdem(ctx context.Context, q Q, r IdemRow) error

PutIdem inserts or replaces the actor/key record.

func QuickCheck

func QuickCheck(ctx context.Context, q Q) error

QuickCheck requires SQLite's quick consistency check to return only "ok".

func RaiseSequences

func RaiseSequences(ctx context.Context, q Q, m map[string]int64) error

RaiseSequences raises each named high-water mark without lowering an existing value, inserting missing rows. The caller supplies a transaction for atomicity.

func RankBounds

func RankBounds(ctx context.Context, q Q) (lo, hi sql.Null[int64], err error)

RankBounds returns the minimum and maximum rank over all tasks, or NULLs when empty.

func RankNext

func RankNext(ctx context.Context, q Q, p RankPos) (sql.Null[RankPos], error)

RankNext returns the successor of p, including closed and tombstoned tasks.

func RankPrev

func RankPrev(ctx context.Context, q Q, p RankPos) (sql.Null[RankPos], error)

RankPrev returns the predecessor of p, including closed and tombstoned tasks.

func RankTaken

func RankTaken(ctx context.Context, q Q, id domain.TaskID, rank int64) (bool, error)

RankTaken reports whether a task other than id holds rank.

func Reasons

func Reasons(ctx context.Context, q Q, task domain.TaskID) ([]domain.TriageRow, error)

Reasons returns a task's reasons in TriageOrder, then sequence order.

func RemoveReason

func RemoveReason(ctx context.Context, q Q, task domain.TaskID, r domain.TriageReason) (sql.Null[domain.TriageRow], error)

RemoveReason deletes and returns the reason, or an invalid Null if absent.

func RenormalizeRanks

func RenormalizeRanks(ctx context.Context, q Q) error

RenormalizeRanks assigns successive multiples of 65536 in global order. Versions, timestamps and events are untouched.

func ReplaceTokens

func ReplaceTokens(ctx context.Context, q Q, tokens []domain.Token) error

ReplaceTokens deletes every api_tokens row and inserts tokens verbatim: ids, secret hashes, scopes and revoked_at are all kept. It is the one write Plan A's store lacks, used by restore and import to carry the live token table across a snapshot.

AIDEV-NOTE: pass a transaction as q. The delete and the inserts are separate statements, so a bare *sql.DB would leave an empty or partial token table on failure. Callers must also raise sqlite_sequence (RaiseSequences) so future tokens never reuse a replaced id.

func ReportEntries

func ReportEntries(ctx context.Context, q Q, from, to civil.Date, tag, project string) ([]domain.LogEntry, error)

ReportEntries returns live entries by ascending day, timed minutes first, then creation time and ID, with optional tag/project filters.

func RevokeAllTokens

func RevokeAllTokens(ctx context.Context, q Q, at time.Time) ([]domain.TokenID, error)

RevokeAllTokens revokes every unrevoked token and returns those IDs in ascending order.

func RevokeToken

func RevokeToken(ctx context.Context, q Q, id domain.TokenID, at time.Time) error

RevokeToken sets the token's revocation time.

func Sequences

func Sequences(ctx context.Context, q Q) (map[string]int64, error)

Sequences returns the allocated AUTOINCREMENT high-water marks.

func SetOpKind

func SetOpKind(ctx context.Context, q Q, id domain.OpID, kind domain.OpKind) error

SetOpKind sets the kind of an operation whose classification depends on transactional state.

func SetOpState

func SetOpState(ctx context.Context, q Q, id domain.OpID, s domain.OpState) error

SetOpState changes an operation's reversal state.

func SetRank

func SetRank(ctx context.Context, q Q, id domain.TaskID, rank int64) error

SetRank changes only the task's rank.

func SetSetting

func SetSetting(ctx context.Context, q Q, key, value string) error

SetSetting inserts a setting or replaces its value.

func SetTaskTags

func SetTaskTags(ctx context.Context, q Q, task domain.TaskID, names []string, now time.Time) error

SetTaskTags replaces a task's tag set, reusing existing names and casing. The caller supplies a transaction when the replacement must be atomic.

func SlipCounts

func SlipCounts(ctx context.Context, q Q, task domain.TaskID, lastPlacedSeq int64) (lifetime, sinceTriage int, err error)

SlipCounts counts live slipped blocks in total and with slipped_seq > lastPlacedSeq.

func StackOps

func StackOps(ctx context.Context, q Q, actor string, s Stack) ([]domain.OpID, error)

StackOps returns the actor's selected stack from bottom to top.

func TaskTags

func TaskTags(ctx context.Context, q Q, task domain.TaskID) ([]string, error)

TaskTags returns stored tag names in case-insensitive name order.

func TopOfStack

func TopOfStack(ctx context.Context, q Q, actor string, s Stack) (seq int64, op domain.OpID, ok bool, err error)

TopOfStack returns the newest row, with ok false for an empty stack.

func TouchSessions

func TouchSessions(ctx context.Context, q Q, last map[[32]byte]time.Time) error

TouchSessions advances last_seen_at without moving stored times backward.

func TouchTokens

func TouchTokens(ctx context.Context, q Q, last map[domain.TokenID]time.Time) error

TouchTokens advances last_used_at without moving stored times backward.

func TrimStack

func TrimStack(ctx context.Context, q Q, actor string, s Stack, depth int) error

TrimStack keeps only the newest depth rows in the actor's selected stack.

func UpdateBlock

func UpdateBlock(ctx context.Context, q Q, b domain.TimeBlock) error

UpdateBlock replaces mutable fields, preserving task_id, created_at and version.

func UpdateEntry

func UpdateEntry(ctx context.Context, q Q, e domain.LogEntry) error

UpdateEntry replaces mutable fields, preserving kind, creation/update times, version and purged_at for their dedicated writers.

func UpdateTask

func UpdateTask(ctx context.Context, q Q, t domain.Task) error

UpdateTask replaces mutable task fields, leaving rank, creation/update times, version and purged_at to their dedicated writers.

Types

type AuthState

type AuthState struct {
	PasswordHash      string
	PasswordChangedAt time.Time
	WebLoginDisabled  bool
	IdemHMACKey       [32]byte
}

AuthState is the singleton authentication configuration; it contains secrets.

func GetAuthState

func GetAuthState(ctx context.Context, q Q) (AuthState, error)

GetAuthState returns the authentication singleton, or ErrNotFound before initialization.

type Bootstrap

type Bootstrap struct {
	Generation domain.Generation
	TZ         string
	Auth       AuthState
	Owner      domain.Token
}

Bootstrap supplies initial settings, authentication and an owner token. Owner must have IsOwner set, an owner.<ts>-<hex> name and AllScopes; its ID is ignored.

type BootstrapOp

type BootstrapOp struct {
	Op     domain.OpRecord
	Events []domain.Event
}

BootstrapOp is an operation with its events, as read for import carry-over.

func ReadBootstrapOps

func ReadBootstrapOps(ctx context.Context, q Q) ([]BootstrapOp, error)

ReadBootstrapOps returns the token.* and auth.* operations with their events, ordered by sequence. They are the history that init --mcp-token and passwd --reset leave in an otherwise empty database.

type EntryQuery

type EntryQuery struct {
	From, To       civil.Date               // Zero means unbounded.
	Task           *sql.Null[domain.TaskID] // Nil means any; invalid means standalone only.
	IncludeDeleted bool
	Tag, Project   string // Either filter excludes standalone entries.
	AfterKeys      []any  // [work_date, untimed 0|1, occurred_min_or_0, created_at_ms]
	AfterID        int64
	Limit          int
}

EntryQuery selects entries with optional date, task, tag/project and cursor filters.

type EventKey

type EventKey struct {
	Entity domain.EntityKind
	ID     int64
	Reason domain.TriageReason
}

EventKey identifies an entity; Reason further distinguishes triage rows only.

type EventOp

type EventOp struct {
	domain.Event
	Op domain.OpRecord
}

EventOp pairs an event with the operation that recorded it.

func EventsAfter

func EventsAfter(ctx context.Context, q Q, k EventKey, afterID domain.EventID) ([]EventOp, error)

EventsAfter returns all events on k strictly after afterID, ordered by event ID. Operation state and derived events are deliberately left for the caller to interpret.

func TaskEvents

func TaskEvents(ctx context.Context, q Q, task domain.TaskID, beforeID domain.EventID, limit int) ([]EventOp, error)

TaskEvents returns a task's denormalized history, newest first; zero beforeID is unbounded.

type ExportFile

type ExportFile struct {
	Format        string                      `json:"format"`
	Version       int                         `json:"version"`
	SchemaVersion int                         `json:"schema_version"`
	ExportedAt    string                      `json:"exported_at"`
	DBGeneration  string                      `json:"db_generation"`
	Sequences     map[string]int64            `json:"sequences"`
	Settings      map[string]string           `json:"settings"`
	Tables        map[string][]map[string]any `json:"tables"`
}

ExportFile is the shared envelope for service exports and offline imports.

type FTSHit

type FTSHit struct {
	Kind     string // "task" | "entry"
	ID       int64
	TaskID   sql.Null[domain.TaskID]
	Title    string
	Snippet  string               // Plain user text; rendering is responsible for sanitization.
	Status   domain.TaskStatus    // Tasks only.
	WorkDate sql.Null[civil.Date] // Entries only.
	Score    float64              // bm25; lower is better.
}

FTSHit is a live task or entry matching a full-text query.

func Search(ctx context.Context, q Q, match, kind string, limit, offset int) ([]FTSHit, error)

Search returns hits ordered by bm25, kind and ID. match is an FTS5 expression prepared by the caller; kind is task, entry or all. Titles have twice the weight of notes, and snippets use ten tokens with no highlighting markers.

type IdemRow

type IdemRow struct {
	Actor, Key string
	Hash       [32]byte
	OpID       sql.Null[domain.OpID]
	Status     int
	Refs       []domain.EntityRef
	ErrorJSON  []byte
	CreatedAt  time.Time
}

IdemRow stores a request hash and replay references, or a terminal 409 problem.

func GetIdem

func GetIdem(ctx context.Context, q Q, actor, key string) (IdemRow, error)

GetIdem returns the actor/key record, or ErrNotFound if absent.

type ImportIn

type ImportIn struct {
	File       *ExportFile
	Bootstrap  []BootstrapOp
	Generation domain.Generation
	// Now is the time of the import; ImportData itself stamps nothing with it.
	Now time.Time
	// LiveSequences are the live DB's sqlite_sequence values (ruling P8):
	// neither the file nor the bootstrap rows carry the live high-water marks.
	LiveSequences map[string]int64
}

ImportIn is the input of ImportData.

type OpQuery

type OpQuery struct {
	Actor               string
	AIOnly              bool
	IDPrefix            string       // Lowercase hex, validated by the caller; empty means any.
	SinceSeq, BeforeSeq domain.OpSeq // Zero means unbounded.
	Limit               int
}

OpQuery selects operations with optional actor, AI, op ID prefix and exclusive sequence filters.

type Pool

type Pool uint8

Pool identifies a connection's transaction and journaling policy.

const (
	// PoolWriter serializes writes in immediate transactions on the live database.
	PoolWriter Pool = iota + 1
	// PoolReader permits only reads, using deferred transactions.
	PoolReader Pool = iota + 1
	// PoolSnapshot permits VACUUM INTO without an immediate transaction.
	PoolSnapshot Pool = iota + 1
	// PoolStaging creates or opens disposable copies in DELETE journal mode.
	PoolStaging Pool = iota + 1
)

type Q

type Q interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Q is the query interface shared by databases, connections and transactions.

type RankPos

type RankPos struct {
	ID   domain.TaskID
	Rank int64
}

RankPos identifies a position in the global (rank, id) task order.

type SchemaStatus

type SchemaStatus struct {
	Current, Latest int
	Pending         []int
}

SchemaStatus describes the applied and available embedded migrations.

type ScrubResult

type ScrubResult struct{ Rows, Events, Ops int }

ScrubResult counts changed task/entry rows, events and operations.

func ScrubEntities

func ScrubEntities(ctx context.Context, q Q, tasks []domain.TaskID, entries []domain.EntryID, now time.Time) (ScrubResult, error)

ScrubEntities tombstones and removes content from the listed tasks and entries, scrubs their event payloads and disables reversal of affected operations. The caller supplies a transaction when the scrub must be atomic.

func (ScrubResult) Changed

func (r ScrubResult) Changed() bool

Changed reports whether any row, event or operation changed.

type Session

type Session struct {
	IDHash, CSRFSecret               [32]byte
	Remote                           string
	CreatedAt, ExpiresAt, LastSeenAt time.Time
}

Session stores a web session's hashed ID, CSRF secret, remote and lifetimes.

func GetSession

func GetSession(ctx context.Context, q Q, idHash [32]byte) (Session, error)

GetSession returns a session, including expired sessions, or ErrNotFound if absent.

type Stack

type Stack string

Stack identifies an actor's undo or redo stack.

const (
	// StackUndo contains operations available to undo.
	StackUndo Stack = "undo"
	// StackRedo contains operations available to redo.
	StackRedo Stack = "redo"
)

type Store

type Store struct {
	Writer, Reader, Snap *sql.DB
	Path                 string
}

Store owns the live writer, reader and snapshot pools, or a single staging pool.

func Open

func Open(ctx context.Context, absPath string) (*Store, error)

Open opens an existing live database, verifies its connections and checks it. It never creates a missing database.

func OpenStaging

func OpenStaging(ctx context.Context, absPath string) (*Store, error)

OpenStaging creates or opens a staged copy with one pool in DELETE mode. It must never be used on a live database or an original snapshot.

func (*Store) CheckpointTruncate

func (s *Store) CheckpointTruncate(ctx context.Context) error

CheckpointTruncate requires a successful WAL checkpoint with no remaining log.

func (*Store) Close

func (s *Store) Close() error

Close closes every owned pool, closing a shared staging pool only once.

func (*Store) Migrate

func (s *Store) Migrate(ctx context.Context, preMigrate func(context.Context) error) ([]int, error)

Migrate applies pending migrations in order, running preMigrate once before changing the database when it is non-nil. It returns the committed versions, including when a later migration or the final integrity checks fail.

func (*Store) SchemaStatus

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

SchemaStatus checks migration compatibility without modifying the database.

type TagCount

type TagCount struct {
	Name  string
	Count int
}

TagCount counts open, non-deleted tasks with the named tag.

func TagCounts

func TagCounts(ctx context.Context, q Q) ([]TagCount, error)

TagCounts returns positive tag counts in case-insensitive name order.

type TaskQuery

type TaskQuery struct {
	View         domain.View
	Tag, Project string
	AfterKeys    []any
	AfterID      int64
	Limit        int
}

TaskQuery selects a filtered task view and an optional keyset page. AfterKeys contains that view's sort keys; AfterID breaks ties.

Jump to

Keyboard shortcuts

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