riverdriver

package module
v0.52.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MPL-2.0 Imports: 10 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 riverdriver exposes generic constructs to be implemented by specific drivers that wrap third party database packages, with the aim being to keep the main River interface decoupled from a specific database package so that other packages or other major versions of packages can be supported in future River versions.

River currently only supports Pgx v5, and the interface here wrap it with only the thinnest possible layer. Adding support for alternate packages will require the interface to change substantially, and therefore it should not be implemented or invoked by user code. Changes to interfaces in this package WILL NOT be considered breaking changes for purposes of River's semantic versioning.

Index

Constants

View Source
const (
	DatabaseNamePostgres  = "postgres"
	DatabaseNameSQLite    = "sqlite"
	DatabaseNameSQLServer = "sqlserver"
)
View Source
const AllQueuesString = "*"
View Source
const MigrationLineMain = "main"
View Source
const UniqueInsertMetadataKey = "river:unique_nonce"

UniqueInsertMetadataKey is a reserved job metadata key used to detect unique insert conflicts on databases that don't expose Postgres system columns.

Variables

View Source
var (
	ErrClosedPool     = errors.New("underlying driver pool is closed")
	ErrNotImplemented = errors.New("driver does not implement this functionality")
)

Functions

func MarshalJSONNoEscapeHTML added in v0.51.0

func MarshalJSONNoEscapeHTML(v any) ([]byte, error)

MarshalJSONNoEscapeHTML is json.Marshal without escaping HTML characters. Drivers use it to encode JSON that's stored as text, like job args and metadata in SQLite and SQL Server, so that it's kept as it's given rather than with `<`, `>`, and `&` rewritten as `<`, `>`, and `&`.

func MigrationLineMainTruncateTables

func MigrationLineMainTruncateTables(version int) []string

MigrationLineMainTruncateTables is a shared helper that produces tables to truncate for the main migration line. It's reused across all drivers.

API is not stable. DO NOT USE.

func UniqueInsertMetadataIsDuplicate

func UniqueInsertMetadataIsDuplicate(metadata []byte, nonce string) bool

UniqueInsertMetadataIsDuplicate returns whether metadata lacks the nonce from a proposed insert, indicating that an existing row was returned instead.

func UniqueInsertMetadataNonce

func UniqueInsertMetadataNonce(metadata []byte) (string, bool)

UniqueInsertMetadataNonce returns the nonce in metadata, or false if the metadata has no valid nonce.

func UniqueInsertMetadataWithNonce

func UniqueInsertMetadataWithNonce(metadata []byte, nonce string) ([]byte, error)

UniqueInsertMetadataWithNonce returns metadata with nonce set under UniqueInsertMetadataKey.

func UnmarshalAttemptError

func UnmarshalAttemptError(data []byte, attemptError *rivertype.AttemptError) error

UnmarshalAttemptError decodes a stored attempt error, using ordinary JSON decoding first. If its shape doesn't match what River writes, valid JSON is decoded on a best effort basis so historical errors can't make a job unreadable. Timestamps outside RFC 3339 are left zero, numeric attempt strings are accepted, and non-string error and trace values are preserved as JSON text.

This tolerance applies to database reads, not rivertype.AttemptError's normal JSON decoding. Only invalid JSON returns an error.

func UnmarshalAttemptErrors

func UnmarshalAttemptErrors(data []byte, attemptErrors *[]rivertype.AttemptError) error

UnmarshalAttemptErrors decodes a stored JSON array of attempt errors. Ordinary arrays are decoded in one pass. If an element can't be decoded, the array is retried with UnmarshalAttemptError for each element. Invalid JSON and non-array values still return errors so the driver can mark the job as undecodable.

Types

type ColumnExistsParams

type ColumnExistsParams struct {
	Column string
	Schema string
	Table  string
}

type Driver

