sqlite

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: MIT Imports: 31 Imported by: 0

README

Ridu SQLite adapter

sqlite is Ridu's embedded database adapter for local and small deployments. It supports content, relationships, versions, auth, preferences, document locks, upload references, and durable tasks through a pure-Go SQLite driver. Production does not need CGO, Node, or a separate database service.

New projects can select it during scaffolding:

ridu new

Choose SQLite in the wizard and review the summary. For non-interactive setup, use the flags in the SQLite guide.

Open never creates Ridu tables. Use Store.Migrate only for explicit development bootstrap, or use the immutable artifact API for a deployed database. Existing projects must update ridu.toml, the server's adapter factory, and committed migrations together; deployed servers require an absolute RIDU_SQLITE_PATH on durable local storage.

See the SQLite guide for new- and existing-project wiring, development sync, immutable migrations, backup/restore, startup verification, and known limits.

The adapter supports local SQLite files and private :memory: databases. It does not provide Payload's remote libSQL transport or a Cloudflare D1 compatibility mode.

Documentation

Overview

Package sqlite provides Ridu's official embedded SQLite document store.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ProjectMigrations

func ProjectMigrations(transforms ...ridumigration.DataTransform) ridumigration.ProjectDriver

ProjectMigrations returns the narrow compiled-project driver used when an immutable artifact names application data callbacks. Register it with ridu.WithProjectMigrations even in project-command mode; ordinary server runtime still owns its separate Store factory.

func VerifyArtifacts

func VerifyArtifacts(ctx context.Context, directory string, transforms ...ridumigration.DataTransform) error

VerifyArtifacts replays complete history into an isolated temporary SQLite database and proves that every artifact and the latest manifest are complete.

Types

type Config

type Config struct {
	// Path is a filesystem path, a file: SQLite URI, or :memory:.
	Path string
	// BusyTimeout bounds how long SQLite waits for another writer. Zero selects
	// ten seconds. Negative values and values above SQLite's signed 32-bit
	// millisecond limit are rejected.
	BusyTimeout time.Duration
	// DisableWAL keeps file databases in their existing journal mode. WAL is
	// enabled by default because it permits readers while the single writer is
	// active. SQLite memory databases ignore WAL mode.
	DisableWAL bool
	// MaxConnections bounds pooled readers. Operation transactions still use
	// BEGIN IMMEDIATE and SQLite's single-writer contract.
	MaxConnections int
}

Config controls the bounded connection behavior of the embedded SQLite store. Zero values select safe local defaults.

type CreatedArtifact

type CreatedArtifact struct {
	Path     string `json:"path"`
	Name     string `json:"name"`
	Checksum string `json:"checksum"`
	Version  uint32 `json:"version"`
}

CreatedArtifact is the stable filesystem identity of one newly committed immutable SQLite migration. It deliberately does not expose Ridu's internal artifact-file representation.

func CreateArtifact

func CreateArtifact(ctx context.Context, directory, name string, after schema.Manifest, now time.Time, allowDestructive bool, transforms ...ridumigration.DataTransformDescriptor) (CreatedArtifact, error)

CreateArtifact plans and atomically creates one immutable SQLite migration file. Existing files are never overwritten and the new artifact must continue the latest committed manifest in directory. The before manifest is derived from that history so applications never need to decode private artifact files themselves.

type MigrationPhaseStatus

type MigrationPhaseStatus struct {
	ID    string                  `json:"id"`
	Mode  ridumigration.PhaseMode `json:"mode"`
	State string                  `json:"state"`
	Steps []MigrationStepStatus   `json:"steps"`
}

MigrationPhaseStatus reports one transaction phase in an immutable artifact.

type MigrationStatus

type MigrationStatus struct {
	Name     string                 `json:"name"`
	Checksum string                 `json:"checksum"`
	Version  uint32                 `json:"version"`
	Applied  bool                   `json:"applied"`
	Phases   []MigrationPhaseStatus `json:"phases"`
}

MigrationStatus describes one immutable SQLite artifact relative to the database ledger. SQLite artifacts are atomic, so phases and steps are either wholly pending or wholly complete and do not need a checkpoint vocabulary.

