postgres

package
v0.1.5 Latest Latest
Warning

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

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

README

Ridu PostgreSQL adapter

github.com/riducms/ridu/adapters/postgres is the official networked database adapter for ordinary production and multi-replica Ridu applications. It implements content, auth, relationships, localization, versions, uploads, locks, preferences, tasks, immutable migrations, and exact readiness through the public store boundary.

New projects can select it during scaffolding:

ridu new

Choose PostgreSQL in the wizard and review the summary before creating the project. Use the complete guide's flag reference only for automation.

Existing projects must update ridu.toml, the server's adapter factory, development wiring, and committed migration history together. Runtime credentials belong in DATABASE_URL; production connections must require verified TLS. Opening the adapter does not create or migrate tables.

Read the complete PostgreSQL guide before changing an adapter or deploying a schema change. It includes generated-project wiring, existing services, ridu migrate verify, backup/cutover, pool bounds, and readiness checks.

Documentation

Overview

Package postgres provides Ridu's first official document store.

Index

Constants

View Source
const AtlasVersion = "1.1.0"

AtlasVersion is Ridu's embedded PostgreSQL planning contract version. It is persisted in every migration artifact so semantic planner upgrades are explicit and reviewable.

View Source
const CodeMigrationPlanMismatch = "RIDU_MIGRATION_PLAN_MISMATCH"

CodeMigrationPlanMismatch is the stable boundary code for an artifact whose contract cannot be reproduced from its embedded immutable inputs.

View Source
const NoticeAtlasProvenance = "RIDU_ATLAS_PROVENANCE"

NoticeAtlasProvenance identifies replay by an Atlas runner version other than the one that planned the frozen artifact SQL.

Variables

View Source
var ErrMaintenanceRequired = errors.New("migration maintenance admission is required")

ErrMaintenanceRequired identifies pending whole-dataset work that requires an explicit maintenance window admission.

Functions

func BuildArtifact

func BuildArtifact(ctx context.Context, name string, before *schema.Manifest, after schema.Manifest, renames []Rename, allowDestructive bool) (ridumigration.Artifact, error)

BuildArtifact uses Atlas to plan all physical PostgreSQL changes and adds ordered Ridu semantic steps for explicitly confirmed rename intent.

func BuildArtifactWithPreviousPlanner

func BuildArtifactWithPreviousPlanner(ctx context.Context, name string, before *schema.Manifest, after schema.Manifest, renames []Rename, allowDestructive bool, previousPlannerVersion string) (ridumigration.Artifact, error)

BuildArtifactWithPreviousPlanner plans against the exact physical contract recorded by the preceding immutable artifact. Ordinary callers should use BuildArtifact; migration-history creation uses this entry point when a reviewed planner upgrade must emit semantic data work.

func ProjectMigrations

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

ProjectMigrations binds checksum-protected callbacks into the compiled project while PostgreSQL retains ownership of every migration transaction and the credential-bearing connection boundary.

func VerifyArtifacts

func VerifyArtifacts(ctx context.Context, databaseURL, directory string) (resultError error)

VerifyArtifacts replays the complete history in a uniquely named temporary PostgreSQL schema, asserts every intermediate state, and always drops the isolated schema before returning. It never touches application tables.

func VerifyArtifactsWithOptions

func VerifyArtifactsWithOptions(ctx context.Context, databaseURL, directory string, options RunnerOptions) (resultError error)

VerifyArtifactsWithOptions replays history with the same operational admissions as ApplyArtifactsWithOptions.

Types

type FieldRename

type FieldRename struct {
	// Before is the field embedded in the previous migration artifact.
	Before schema.Field
	// After is its confirmed match in current executable config.
	After schema.Field
}

FieldRename relates one field before and after a confirmed rename.

type MaintenanceRequiredError

type MaintenanceRequiredError struct {
	Artifacts []string
}

MaintenanceRequiredError lists artifacts refused before any schema or ledger mutation. SQL and content details intentionally remain in the artifact files.