type Driver[TTx any] interface {
	// ArgPlaceholder is the placeholder character used in query positional
	// arguments, so "$" for "$1", "$2", "$3", etc. This is a "$" for Postgres,
	// "?" for SQLite, and "@p" for SQL Server.
	//
	// API is not stable. DO NOT USE.
	ArgPlaceholder() string

	// DatabaseName is the name of the database that the driver targets like
	// "postgres" or "sqlite". This is used for purposes like a cache key prefix
	// in riverdbtest so that multiple drivers may share schemas as long as they
	// target the same database.
	//
	// API is not stable. DO NOT USE.
	DatabaseName() string

	// GetExecutor gets an executor for the driver.
	//
	// API is not stable. DO NOT USE.
	GetExecutor() Executor

	// GetListener gets a listener for purposes of receiving notifications.
	//
	// API is not stable. DO NOT USE.
	GetListener(params *GetListenenerParams) Listener

	// GetMigrationDefaultLines gets default migration lines that should be
	// applied when using this driver. This is mainly used by riverdbtest to
	// figure out what migration lines should be available by default for new
	// test schemas.
	//
	// API is not stable. DO NOT USE.
	GetMigrationDefaultLines() []string

	// GetMigrationFS gets a filesystem containing migrations for the driver.
	//
	// Each set of migration files is expected to exist within the filesystem as
	// `migration/<line>/`. For example:
	//
	//     migration/main/001_create_river_migration.up.sql
	//
	// API is not stable. DO NOT USE.
	GetMigrationFS(line string) fs.FS

	// GetMigrationLines gets supported migration lines from the driver. Most
	// drivers will only support a single line: MigrationLineMain.
	//
	// API is not stable. DO NOT USE.
	GetMigrationLines() []string

	// GetMigrationTruncateTables gets the tables that should be truncated
	// before or after tests for a specific migration line returned by this
	// driver. Tables to truncate doesn't need to consider intermediary states,
	// and should return tables for the latest migration version.
	//
	// API is not stable. DO NOT USE.
	GetMigrationTruncateTables(line string, version int) []string

	// PoolIsSet returns true if the driver is configured with a database pool.
	//
	// API is not stable. DO NOT USE.
	PoolIsSet() bool

	// PoolSet sets a database pool into a driver will a nil pool. This is meant
	// only for use in testing, and only in specific circumstances where it's
	// needed. The pool in a driver should generally be treated as immutable
	// because it's inherited by driver executors, and changing if when active
	// executors exist will cause problems.
	//
	// Most drivers don't implement this function and return ErrNotImplemented.
	//
	// Drivers should only set a pool if the previous pool was nil (to help root
	// out bugs where something unexpected is happening), and panic in case a
	// pool is set to a driver twice.
	//
	// API is not stable. DO NOT USE.
	PoolSet(dbPool any) error

	// SQLFragmentColumnContainsAll generates an SQL fragment to be included as
	// a predicate in a `WHERE` query for a collection column containing all of
	// the given values. Postgres uses array containment while SQLite compares
	// values from a JSON array.
	//
	// API is not stable. DO NOT USE.
	SQLFragmentColumnContainsAll(column, namedArg string, values []string) (string, any, error)

	// SQLFragmentColumnContainsAny generates an SQL fragment to be included as
	// a predicate in a `WHERE` query for a collection column containing at least
	// one of the given values. Postgres uses array overlap while SQLite
	// compares values from a JSON array.
	//
	// API is not stable. DO NOT USE.
	SQLFragmentColumnContainsAny(column, namedArg string, values []string) (string, any, error)

	// SQLFragmentColumnIn generates an SQL fragment to be included as a
	// predicate in a `WHERE` query for the existence of a set of values in a
	// column like `id IN (...)`. The actual implementation depends on support
	// for specific data types. Postgres uses arrays while SQLite uses a JSON
	// fragment with `json_each`.
	//
	// API is not stable. DO NOT USE.
	SQLFragmentColumnIn(column string, values any) (string, any, error)

	// SupportsListener gets whether this driver supports a listener. Drivers
	// that don't support a listener support poll only mode only.
	// Before InitDriver, this reports the driver's default capability; callers
	// must recheck after initialization to account for the database server.
	//
	// API is not stable. DO NOT USE.
	SupportsListener() bool

	// SupportsListenNotify indicates whether the driver can broadcast
	// notifications that a listener can receive, either through a native
	// database mechanism like Postgres LISTEN/NOTIFY or a driver-specific
	// emulation. This differs from SupportsListener in that even if a driver
	// doesn't support a listener but the database supports the underlying
	// notification mechanism, it will still broadcast in case there are other
	// clients/drivers on the database that do support a listener. If
	// notifications can't be supported at all, no broadcast attempt is made.
	// Like SupportsListener, this is refined by InitDriver. Executors also
	// initialize lazily before sending notifications for clients that never start.
	//
	// API is not stable. DO NOT USE.
	SupportsListenNotify() bool

	// TimePrecision returns the maximum time resolution supported by the
	// database. This is used in test assertions when checking round trips on
	// timestamps.
	//
	// API is not stable. DO NOT USE.
	TimePrecision() time.Duration

	// UnwrapExecutor gets an executor from a driver transaction.
	//
	// API is not stable. DO NOT USE.
	UnwrapExecutor(tx TTx) ExecutorTx

	// UnwrapTx gets a driver transaction from an executor. This is currently
	// only needed for test transaction helpers.
	//
	// API is not stable. DO NOT USE.
	UnwrapTx(execTx ExecutorTx) TTx
}

Driver provides a database driver for use with river.Client.

Its purpose is to wrap the interface of a third party database package, with the aim being to keep the main River interface decoupled from a specific database package so that other packages or major versions of packages can be supported in future River versions.