func InspectArtifacts

func InspectArtifacts(ctx context.Context, path, directory string, executableManifest schema.Manifest) ([]MigrationStatus, error)

InspectArtifacts reports immutable migration state without creating or changing the selected SQLite database. Missing files have an all-pending state; existing files are opened read-only without adapter write pragmas.

type MigrationStepStatus

type MigrationStepStatus struct {
	ID    string                 `json:"id"`
	Kind  ridumigration.StepKind `json:"kind"`
	State string                 `json:"state"`
}

MigrationStepStatus reports one SQLite artifact step.

type SafetyError

type SafetyError struct {
	Risks []ridumigration.Risk
}

SafetyError reports a valid SQLite transition that requires explicit destructive approval before an immutable artifact can be created.

func (*SafetyError) Error

func (err *SafetyError) Error() string

type Store

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

Store is one embedded SQLite database. Schema changes are explicit through Migrate or immutable artifact application; Open never mutates CMS tables.

func Open

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

Open connects to a SQLite file or :memory: database using safe defaults.

func OpenWithConfig

func OpenWithConfig(ctx context.Context, config Config) (*Store, error)

OpenWithConfig connects to SQLite without creating or changing Ridu's schema. Every pooled connection receives the same validated pragmas.

func (*Store) AcquireDocumentLock

func (backend *Store) AcquireDocumentLock(ctx context.Context, candidate store.DocumentLock, now time.Time, takeover bool) (store.DocumentLock, bool, error)

func (*Store) AllowAuthAttempt

func (backend *Store) AllowAuthAttempt(ctx context.Context, keyHash string, now time.Time, window time.Duration, maximum int) (bool, error)

func (*Store) ApplyArtifacts

func (backend *Store) ApplyArtifacts(ctx context.Context, directory string, transforms ...ridumigration.DataTransform) error

ApplyArtifacts validates the complete committed history before creating a ledger or changing application schema. All pending artifacts and their ledger rows commit under one BEGIN IMMEDIATE writer reservation.

func (*Store) ArtifactPlan

func (backend *Store) ArtifactPlan(ctx context.Context, directory string, executableManifest schema.Manifest) ([]MigrationStatus, error)

ArtifactPlan returns the same manifest-bound immutable SQLite topology as status.

func (*Store) ArtifactStatus

func (backend *Store) ArtifactStatus(ctx context.Context, directory string, executableManifest schema.Manifest) ([]MigrationStatus, error)

ArtifactStatus binds immutable history to the executable schema, then uses that exact history snapshot to report the atomic applied/pending boundary.

func (*Store) Begin

func (backend *Store) Begin(ctx context.Context) (store.Transaction, error)

Begin opens a write-capable operation transaction. BEGIN IMMEDIATE obtains SQLite's honest database-level writer reservation before access and relationship checks run, replacing PostgreSQL row locks without pretending SQLite has finer lock semantics.

func (*Store) BeginSnapshot

func (backend *Store) BeginSnapshot(ctx context.Context) (store.Transaction, error)

BeginSnapshot opens a stable deferred read snapshot without reserving the database's single writer. The operation engine uses it for read-only work.

func (*Store) CancelTask

func (backend *Store) CancelTask(ctx context.Context, id string) error

func (*Store) ChangePasswordHash

func (backend *Store) ChangePasswordHash(ctx context.Context, collection schema.Collection, userID string, expectedPasswordHash, hash []byte) error

func (*Store) ClaimTasks

func (backend *Store) ClaimTasks(ctx context.Context, request store.TaskClaim) ([]store.Task, error)

func (*Store) Close

func (backend *Store) Close() error

Close releases every pooled SQLite connection.

func (*Store) CompleteTask

func (backend *Store) CompleteTask(ctx context.Context, id, leaseToken string, output json.RawMessage) error

func (*Store) CreateAPIKey

func (backend *Store) CreateAPIKey(ctx context.Context, key store.AuthAPIKey, sessionTokenHash string, now time.Time) error

func (*Store) CreateAuthToken

func (backend *Store) CreateAuthToken(ctx context.Context, token store.AuthToken) error