func (*MaintenanceRequiredError) Error

func (err *MaintenanceRequiredError) Error() string

func (*MaintenanceRequiredError) Is

func (err *MaintenanceRequiredError) Is(target error) bool

type MigrationNotice

type MigrationNotice struct {
	Code     string
	Artifact string
	Message  string
}

MigrationNotice is stable, machine-readable runner context.

type MigrationPhaseStatus

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

MigrationPhaseStatus describes one immutable execution boundary.

type MigrationStatus

type MigrationStatus struct {
	// Name is the complete artifact filename.
	Name string `json:"name"`
	// Checksum is the canonical artifact SHA-256 digest.
	Checksum string `json:"checksum"`
	// Version is the frozen artifact wire version.
	Version uint32 `json:"version"`
	// Applied reports whether the database ledger contains this artifact.
	Applied bool `json:"applied"`
	// Phases exposes resumable progress.
	Phases []MigrationPhaseStatus `json:"phases,omitempty"`
}

MigrationStatus describes one immutable artifact relative to the database ledger.

type MigrationStepStatus

type MigrationStepStatus struct {
	ID         string                 `json:"id"`
	Kind       ridumigration.StepKind `json:"kind"`
	State      string                 `json:"state"`
	Checkpoint json.RawMessage        `json:"checkpoint,omitempty"`
}

MigrationStepStatus describes one stable executor and its durable checkpoint.

type PoolConfig

type PoolConfig struct {
	DatabaseURL string
	// AllowInsecureTransport explicitly permits plaintext PostgreSQL connections.
	// Keep this false in production; it exists for local Unix sockets and
	// development databases whose transport is secured outside PostgreSQL.
	AllowInsecureTransport bool
	ApplicationName        string
	MaxConnections         int32
	// MaxUploadLockConnections bounds the separate advisory-lock pool used
	// while object storage and document transactions are coordinated. Keeping
	// this pool separate prevents staged uploads from starving their own
	// document transactions. Zero selects four connections.
	MaxUploadLockConnections        int32
	MinConnections                  int32
	MaxConnectionLifetime           time.Duration
	MaxConnectionLifetimeJitter     time.Duration
	MaxConnectionIdleTime           time.Duration
	HealthCheckPeriod               time.Duration
	ConnectTimeout                  time.Duration
	StatementTimeout                time.Duration
	LockTimeout                     time.Duration
	IdleInTransactionSessionTimeout time.Duration
}

PoolConfig defines bounded production connection and PostgreSQL session defaults. Zero values select Ridu's defaults; negative duration values explicitly disable the corresponding timeout.

type Rename

type Rename struct {
	// Kind selects collection or field rename planning.
	Kind RenameKind
	// BeforeCollection is the collection embedded in the previous artifact.
	BeforeCollection schema.Collection
	// AfterCollection is its collection in current executable config.
	AfterCollection schema.Collection
	// BeforeField and AfterField are set for a standalone field rename.
	BeforeField *schema.Field
	AfterField  *schema.Field
	// Fields contains all physical and nested field pairs for a collection rename.
	Fields []FieldRename
}

Rename records migration-time identity intent confirmed by the application author.

type RenameKind

type RenameKind string

RenameKind identifies the address whose storage identity changes.

const (
	// RenameCollection preserves a collection while changing its derived identity.
	RenameCollection RenameKind = "collection"
	// RenameField preserves a field while changing its derived identity.
	RenameField RenameKind = "field"
)

type RunnerOptions