River currently only supports Pgx v5, and this interface wraps it with only the thinnest possible layer. Adding support for alternate packages will require it to change substantially, and therefore it should not be implemented or invoked by user code. Changes to this interface WILL NOT be considered breaking changes for purposes of River's semantic versioning.

API is not stable. DO NOT IMPLEMENT.

type Executor

type Executor interface {
	// Begin begins a new subtransaction. ErrSubTxNotSupported may be returned
	// if the executor is a transaction and the driver doesn't support
	// subtransactions (like riverdriver/riverdatabasesql for database/sql).
	Begin(ctx context.Context) (ExecutorTx, error)

	// ColumnExists checks whether a column for a particular table exists for
	// the schema in the current search schema.
	ColumnExists(ctx context.Context, params *ColumnExistsParams) (bool, error)

	// Exec executes raw SQL. Used for migrations.
	Exec(ctx context.Context, sql string, args ...any) error

	// IndexDropIfExists drops a database index if exists. This abstraction is a
	// little leaky right now because Postgres runs this `CONCURRENTLY` and
	// that's not possible in SQLite.
	//
	// API is not stable. DO NOT USE.
	IndexDropIfExists(ctx context.Context, params *IndexDropIfExistsParams) error
	IndexExists(ctx context.Context, params *IndexExistsParams) (bool, error)
	IndexesExist(ctx context.Context, params *IndexesExistParams) (map[string]bool, error)

	// IndexReindex reindexes a database index. This abstraction is a little
	// leaky right now because Postgres runs this `CONCURRENTLY` and that's not
	// possible in SQLite.
	//
	// API is not stable. DO NOT USE.
	IndexReindex(ctx context.Context, params *IndexReindexParams) error
	IndexReindexArtifacts(ctx context.Context, params *IndexReindexArtifactsParams) ([]string, error)

	// InitDriver initializes driver-specific state using information read from
	// the database. Implementations must be safe to call concurrently and
	// repeatedly, and should cache successfully initialized state.
	InitDriver(ctx context.Context) error

	JobCancel(ctx context.Context, params *JobCancelParams) (*rivertype.JobRow, error)
	JobCountByAllStates(ctx context.Context, params *JobCountByAllStatesParams) (map[rivertype.JobState]int, error)
	JobCountByQueueAndState(ctx context.Context, params *JobCountByQueueAndStateParams) ([]*JobCountByQueueAndStateResult, error)
	JobCountByState(ctx context.Context, params *JobCountByStateParams) (int, error)
	JobDelete(ctx context.Context, params *JobDeleteParams) (*rivertype.JobRow, error)
	JobDeleteBefore(ctx context.Context, params *JobDeleteBeforeParams) (int, error)
	JobDeleteMany(ctx context.Context, params *JobDeleteManyParams) ([]*rivertype.JobRow, error)

	// JobGetAvailable locks available jobs for work, moving them to `running`.
	// A locked job whose row can't be fully decoded doesn't fail the call.
	// It's included in Jobs with an entry in DecodeErrors so that the caller
	// can fail its attempt instead of working the partial row.
	JobGetAvailable(ctx context.Context, params *JobGetAvailableParams) (*JobGetAvailableResult, error)

	JobGetByID(ctx context.Context, params *JobGetByIDParams) (*rivertype.JobRow, error)
	JobGetByIDMany(ctx context.Context, params *JobGetByIDManyParams) ([]*rivertype.JobRow, error)
	JobGetByKindMany(ctx context.Context, params *JobGetByKindManyParams) ([]*rivertype.JobRow, error)

	// JobGetCancelRequested returns IDs of running jobs with a cancellation request,
	// restricted to the provided IDs.
	JobGetCancelRequested(ctx context.Context, params *JobGetCancelRequestedParams) ([]int64, error)

	// JobGetStuck gets jobs that have been running since before a horizon. A
	// job row that can't be fully decoded is returned with the fields that
	// couldn't be decoded left empty so that one bad row can't prevent stuck
	// jobs from being rescued.
	JobGetStuck(ctx context.Context, params *JobGetStuckParams) ([]*rivertype.JobRow, error)

	JobInsertFastMany(ctx context.Context, params *JobInsertFastManyParams) ([]*JobInsertFastResult, error)
	JobInsertFastManyNoReturning(ctx context.Context, params *JobInsertFastManyParams) (int, error)
	JobInsertFull(ctx context.Context, params *JobInsertFullParams) (*rivertype.JobRow, error)
	JobInsertFullMany(ctx context.Context, jobs *JobInsertFullManyParams) ([]*rivertype.JobRow, error)
	JobKindList(ctx context.Context, params *JobKindListParams) ([]string, error)
	JobList(ctx context.Context, params *JobListParams) ([]*rivertype.JobRow, error)
	JobRescueMany(ctx context.Context, params *JobRescueManyParams) (*struct{}, error)
	JobRetry(ctx context.Context, params *JobRetryParams) (*rivertype.JobRow, error)
	JobSchedule(ctx context.Context, params *JobScheduleParams) ([]*JobScheduleResult, error)

	// JobSetStateIfRunningMany sets the state of running jobs, returning the
	// resulting rows. A job row that can't be fully decoded is returned with
	// the fields that couldn't be decoded left empty so that the state of an
	// undecodable job can be set without failing the other jobs set with it.
	JobSetStateIfRunningMany(ctx context.Context, params *JobSetStateIfRunningManyParams) ([]*rivertype.JobRow, error)

	JobUpdate(ctx context.Context, params *JobUpdateParams) (*rivertype.JobRow, error)
	JobUpdateFull(ctx context.Context, params *JobUpdateFullParams) (*rivertype.JobRow, error)
	LeaderAttemptElect(ctx context.Context, params *LeaderElectParams) (*Leader, error)
	LeaderAttemptReelect(ctx context.Context, params *LeaderReelectParams) (*Leader, error)
	LeaderDeleteExpired(ctx context.Context, params *LeaderDeleteExpiredParams) (int, error)
	LeaderGetElectedLeader(ctx context.Context, params *LeaderGetElectedLeaderParams) (*Leader, error)
	LeaderInsert(ctx context.Context, params *LeaderInsertParams) (*Leader, error)
	LeaderResign(ctx context.Context, params *LeaderResignParams) (bool, error)

	// MigrationDeleteAssumingMainMany deletes many migrations assuming
	// everything is on the main line. This is suitable for use in databases on
	// a version before the `line` column exists.
	MigrationDeleteAssumingMainMany(ctx context.Context, params *MigrationDeleteAssumingMainManyParams) ([]*Migration, error)

	// MigrationDeleteByLineAndVersionMany deletes many migration versions on a
	// particular line.
	MigrationDeleteByLineAndVersionMany(ctx context.Context, params *MigrationDeleteByLineAndVersionManyParams) ([]*Migration, error)

	// MigrationGetAllAssumingMain gets all migrations assuming everything is on
	// the main line. This is suitable for use in databases on a version before
	// the `line` column exists.
	MigrationGetAllAssumingMain(ctx context.Context, params *MigrationGetAllAssumingMainParams) ([]*Migration, error)

	// MigrationGetByLine gets all currently applied migrations.
	MigrationGetByLine(ctx context.Context, params *MigrationGetByLineParams) ([]*Migration, error)

	// MigrationInsertMany inserts many migration versions.
	MigrationInsertMany(ctx context.Context, params *MigrationInsertManyParams) ([]*Migration, error)

	// MigrationInsertManyAssumingMain inserts many migrations, assuming they're
	// on the main line. This operation is necessary for compatibility before
	// the `line` column was added to the migrations table.
	MigrationInsertManyAssumingMain(ctx context.Context, params *MigrationInsertManyAssumingMainParams) ([]*Migration, error)

	// MigrationLock acquires a lock that serializes migrators operating on the
	// same schema and migration line. It must be invoked from within a
	// transaction, and the lock is held until that transaction ends. If
	// another transaction holds the lock, it blocks until the lock is
	// released.
	//
	// Drivers whose write transactions are already serialized by the database
	// may implement it as a no-op.
	MigrationLock(ctx context.Context, params *MigrationLockParams) error

	// NotificationDeleteBefore deletes up to Max notifications before a certain
	// time horizon, oldest first.
	//
	// A "notification" in this context refers to a row in `river_notification`
	// which is a special table implemented in some databases (e.g. SQLite) that
	// simulates Postgres' listen/notify when not available.
	NotificationDeleteBefore(ctx context.Context, params *NotificationDeleteBeforeParams) (int, error)

	NotifyMany(ctx context.Context, params *NotifyManyParams) error

	// Ping checks that the database is reachable.
	Ping(ctx context.Context) error

	PGAdvisoryXactLock(ctx context.Context, key int64) (*struct{}, error)

	QueueCreateOrSetUpdatedAt(ctx context.Context, params *QueueCreateOrSetUpdatedAtParams) (*rivertype.Queue, error)
	QueueDeleteExpired(ctx context.Context, params *QueueDeleteExpiredParams) ([]string, error)
	QueueGet(ctx context.Context, params *QueueGetParams) (*rivertype.Queue, error)
	QueueList(ctx context.Context, params *QueueListParams) ([]*rivertype.Queue, error)
	QueueNameList(ctx context.Context, params *QueueNameListParams) ([]string, error)
	QueuePause(ctx context.Context, params *QueuePauseParams) error
	QueueResume(ctx context.Context, params *QueueResumeParams) error
	QueueUpdate(ctx context.Context, params *QueueUpdateParams) (*rivertype.Queue, error)
	QueryRow(ctx context.Context, sql string, args ...any) Row

	SchemaCreate(ctx context.Context, params *SchemaCreateParams) error
	SchemaDrop(ctx context.Context, params *SchemaDropParams) error
	SchemaGetExpired(ctx context.Context, params *SchemaGetExpiredParams) ([]string, error)

	// TableExists checks whether a table exists for the schema in the current
	// search schema.
	TableExists(ctx context.Context, params *TableExistsParams) (bool, error)
	TableTruncate(ctx context.Context, params *TableTruncateParams) error
}