func (*Store) CreateSession

func (backend *Store) CreateSession(ctx context.Context, session store.AuthSession, expectedPasswordHash []byte) error

func (*Store) DeleteAPIKey

func (backend *Store) DeleteAPIKey(ctx context.Context, collectionID schema.StableID, userID, id string) error

func (*Store) DeletePreference

func (backend *Store) DeletePreference(ctx context.Context, collectionID schema.StableID, userID, key string) error

func (*Store) DeletePreferences

func (backend *Store) DeletePreferences(ctx context.Context, collectionID schema.StableID, userID string) error

func (*Store) DeleteSession

func (backend *Store) DeleteSession(ctx context.Context, tokenHash string) error

func (*Store) DeleteUserSession

func (backend *Store) DeleteUserSession(ctx context.Context, collectionID schema.StableID, userID, sessionID string) error

func (*Store) DeleteUserSessions

func (backend *Store) DeleteUserSessions(ctx context.Context, collectionID schema.StableID, userID string) error

func (*Store) DismissTaskForTarget

func (backend *Store) DismissTaskForTarget(ctx context.Context, id, slug string, target store.DocumentReference) error

func (*Store) DownArtifacts

func (backend *Store) DownArtifacts(ctx context.Context, directory string, transforms ...ridumigration.DataTransform) error

DownArtifacts rolls back the most recently applied immutable artifact. The artifact file remains committed, so status reports it as pending and a later ApplyArtifacts call can replay it. Registered callbacks are checksum-bound to the artifact. An already-empty database is a no-op.

func (*Store) EnqueueTask

func (backend *Store) EnqueueTask(ctx context.Context, task store.Task) (store.Task, error)

func (*Store) FailTask

func (backend *Store) FailTask(ctx context.Context, failure store.TaskFailure) error

func (*Store) FindAPIKey

func (backend *Store) FindAPIKey(ctx context.Context, id string, now time.Time) (store.AuthAPIKey, error)

func (*Store) FindAuthCredential

func (backend *Store) FindAuthCredential(ctx context.Context, collection schema.Collection, identity string) (store.AuthCredential, error)

func (*Store) FindDocumentLock

func (backend *Store) FindDocumentLock(ctx context.Context, collectionID schema.StableID, documentID string, now time.Time) (store.DocumentLock, error)

func (*Store) FindSession

func (backend *Store) FindSession(ctx context.Context, tokenHash string, now time.Time) (store.AuthSession, error)

func (*Store) FindTask

func (backend *Store) FindTask(ctx context.Context, id string) (store.Task, error)

func (*Store) ForceUnlock

func (backend *Store) ForceUnlock(ctx context.Context, collectionID schema.StableID, userID string) error

func (*Store) FreshArtifacts

func (backend *Store) FreshArtifacts(ctx context.Context, directory string, transforms ...ridumigration.DataTransform) error

FreshArtifacts drops every non-internal object in the selected SQLite database and replays committed history in one transaction. Callers must put an explicit destructive confirmation in front of this method. Registered up callbacks replay with their committed artifacts.

func (*Store) GetPreference

func (backend *Store) GetPreference(ctx context.Context, collectionID schema.StableID, userID, key string) (store.Preference, error)

func (*Store) HeartbeatTask

func (backend *Store) HeartbeatTask(ctx context.Context, id, leaseToken string, leaseDuration time.Duration) error

func (*Store) ListAPIKeys

func (backend *Store) ListAPIKeys(ctx context.Context, collectionID schema.StableID, userID string, now time.Time) ([]store.AuthAPIKey, error)

func (*Store) ListSessions

func (backend *Store) ListSessions(ctx context.Context, collectionID schema.StableID, userID string, now time.Time) ([]store.AuthSession, error)

func (*Store) ListTasks

func (backend *Store) ListTasks(ctx context.Context, request store.TaskList) ([]store.Task, error)

func (*Store) LockUploadObjects

func (backend *Store) LockUploadObjects(ctx context.Context, objectKeys []string) (func(), error)

LockUploadObjects serializes upload admission and cleanup across every process sharing a file database. SQLite memory databases are private to one Store and use the equivalent in-process gate.