type RunnerOptions struct {
	// AllowInsecureDatabase explicitly permits a PostgreSQL connection that can
	// fall back to plaintext. It is intended only for local migration drills.
	AllowInsecureDatabase bool
	// AllowMaintenance admits traffic-sensitive semantic steps such as content
	// rewrites, compiled data transforms, resource retirement, and
	// reference-index rebuilds. Every old writer must be stopped while they run.
	// It does not relax artifact validation.
	AllowMaintenance bool
	// AllowUnbounded permits a zero operational timeout. Without this explicit
	// admission, zero selects the runner's bounded production default.
	AllowUnbounded bool
	// AdvisoryLockWait bounds how long this runner waits for another migrator.
	AdvisoryLockWait time.Duration
	// LockTimeout bounds PostgreSQL lock acquisition inside a phase.
	LockTimeout time.Duration
	// StatementTimeout bounds one transactional SQL statement.
	StatementTimeout time.Duration
	// BatchTimeout bounds the complete execution of one checkpoint batch.
	BatchTimeout time.Duration
	// ConcurrentIndexTimeout bounds one CREATE/DROP INDEX CONCURRENTLY command.
	ConcurrentIndexTimeout time.Duration
	// IdleInTransactionTimeout protects a paused transactional phase.
	IdleInTransactionTimeout time.Duration
	// StopAfterPhase and StopAfterStep are explicit, successfully committed
	// rollout boundaries. A transaction phase can stop only at its final step.
	StopAfterPhase string
	StopAfterStep  string
	// Notice receives non-blocking execution provenance after the complete
	// pending history has passed preflight.
	Notice func(MigrationNotice)
	// contains filtered or unexported fields
}

RunnerOptions controls explicit operational admissions without changing the immutable artifact being replayed.

type SafetyError

type SafetyError struct {
	Risks []ridumigration.Risk
}

SafetyError reports a valid schema transition that requires explicit destructive approval or a semantic migration Ridu cannot prove safe.

func (*SafetyError) Error

func (err *SafetyError) Error() string

type Statement

type Statement struct {
	// Kind is a stable, human-readable description of the planned change.
	Kind string
	// SQL is the complete PostgreSQL statement to apply.
	SQL string
	// CollectionID identifies the collection affected by the statement, when any.
	CollectionID schema.StableID
	// FieldID identifies the top-level field affected by the statement, when any.
	FieldID schema.StableID
}

Statement is one ordered SQL change in a development schema plan.

type Store

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

func Open

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

func OpenWithConfig

func OpenWithConfig(ctx context.Context, options PoolConfig) (*Store, error)

OpenWithConfig opens the official PostgreSQL store with explicit pool and server-side resource bounds.

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) error

ApplyArtifacts validates the complete immutable history and applies each pending artifact in its own transaction while holding a session advisory lock.

func (*Store) ApplyArtifactsWithOptions

func (backend *Store) ApplyArtifactsWithOptions(ctx context.Context, directory string, options RunnerOptions) error

ApplyArtifactsWithOptions validates the complete immutable history before mutating the migration ledger or application schema.

func (*Store) ApplyPlan

func (backend *Store) ApplyPlan(ctx context.Context, statements []Statement) error

ApplyPlan applies an Atlas-planned, non-destructive development sync in one transaction. It is intentionally separate from production artifact history.

func (*Store) ArtifactPlan

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

ArtifactPlan returns the same immutable execution topology as status, including durable checkpoints, without applying any step.

func (*Store) ArtifactStatus

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

ArtifactStatus returns immutable artifact state relative to the database ledger.

func (*Store) Begin

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

func (*Store) BeginSnapshot

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

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()

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) 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) 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 uses session advisory locks so object-store deletion and migration-owned adoption of an existing key cannot pass each other between database transactions or application processes.

func (*Store) Ping

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

func (*Store) Plan

func (backend *Store) Plan(ctx context.Context, manifest schema.Manifest) ([]Statement, error)

Plan inspects the current PostgreSQL schema and returns only a safe development synchronization plan. Production history uses BuildArtifact.

func (*Store) PruneExpiredAuth

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

PruneExpiredAuth removes one bounded batch from each expiring durable credential family. The candidate ordering matches the lifecycle indexes; row locks let every process run the same maintenance cycle without duplicate work or an application-wide coordinator.

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 latest complete immutable migration targets the exact manifest embedded in this process. In-progress migration work is rejected even if an older completed digest happens to match.

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) 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) 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