Executor provides River operations against a database. It may be a database pool or transaction.

API is not stable. DO NOT IMPLEMENT.

type ExecutorTx

type ExecutorTx interface {
	Executor

	// Commit commits the transaction.
	//
	// API is not stable. DO NOT USE.
	Commit(ctx context.Context) error

	// Rollback rolls back the transaction.
	//
	// API is not stable. DO NOT USE.
	Rollback(ctx context.Context) error
}

ExecutorTx is an executor which is a transaction. In addition to standard Executor operations, it may be committed or rolled back.

API is not stable. DO NOT IMPLEMENT.

type GetListenenerParams

type GetListenenerParams struct {
	Schema string
}

type IndexDropIfExistsParams

type IndexDropIfExistsParams struct {
	Index  string
	Schema string
}

type IndexExistsParams

type IndexExistsParams struct {
	Index  string
	Schema string
}

type IndexReindexArtifactsParams

type IndexReindexArtifactsParams struct {
	Index  string
	Schema string
}

type IndexReindexParams

type IndexReindexParams struct {
	Index  string
	Schema string
}

type IndexesExistParams

type IndexesExistParams struct {
	IndexNames []string
	Schema     string
}

type JobCancelParams

type JobCancelParams struct {
	ID                int64
	CancelAttemptedAt time.Time
	ControlTopic      string
	Now               *time.Time
	Schema            string
}