func (*Store) Migrate

func (backend *Store) Migrate(ctx context.Context, manifest schema.Manifest) error

Migrate atomically installs SQLite's adapter-owned tables and records the exact manifest digest. It is an explicit development/bootstrap operation; Open never calls it and production callers should apply reviewed immutable artifacts once the SQLite artifact runner is configured.

func (*Store) Ping

func (backend *Store) Ping(ctx context.Context) error

Ping proves that SQLite can serve a query and that foreign-key enforcement is active on the selected pooled connection.

func (*Store) PruneExpiredAuth

func (backend *Store) PruneExpiredAuth(ctx context.Context, limit int) (store.AuthPruneResult, error)

PruneExpiredAuth removes at most limit records from each expiring auth family. BEGIN IMMEDIATE serializes candidates across processes so two maintenance workers cannot count or delete the same record.

func (*Store) PruneTasks

func (backend *Store) PruneTasks(ctx context.Context, limit int) (int, error)

func (*Store) Ready

func (backend *Store) Ready(ctx context.Context, manifest schema.Manifest) error

Ready proves connectivity and that the explicitly applied manifest is the exact manifest embedded in this process.

func (*Store) ReadyWithMigrationHistory

func (backend *Store) ReadyWithMigrationHistory(ctx context.Context, manifest schema.Manifest, expectedHistoryDigest string) error

ReadyWithMigrationHistory proves ordinary readiness and exact agreement with the complete ordered migration history embedded in the executable.

func (*Store) RecordFailedLogin

func (backend *Store) RecordFailedLogin(ctx context.Context, collectionID schema.StableID, userID string, now time.Time, maximum int, lockDuration time.Duration) (store.AuthCredential, error)

func (*Store) RefreshArtifacts

func (backend *Store) RefreshArtifacts(ctx context.Context, directory string, transforms ...ridumigration.DataTransform) error

RefreshArtifacts rolls back every applied artifact and replays the complete committed schema and callback history in one SQLite transaction.

func (*Store) ReleaseDocumentLock

func (backend *Store) ReleaseDocumentLock(ctx context.Context, collectionID schema.StableID, documentID string, ownerCollectionID schema.StableID, ownerID string) error

func (*Store) ReleaseTask

func (backend *Store) ReleaseTask(ctx context.Context, id, leaseToken string, delay time.Duration, code, message string) error

func (*Store) ResetArtifacts

func (backend *Store) ResetArtifacts(ctx context.Context, directory string, transforms ...ridumigration.DataTransform) error

ResetArtifacts rolls back every applied artifact in exact reverse order. Files and their immutable checksums remain untouched, and registered callbacks run in the same transaction.

func (*Store) ResetLoginAttempts

func (backend *Store) ResetLoginAttempts(ctx context.Context, collectionID schema.StableID, userID string, now time.Time) (bool, error)

func (*Store) ResetPasswordWithToken

func (backend *Store) ResetPasswordWithToken(ctx context.Context, collectionID schema.StableID, tokenHash string, hash []byte, now time.Time) (string, error)

func (*Store) RotateSession

func (backend *Store) RotateSession(ctx context.Context, currentHash string, replacement store.AuthSession, now time.Time) error

func (*Store) SetPasswordHash

func (backend *Store) SetPasswordHash(ctx context.Context, collection schema.Collection, userID string, hash []byte, initiallyVerified bool) error

func (*Store) SetPreference

func (backend *Store) SetPreference(ctx context.Context, preference store.Preference) (store.Preference, error)

func (*Store) TouchAPIKey

func (backend *Store) TouchAPIKey(ctx context.Context, id string, now time.Time) error

func (*Store) UpgradePasswordHash

func (backend *Store) UpgradePasswordHash(ctx context.Context, collection schema.Collection, userID string, expectedPasswordHash, hash []byte) error

func (*Store) VerifyEmailWithToken

func (backend *Store) VerifyEmailWithToken(ctx context.Context, collectionID schema.StableID, tokenHash string, now time.Time) (string, error)

Jump to

Keyboard shortcuts

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