type JobCountByAllStatesParams

type JobCountByAllStatesParams struct {
	Schema string
}

type JobCountByQueueAndStateParams

type JobCountByQueueAndStateParams struct {
	QueueNames []string
	Schema     string
}

type JobCountByQueueAndStateResult

type JobCountByQueueAndStateResult struct {
	CountAvailable int64
	CountRunning   int64
	Queue          string
}

type JobCountByStateParams

type JobCountByStateParams struct {
	Schema string
	State  rivertype.JobState
}

type JobDeleteBeforeParams

type JobDeleteBeforeParams struct {
	CancelledDoDelete           bool
	CancelledFinalizedAtHorizon time.Time
	CompletedDoDelete           bool
	CompletedFinalizedAtHorizon time.Time
	DiscardedDoDelete           bool
	DiscardedFinalizedAtHorizon time.Time
	Max                         int
	QueuesExcluded              []string
	QueuesIncluded              []string
	Schema                      string
}

type JobDeleteManyParams

type JobDeleteManyParams JobListParams

type JobDeleteParams

type JobDeleteParams struct {
	ID     int64
	Schema string
}

type JobGetAvailableParams

type JobGetAvailableParams struct {
	ClientID string

	// Kind restricts claims to these kinds. Nil allows every kind; an empty,
	// non-nil slice allows none. Filtering occurs before the limit and locking.
	Kind []string

	MaxAttemptedBy int
	MaxToLock      int
	Now            *time.Time
	ProducerID     int64
	Queue          string
	Schema         string
}

type JobGetAvailableResult

type JobGetAvailableResult struct {
	// DecodeErrors contains decode errors keyed by job ID. It's nil when all
	// rows decoded successfully. Each entry corresponds to a row in Jobs whose
	// attempt should be failed instead of worked.
	DecodeErrors map[int64]error

	// Jobs contains every locked job, including rows that couldn't be fully
	// decoded. Fields that couldn't be decoded are left empty, with the error
	// recorded in DecodeErrors. Every job has been moved to `running`.
	Jobs []*rivertype.JobRow
}

JobGetAvailableResult is the result of JobGetAvailable.

type JobGetByIDManyParams

type JobGetByIDManyParams struct {
	ID     []int64
	Schema string
}

type JobGetByIDParams

type JobGetByIDParams struct {
	ID     int64
	Schema string
}

type JobGetByKindManyParams

type JobGetByKindManyParams struct {
	Kind   []string
	Schema string
}

type JobGetCancelRequestedParams

type JobGetCancelRequestedParams struct {
	ID     []int64
	Schema string
}

JobGetCancelRequestedParams restricts cancellation checks to specific job IDs.

type JobGetStuckParams

type JobGetStuckParams struct {
	AfterID      int64
	Max          int
	Schema       string
	StuckHorizon time.Time
}

type JobInsertFastManyParams

type JobInsertFastManyParams struct {
	Jobs   []*JobInsertFastParams
	Schema string
}

type JobInsertFastParams

type JobInsertFastParams struct {
	ID *int64
	// Args contains the raw underlying job arguments struct. It has already been
	// encoded into EncodedArgs, but the original is kept here for to leverage its
	// struct tags and interfaces, such as for use in unique key generation.
	Args         rivertype.JobArgs
	CreatedAt    *time.Time
	EncodedArgs  []byte
	Kind         string
	MaxAttempts  int
	Metadata     []byte
	Priority     int
	Queue        string
	ScheduledAt  *time.Time
	State        rivertype.JobState
	Tags         []string
	UniqueKey    []byte
	UniqueStates byte
}

type JobInsertFastResult

type JobInsertFastResult struct {
	Job                      *rivertype.JobRow
	UniqueSkippedAsDuplicate bool
}

type JobInsertFullManyParams

type JobInsertFullManyParams struct {
	Jobs   []*JobInsertFullParams
	Schema string
}

type JobInsertFullParams

type JobInsertFullParams struct {
	Attempt      int
	AttemptedAt  *time.Time
	AttemptedBy  []string
	CreatedAt    *time.Time
	EncodedArgs  []byte
	Errors       [][]byte
	FinalizedAt  *time.Time
	Kind         string
	MaxAttempts  int
	Metadata     []byte
	Priority     int
	Queue        string
	ScheduledAt  *time.Time
	Schema       string
	State        rivertype.JobState
	Tags         []string
	UniqueKey    []byte
	UniqueStates byte
}

type JobKindListParams

type JobKindListParams struct {
	After   string
	Exclude []string
	Match   string
	Max     int
	Schema  string
}

type JobListParams

type JobListParams struct {
	Max           int32
	NamedArgs     map[string]any
	OrderByClause string
	Schema        string
	WhereClause   string
}

type JobRescueManyParams

type JobRescueManyParams struct {
	ID           []int64
	Error        [][]byte
	FinalizedAt  []*time.Time
	ScheduledAt  []time.Time
	Schema       string
	State        []string
	StuckHorizon time.Time
}

type JobRetryParams

type JobRetryParams struct {
	ID     int64
	Now    *time.Time
	Schema string
}

type JobScheduleParams

type JobScheduleParams struct {
	Max    int
	Now    *time.Time
	Schema string
}

type JobScheduleResult

type JobScheduleResult struct {
	Job               rivertype.JobRow
	ConflictDiscarded bool
}

type JobSetStateIfRunningManyParams

type JobSetStateIfRunningManyParams struct {
	ID              []int64
	Attempt         []*int
	ErrData         [][]byte
	FinalizedAt     []*time.Time
	MetadataDoMerge []bool
	MetadataUpdates [][]byte
	Now             *time.Time
	ScheduledAt     []*time.Time
	Schema          string
	State           []rivertype.JobState
}

JobSetStateIfRunningManyParams are parameters to update the state of currently running jobs. Use one of the constructors below to ensure a correct combination of parameters.

type JobSetStateIfRunningParams

type JobSetStateIfRunningParams struct {
	ID              int64
	Attempt         *int
	ErrData         []byte
	FinalizedAt     *time.Time
	MetadataDoMerge bool
	MetadataUpdates []byte
	Reason          JobSetStateReason
	ScheduledAt     *time.Time
	Schema          string // added by completer
	State           rivertype.JobState
}

JobSetStateIfRunningParams are parameters to update the state of a currently running job. Use one of the constructors below to ensure a correct combination of parameters.

func JobSetStateCancelled

func JobSetStateCancelled(id int64, finalizedAt time.Time, errData []byte, metadataUpdates []byte) *JobSetStateIfRunningParams

func JobSetStateCompleted

func JobSetStateCompleted(id int64, finalizedAt time.Time, metadataUpdates []byte) *JobSetStateIfRunningParams

func JobSetStateDiscarded

func JobSetStateDiscarded(id int64, finalizedAt time.Time, errData []byte, metadataUpdates []byte) *JobSetStateIfRunningParams

func JobSetStateErrorAvailable

func JobSetStateErrorAvailable(id int64, scheduledAt time.Time, errData []byte, metadataUpdates []byte) *JobSetStateIfRunningParams

JobSetStateErrorAvailable makes an errored job immediately available.

func JobSetStateErrorRetryable

func JobSetStateErrorRetryable(id int64, scheduledAt time.Time, errData []byte, metadataUpdates []byte) *JobSetStateIfRunningParams

func JobSetStateInterrupted

func JobSetStateInterrupted(id int64, scheduledAt time.Time, attempt int, metadataUpdates []byte) *JobSetStateIfRunningParams

JobSetStateInterrupted makes a job that was interrupted by client shutdown immediately available without recording an error.

func JobSetStateSnoozed

func JobSetStateSnoozed(id int64, scheduledAt time.Time, attempt int, metadataUpdates []byte) *JobSetStateIfRunningParams

func JobSetStateSnoozedAvailable

func JobSetStateSnoozedAvailable(id int64, scheduledAt time.Time, attempt int, metadataUpdates []byte) *JobSetStateIfRunningParams

type JobSetStateReason

type JobSetStateReason string

JobSetStateReason describes why a running job's state was changed. It lets callers distinguish transitions that result in the same state, like a failed job being retried and a job interrupted by client shutdown both becoming available.

const (
	// JobSetStateReasonCancelled indicates that a job was cancelled.
	JobSetStateReasonCancelled JobSetStateReason = "cancelled"
	// JobSetStateReasonCompleted indicates that a job completed successfully.
	JobSetStateReasonCompleted JobSetStateReason = "completed"
	// JobSetStateReasonFailed indicates that a job failed.
	JobSetStateReasonFailed JobSetStateReason = "failed"
	// JobSetStateReasonInterrupted indicates that a job was interrupted by
	// client shutdown and made available to be worked again.
	JobSetStateReasonInterrupted JobSetStateReason = "interrupted"
	// JobSetStateReasonSnoozed indicates that a job was snoozed.
	JobSetStateReasonSnoozed JobSetStateReason = "snoozed"
)

type JobUpdateFullParams

type JobUpdateFullParams struct {
	ID                  int64
	AttemptDoUpdate     bool
	Attempt             int
	AttemptedAtDoUpdate bool
	AttemptedAt         *time.Time
	AttemptedByDoUpdate bool
	AttemptedBy         []string
	ErrorsDoUpdate      bool
	Errors              [][]byte
	FinalizedAtDoUpdate bool
	FinalizedAt         *time.Time
	MaxAttemptsDoUpdate bool
	MaxAttempts         int
	MetadataDoUpdate    bool
	Metadata            []byte
	Schema              string
	StateDoUpdate       bool
	State               rivertype.JobState
	// Deprecated and will be removed when advisory lock unique path is removed.
	UniqueKeyDoUpdate bool
	// Deprecated and will be removed when advisory lock unique path is removed.
	UniqueKey []byte
}

type JobUpdateParams

type JobUpdateParams struct {
	ID              int64
	MetadataDoMerge bool
	Metadata        []byte
	Schema          string
}

type Leader

type Leader struct {
	ElectedAt time.Time
	ExpiresAt time.Time
	LeaderID  string
}

Leader represents a River leader.

API is not stable. DO NOT USE.

type LeaderDeleteExpiredParams

type LeaderDeleteExpiredParams struct {
	Now    *time.Time
	Schema string
}

type LeaderElectParams

type LeaderElectParams struct {
	LeaderID string
	Now      *time.Time
	Schema   string
	TTL      time.Duration
}

type LeaderGetElectedLeaderParams

type LeaderGetElectedLeaderParams struct {
	Schema string
}

type LeaderInsertParams

type LeaderInsertParams struct {
	ElectedAt *time.Time
	ExpiresAt *time.Time
	LeaderID  string
	Now       *time.Time
	Schema    string
	TTL       time.Duration
}

type LeaderReelectParams

type LeaderReelectParams struct {
	ElectedAt time.Time
	LeaderID  string
	Now       *time.Time
	Schema    string
	TTL       time.Duration
}

type LeaderResignParams

type LeaderResignParams struct {
	ElectedAt       time.Time
	LeaderID        string
	LeadershipTopic string
	Schema          string
}

type Listener

type Listener interface {
	Close(ctx context.Context) error
	Connect(ctx context.Context) error
	Listen(ctx context.Context, topic string) error
	Ping(ctx context.Context) error
	Schema() string
	SetAfterConnectExec(sql string) // should only ever be used in testing
	Unlisten(ctx context.Context, topic string) error
	WaitForNotification(ctx context.Context) (*Notification, error)
}

Listener listens for notifications. In Postgres, this is a database connection where `LISTEN` has been run.

API is not stable. DO NOT IMPLEMENT.

type Migration

type Migration struct {
	// CreatedAt is when the migration was initially created.
	//
	// API is not stable. DO NOT USE.
	CreatedAt time.Time

	// Line is the migration line that the migration belongs to.
	//
	// API is not stable. DO NOT USE.
	Line string

	// Version is the version of the migration.
	//
	// API is not stable. DO NOT USE.
	Version int
}

Migration represents a River migration.

API is not stable. DO NOT USE.

type MigrationDeleteAssumingMainManyParams

type MigrationDeleteAssumingMainManyParams struct {
	Schema   string
	Versions []int
}

type MigrationDeleteByLineAndVersionManyParams

type MigrationDeleteByLineAndVersionManyParams struct {
	Line     string
	Schema   string
	Versions []int
}

type MigrationGetAllAssumingMainParams

type MigrationGetAllAssumingMainParams struct {
	Schema string
}

type MigrationGetByLineParams

type MigrationGetByLineParams struct {
	Line   string
	Schema string
}

type MigrationInsertManyAssumingMainParams

type MigrationInsertManyAssumingMainParams struct {
	Schema   string
	Versions []int
}

type MigrationInsertManyParams

type MigrationInsertManyParams struct {
	Line     string
	Schema   string
	Versions []int
}

type MigrationLockParams added in v0.52.0

type MigrationLockParams struct {
	Line   string
	Schema string
}

type Notification

type Notification struct {
	Payload string
	Topic   string
}

type NotificationDeleteBeforeParams

type NotificationDeleteBeforeParams struct {
	CreatedAtHorizon time.Time
	Max              int
	Schema           string
}

type NotifyManyParams

type NotifyManyParams struct {
	Payload []string
	Topic   string
	Schema  string
}

NotifyManyParams are parameters to issue many pubsub notifications all at once for a single topic.

type PostgresCapabilities

type PostgresCapabilities struct {
	SupportsListenNotify bool
	UniqueInsertMode     UniqueInsertMode
}

PostgresCapabilities describes database features detected by Postgres drivers. Drivers cache a successful detection for their lifetime.

func NewPostgresCapabilities

func NewPostgresCapabilities(product string, version int32, ybListenNotifyEnabled bool) *PostgresCapabilities

NewPostgresCapabilities detects features from the server's product, version, and settings.

type ProducerKeepAliveParams

type ProducerKeepAliveParams struct {
	ID                    int64
	QueueName             string
	Schema                string
	StaleUpdatedAtHorizon time.Time
}

type QueueCreateOrSetUpdatedAtParams

type QueueCreateOrSetUpdatedAtParams struct {
	Metadata  []byte
	Name      string
	Now       *time.Time
	PausedAt  *time.Time
	Schema    string
	UpdatedAt *time.Time
}

type QueueDeleteExpiredParams

type QueueDeleteExpiredParams struct {
	Max              int
	Schema           string
	UpdatedAtHorizon time.Time
}

type QueueGetParams

type QueueGetParams struct {
	Name   string
	Schema string
}

type QueueListParams

type QueueListParams struct {
	Max    int
	Schema string
}

type QueueNameListParams

type QueueNameListParams struct {
	After   string
	Exclude []string
	Match   string
	Max     int
	Schema  string
}

type QueuePauseParams

type QueuePauseParams struct {
	Name   string
	Now    *time.Time
	Schema string
}

type QueueResumeParams

type QueueResumeParams struct {
	Name   string
	Now    *time.Time
	Schema string
}

type QueueUpdateParams

type QueueUpdateParams struct {
	Metadata         []byte
	MetadataDoUpdate bool
	Name             string
	Schema           string
}

type Row

type Row interface {
	Scan(dest ...any) error
}

type Schema

type Schema struct {
	Name string
}

type SchemaCreateParams

type SchemaCreateParams struct {
	Schema string
}

type SchemaDropParams

type SchemaDropParams struct {
	Schema string
}

type SchemaGetExpiredParams

type SchemaGetExpiredParams struct {
	BeforeName string
	Prefix     string
}

type TableExistsParams

type TableExistsParams struct {
	Schema string
	Table  string
}

type TableTruncateParams

type TableTruncateParams struct {
	Schema string
	Table  []string
}

type UniqueInsertMode

type UniqueInsertMode uint32

UniqueInsertMode is a database-specific strategy for detecting whether a unique insert returned a newly inserted job or an existing one.

const (
	// UniqueInsertModeUnknown indicates that a database's mode hasn't been
	// detected yet.
	UniqueInsertModeUnknown UniqueInsertMode = iota

	// UniqueInsertModeMetadataNonce detects conflicts by putting a nonce in the
	// metadata of the proposed job and checking whether the returned job
	// contains it.
	UniqueInsertModeMetadataNonce

	// UniqueInsertModeReturningOld uses Postgres 18's OLD row support in
	// RETURNING.
	UniqueInsertModeReturningOld

	// UniqueInsertModeXmax uses Postgres's xmax system column.
	UniqueInsertModeXmax
)

func UniqueInsertModeFromProductAndVersion

func UniqueInsertModeFromProductAndVersion(product string, version int32) UniqueInsertMode

UniqueInsertModeFromProductAndVersion returns the unique insert mode appropriate for a database product and its Postgres-compatible server version number.

func (UniqueInsertMode) SQL

func (m UniqueInsertMode) SQL() string

SQL returns the SQL expression for the mode. UniqueInsertModeMetadataNonce always returns false because duplicate detection is performed in Go instead.

Directories

Path Synopsis
riverpgxv5 module
riversqlite module

Jump to

Keyboard shortcuts

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