postgres

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 9, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultOAuthStateTTL = 10 * time.Minute

DefaultOAuthStateTTL is the default time-to-live for OAuth states.

Variables

View Source
var (
	// ErrInvalidKeySize is returned when the encryption key is not 32 bytes.
	ErrInvalidKeySize = errors.New("encryption key must be 32 bytes")

	// ErrInvalidBlobSize is returned when the encrypted blob is too small.
	ErrInvalidBlobSize = errors.New("encrypted blob is too small")

	// ErrUnsupportedVersion is returned when the blob version is not supported.
	ErrUnsupportedVersion = errors.New("unsupported secret blob version")

	// ErrDecryptionFailed is returned when decryption fails (wrong key or corrupted data).
	ErrDecryptionFailed = errors.New("failed to decrypt secret blob")
)

Functions

func Down added in v0.3.0

func Down(ctx context.Context, db *sql.DB) error

Down rolls back the most recently applied migration.

func EnsureClean added in v0.3.0

func EnsureClean(ctx context.Context, db *sql.DB) error

EnsureClean returns nil if the database's currently-applied migration version equals the highest version embedded in the binary.

func MaxEmbeddedVersion added in v0.3.0

func MaxEmbeddedVersion() (int64, error)

MaxEmbeddedVersion returns the highest migration version present in the embedded migrations FS. Returns 0 if no migrations are embedded.

Walks the embedded FS directly rather than constructing a goose Provider: goose v3.27 Provider requires a non-nil DB even for source enumeration, and EnsureClean has to call this from contexts where the DB lives in a caller's hand. Filename-parsing is the documented goose convention (NNNN_description.sql) and is stable enough for our purposes.

func NullString

func NullString(s *string) sql.NullString

NullString converts a string pointer to sql.NullString

func NullTime

func NullTime(t *time.Time) sql.NullTime

NullTime converts a time pointer to sql.NullTime

func Status added in v0.3.0

func Status(ctx context.Context, db *sql.DB) error

Status prints applied / pending status of every embedded migration to stdout.

func StringPtr

func StringPtr(ns sql.NullString) *string

StringPtr converts sql.NullString to string pointer

func TimePtr

func TimePtr(nt sql.NullTime) *time.Time

TimePtr converts sql.NullTime to time pointer

func Up added in v0.3.0

func Up(ctx context.Context, db *sql.DB) error

Up applies all embedded up-migrations that have not yet been applied. It is idempotent: running it against a fully-migrated DB is a no-op.

func Version added in v0.3.0

func Version(ctx context.Context, db *sql.DB) (int64, error)

Version returns the highest migration version currently recorded as applied in the goose_db_version table. Returns 0 against a database that has never been migrated.

Types

type AdvisoryLock

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

AdvisoryLock implements DistributedLock using PostgreSQL advisory locks.

IMPORTANT LIMITATIONS: - Advisory locks are connection-scoped, not TTL-based - If the connection is lost, the lock is automatically released - TTL parameter is ignored (locks don't expire automatically) - Extend is a no-op since locks don't have TTL

For production multi-worker deployments, Redis locks are recommended. This is provided as a fallback when Redis is unavailable.

func NewAdvisoryLock

func NewAdvisoryLock(db *DB) *AdvisoryLock

NewAdvisoryLock creates a new PostgreSQL advisory lock adapter.

func (*AdvisoryLock) Acquire

func (l *AdvisoryLock) Acquire(ctx context.Context, name string, ttl time.Duration) (bool, error)

Acquire attempts to acquire a named advisory lock. Uses pg_try_advisory_lock which returns immediately without blocking.

Note: The TTL parameter is ignored - PostgreSQL advisory locks don't have TTL. The lock is held until explicitly released or the connection closes.

func (*AdvisoryLock) Extend

func (l *AdvisoryLock) Extend(ctx context.Context, name string, ttl time.Duration) error

Extend is a no-op for PostgreSQL advisory locks since they don't have TTL. Advisory locks are held until explicitly released or the connection closes.

func (*AdvisoryLock) Ping

func (l *AdvisoryLock) Ping(ctx context.Context) error

Ping checks if the PostgreSQL backend is healthy.

func (*AdvisoryLock) Release

func (l *AdvisoryLock) Release(ctx context.Context, name string) error

Release releases a named advisory lock. Uses pg_advisory_unlock to release the lock. Safe to call even if the lock is not held (returns false but no error).

type AuthorizationCodeStore added in v0.2.1

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

AuthorizationCodeStore implements driven.AuthorizationCodeStore using PostgreSQL.

func NewAuthorizationCodeStore added in v0.2.1

func NewAuthorizationCodeStore(db *sql.DB) *AuthorizationCodeStore

NewAuthorizationCodeStore creates a new PostgreSQL-backed authorization code store.

func (*AuthorizationCodeStore) Cleanup added in v0.2.1

func (s *AuthorizationCodeStore) Cleanup(ctx context.Context) error

Cleanup removes expired authorization codes.

func (*AuthorizationCodeStore) GetAndMarkUsed added in v0.2.1

func (s *AuthorizationCodeStore) GetAndMarkUsed(ctx context.Context, code string) (*domain.AuthorizationCode, error)

GetAndMarkUsed atomically retrieves the code and marks it as used.

func (*AuthorizationCodeStore) Save added in v0.2.1

Save stores a new authorization code.

type CapabilityStore

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

CapabilityStore implements driven.CapabilityStore against the per-row capability_preferences table. Each (team_id, capability_type) is one row; capabilities absent from the rowset have no explicit preference and fall back to descriptor defaults at resolution time.

func NewCapabilityStore

func NewCapabilityStore(db *DB) *CapabilityStore

NewCapabilityStore creates a new CapabilityStore.

func (*CapabilityStore) GetPreferences

func (s *CapabilityStore) GetPreferences(ctx context.Context, teamID string) (*domain.CapabilityPreferences, error)

GetPreferences returns every persisted toggle for the team. Empty result is not an error — the returned preferences's Toggles map is empty and callers fall back to descriptor defaults.

func (*CapabilityStore) SetToggles added in v0.4.0

func (s *CapabilityStore) SetToggles(ctx context.Context, teamID string, toggles map[domain.CapabilityType]bool) error

SetToggles upserts a partial set of toggles for the team. Toggles not present in the input are left unchanged in storage.

type Config

type Config struct {
	// MaxOpenConns is the maximum number of open connections
	MaxOpenConns int

	// MaxIdleConns is the maximum number of idle connections
	MaxIdleConns int

	// ConnMaxLifetime is the maximum lifetime of a connection
	ConnMaxLifetime time.Duration

	// ConnMaxIdleTime is the maximum idle time of a connection
	ConnMaxIdleTime time.Duration
}

Config holds database connection-pool tuning. The DSN itself is resolved out-of-band via a driven.DBCredentialProvider and is no longer carried on this struct.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults for the connection pool.

type ConnectionStore

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

ConnectionStore implements driven.ConnectionStore using PostgreSQL.

func NewConnectionStore

func NewConnectionStore(db *sql.DB, encryptor *SecretEncryptor) *ConnectionStore

NewConnectionStore creates a new PostgreSQL-backed connection store.

func (*ConnectionStore) Delete

func (s *ConnectionStore) Delete(ctx context.Context, id string) error

Delete removes a connection by ID.

func (*ConnectionStore) Get

Get retrieves a connection by ID with decrypted secrets.

func (*ConnectionStore) GetByAccountID

func (s *ConnectionStore) GetByAccountID(ctx context.Context, platform domain.PlatformType, accountID string) (*domain.Connection, error)

GetByAccountID retrieves a connection by platform type and account ID.

func (*ConnectionStore) GetByPlatform added in v0.2.1

func (s *ConnectionStore) GetByPlatform(ctx context.Context, platform domain.PlatformType) ([]*domain.ConnectionSummary, error)

GetByPlatform retrieves connections for a platform type (no secrets).

func (*ConnectionStore) GetByTenantID added in v0.4.0

func (s *ConnectionStore) GetByTenantID(ctx context.Context, platform domain.PlatformType, tenantID string) (*domain.Connection, error)

GetByTenantID retrieves an app-only connection by platform type and tenant ID. Returns nil, nil when not found (not an error; the caller decides how to handle absence).

func (*ConnectionStore) List

List retrieves all connections as summaries (no secrets).

func (*ConnectionStore) Save

func (s *ConnectionStore) Save(ctx context.Context, conn *domain.Connection) error

Save stores a new connection or updates an existing one.

func (*ConnectionStore) UpdateLastUsed

func (s *ConnectionStore) UpdateLastUsed(ctx context.Context, id string) error

UpdateLastUsed updates the last_used_at timestamp.

func (*ConnectionStore) UpdateSecrets

func (s *ConnectionStore) UpdateSecrets(ctx context.Context, id string, secrets *domain.ConnectionSecrets, expiry *time.Time) error

UpdateSecrets updates the encrypted secrets and OAuth metadata.

type DB

type DB struct {
	*sql.DB
}

DB wraps a sql.DB connection pool with Sercha-specific functionality

func Connect

func Connect(ctx context.Context, provider driven.DBCredentialProvider, cfg Config) (*DB, error)

Connect resolves the DSN via the supplied credential provider, enforces the sslmode=disable startup guard, opens a connection pool, and verifies connectivity. It does NOT run migrations; that responsibility belongs to either the `migrate` subcommand or the AUTO_MIGRATE branch in main.go.

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping checks if the database is reachable

func (*DB) Transaction

func (db *DB) Transaction(ctx context.Context, fn func(*sql.Tx) error) error

Transaction executes a function within a database transaction

type DocumentStore

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

DocumentStore implements driven.DocumentStore using PostgreSQL

func NewDocumentStore

func NewDocumentStore(db *DB) *DocumentStore

NewDocumentStore creates a new DocumentStore

func (*DocumentStore) Count

func (s *DocumentStore) Count(ctx context.Context) (int, error)

Count returns total document count

func (*DocumentStore) CountBySource

func (s *DocumentStore) CountBySource(ctx context.Context, sourceID string) (int, error)

CountBySource returns document count for a source

func (*DocumentStore) Delete

func (s *DocumentStore) Delete(ctx context.Context, id string) error

Delete deletes a document

func (*DocumentStore) DeleteBatch

func (s *DocumentStore) DeleteBatch(ctx context.Context, ids []string) error

DeleteBatch deletes multiple documents by ID

func (*DocumentStore) DeleteBySource

func (s *DocumentStore) DeleteBySource(ctx context.Context, sourceID string) error

DeleteBySource deletes all documents for a source

func (*DocumentStore) DeleteBySourceAndContainer added in v0.2.1

func (s *DocumentStore) DeleteBySourceAndContainer(ctx context.Context, sourceID, containerID string) error

DeleteBySourceAndContainer deletes all documents for a specific container within a source

func (*DocumentStore) Get

func (s *DocumentStore) Get(ctx context.Context, id string) (*domain.Document, error)

Get retrieves a document by ID

func (*DocumentStore) GetByExternalID

func (s *DocumentStore) GetByExternalID(ctx context.Context, sourceID, externalID string) (*domain.Document, error)

GetByExternalID retrieves a document by source and external ID

func (*DocumentStore) GetByIDs added in v0.3.0

func (s *DocumentStore) GetByIDs(ctx context.Context, ids []string) (map[string]*domain.Document, error)

GetByIDs fetches multiple documents in a single round trip. Missing IDs simply don't appear in the returned map. Avoids the N-query pattern previously used by services/search.go to materialise ranked results.

func (*DocumentStore) GetBySource

func (s *DocumentStore) GetBySource(ctx context.Context, sourceID string, limit, offset int) ([]*domain.Document, error)

GetBySource retrieves all documents for a source with pagination

func (*DocumentStore) ListExternalIDs

func (s *DocumentStore) ListExternalIDs(ctx context.Context, sourceID string) ([]string, error)

ListExternalIDs returns all external IDs for a source (for diff sync)

func (*DocumentStore) Save

func (s *DocumentStore) Save(ctx context.Context, doc *domain.Document) error

Save creates or updates a document

func (*DocumentStore) SaveBatch

func (s *DocumentStore) SaveBatch(ctx context.Context, docs []*domain.Document) error

SaveBatch saves multiple documents in a transaction

type EnvDBCredential added in v0.3.0

type EnvDBCredential struct {
	// EnvVar names the environment variable to read. If empty, "DATABASE_URL"
	// is used.
	EnvVar string
}

EnvDBCredential resolves the Postgres DSN from a process environment variable. The default variable is DATABASE_URL.

EnvDBCredential is the in-binary default impl of driven.DBCredentialProvider. Other impls (Vault, AWS Secrets Manager, IAM auth) are out of scope for this package but plug into the same port without changes to db.go.

func NewEnvDBCredential added in v0.3.0

func NewEnvDBCredential() *EnvDBCredential

NewEnvDBCredential returns an EnvDBCredential that reads DATABASE_URL.

func (*EnvDBCredential) Resolve added in v0.3.0

func (e *EnvDBCredential) Resolve(_ context.Context) (string, error)

Resolve reads the configured environment variable and returns its value as the DSN. Returns a non-nil error when the variable is unset or empty.

ctx is honoured by the interface contract but ignored here: env lookups are non-blocking process-state reads.

type OAuthClientStore added in v0.2.1

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

OAuthClientStore implements driven.OAuthClientStore using PostgreSQL.

func NewOAuthClientStore added in v0.2.1

func NewOAuthClientStore(db *sql.DB) *OAuthClientStore

NewOAuthClientStore creates a new PostgreSQL-backed OAuth client store.

func (*OAuthClientStore) Delete added in v0.2.1

func (s *OAuthClientStore) Delete(ctx context.Context, clientID string) error

Delete removes a client by client_id.

func (*OAuthClientStore) Get added in v0.2.1

func (s *OAuthClientStore) Get(ctx context.Context, clientID string) (*domain.OAuthClient, error)

Get retrieves a client by client_id.

func (*OAuthClientStore) List added in v0.2.1

List retrieves all registered clients.

func (*OAuthClientStore) Save added in v0.2.1

func (s *OAuthClientStore) Save(ctx context.Context, client *domain.OAuthClient) error

Save stores a new client or updates an existing one.

type OAuthStateStore

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

OAuthStateStore implements driven.OAuthStateStore using PostgreSQL.

func NewOAuthStateStore

func NewOAuthStateStore(db *sql.DB) *OAuthStateStore

NewOAuthStateStore creates a new PostgreSQL-backed OAuth state store.

func NewOAuthStateStoreWithTTL

func NewOAuthStateStoreWithTTL(db *sql.DB, ttl time.Duration) *OAuthStateStore

NewOAuthStateStoreWithTTL creates an OAuth state store with custom TTL.

func (*OAuthStateStore) Cleanup

func (s *OAuthStateStore) Cleanup(ctx context.Context) error

Cleanup removes expired states.

func (*OAuthStateStore) GetAndDelete

func (s *OAuthStateStore) GetAndDelete(ctx context.Context, state string) (*driven.OAuthState, error)

GetAndDelete atomically retrieves and deletes the state. Uses DELETE ... RETURNING for atomic single-use semantics.

func (*OAuthStateStore) Save

func (s *OAuthStateStore) Save(ctx context.Context, state *driven.OAuthState) error

Save stores a new OAuth state.

type OAuthTokenStore added in v0.2.1

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

OAuthTokenStore implements driven.OAuthTokenStore using PostgreSQL.

func NewOAuthTokenStore added in v0.2.1

func NewOAuthTokenStore(db *sql.DB) *OAuthTokenStore

NewOAuthTokenStore creates a new PostgreSQL-backed OAuth token store.

func (*OAuthTokenStore) Cleanup added in v0.2.1

func (s *OAuthTokenStore) Cleanup(ctx context.Context) error

Cleanup removes expired tokens.

func (*OAuthTokenStore) GetAccessToken added in v0.2.1

func (s *OAuthTokenStore) GetAccessToken(ctx context.Context, tokenID string) (*domain.OAuthAccessToken, error)

GetAccessToken retrieves an access token by its ID (jti claim).

func (*OAuthTokenStore) GetRefreshToken added in v0.2.1

func (s *OAuthTokenStore) GetRefreshToken(ctx context.Context, tokenID string) (*domain.OAuthRefreshToken, error)

GetRefreshToken retrieves a refresh token by its ID.

func (*OAuthTokenStore) ListClientsForUser added in v0.4.0

func (s *OAuthTokenStore) ListClientsForUser(ctx context.Context, userID string) ([]string, error)

ListClientsForUser returns the distinct client IDs the given user currently holds at least one non-revoked, non-expired refresh token for. See ListUsersForClient for the rationale on refresh-vs-access tokens.

func (*OAuthTokenStore) ListUsersForClient added in v0.4.0

func (s *OAuthTokenStore) ListUsersForClient(ctx context.Context, clientID string) ([]string, error)

ListUsersForClient returns the distinct user IDs that currently hold at least one non-revoked, non-expired refresh token for the given clientID.

Refresh tokens (not access tokens) are the right notion of "is this user connected": they outlive the access-token lifetime (~15 min) and only disappear when the user explicitly disconnects, an admin revokes, or the refresh token expires (typically ~30 days). An admin "who has connected app X?" view that filtered on access tokens would silently drop users in the gap between refreshes.

func (*OAuthTokenStore) RevokeAccessToken added in v0.2.1

func (s *OAuthTokenStore) RevokeAccessToken(ctx context.Context, tokenID string) error

RevokeAccessToken marks an access token as revoked.

func (*OAuthTokenStore) RevokeAllForClient added in v0.2.1

func (s *OAuthTokenStore) RevokeAllForClient(ctx context.Context, clientID string) error

RevokeAllForClient revokes all tokens (access and refresh) for a given client.

func (*OAuthTokenStore) RevokeRefreshToken added in v0.2.1

func (s *OAuthTokenStore) RevokeRefreshToken(ctx context.Context, tokenID string) error

RevokeRefreshToken marks a refresh token as revoked.

func (*OAuthTokenStore) RotateRefreshToken added in v0.2.1

func (s *OAuthTokenStore) RotateRefreshToken(ctx context.Context, oldTokenID string, newTokenID string) error

RotateRefreshToken marks the old token as rotated and returns the new token ID.

func (*OAuthTokenStore) SaveAccessToken added in v0.2.1

func (s *OAuthTokenStore) SaveAccessToken(ctx context.Context, token *domain.OAuthAccessToken) error

SaveAccessToken stores a new access token.

func (*OAuthTokenStore) SaveRefreshToken added in v0.2.1

func (s *OAuthTokenStore) SaveRefreshToken(ctx context.Context, token *domain.OAuthRefreshToken) error

SaveRefreshToken stores a new refresh token.

type SchedulerStore

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

SchedulerStore implements driven.SchedulerStore using PostgreSQL

func NewSchedulerStore

func NewSchedulerStore(db *DB) *SchedulerStore

NewSchedulerStore creates a new SchedulerStore

func (*SchedulerStore) DeleteScheduledTask

func (s *SchedulerStore) DeleteScheduledTask(ctx context.Context, id string) error

DeleteScheduledTask removes a scheduled task

func (*SchedulerStore) GetDueScheduledTasks

func (s *SchedulerStore) GetDueScheduledTasks(ctx context.Context) ([]*domain.ScheduledTask, error)

GetDueScheduledTasks retrieves scheduled tasks that are due to run

func (*SchedulerStore) GetScheduledTask

func (s *SchedulerStore) GetScheduledTask(ctx context.Context, id string) (*domain.ScheduledTask, error)

GetScheduledTask retrieves a scheduled task by ID

func (*SchedulerStore) ListScheduledTasks

func (s *SchedulerStore) ListScheduledTasks(ctx context.Context, teamID string) ([]*domain.ScheduledTask, error)

ListScheduledTasks retrieves all scheduled tasks for a team

func (*SchedulerStore) SaveScheduledTask

func (s *SchedulerStore) SaveScheduledTask(ctx context.Context, task *domain.ScheduledTask) error

SaveScheduledTask creates or updates a scheduled task

func (*SchedulerStore) UpdateLastRun

func (s *SchedulerStore) UpdateLastRun(ctx context.Context, id string, lastError string) error

UpdateLastRun updates the last run time and next run time

type SearchQueryRepository

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

SearchQueryRepository implements driven.SearchQueryRepository using PostgreSQL

func NewSearchQueryRepository

func NewSearchQueryRepository(db *DB) *SearchQueryRepository

NewSearchQueryRepository creates a new SearchQueryRepository

func (*SearchQueryRepository) GetSearchAnalytics

func (r *SearchQueryRepository) GetSearchAnalytics(ctx context.Context, teamID string, period domain.AnalyticsPeriod) (*domain.SearchAnalytics, error)

GetSearchAnalytics computes aggregated search analytics for a time period

func (*SearchQueryRepository) GetSearchHistory

func (r *SearchQueryRepository) GetSearchHistory(ctx context.Context, teamID string, limit int) ([]*domain.SearchQuery, error)

GetSearchHistory retrieves recent search queries

func (*SearchQueryRepository) GetSearchMetrics

func (r *SearchQueryRepository) GetSearchMetrics(ctx context.Context, teamID string, period domain.AnalyticsPeriod) (*domain.SearchMetrics, error)

GetSearchMetrics computes performance metrics for a time period

func (*SearchQueryRepository) Save

Save logs a search query for analytics tracking

type SecretEncryptor

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

SecretEncryptor handles AES-256-GCM encryption/decryption of secrets. The encrypted format is: version(1) || nonce(12) || ciphertext(N)

func NewSecretEncryptor

func NewSecretEncryptor(key []byte) (*SecretEncryptor, error)

NewSecretEncryptor creates a new encryptor with the given 32-byte key.

func (*SecretEncryptor) Decrypt

func (e *SecretEncryptor) Decrypt(blob []byte, value any) error

Decrypt decrypts a blob and unmarshals the result into the given value. The value should be a pointer to the target type.

func (*SecretEncryptor) DecryptString

func (e *SecretEncryptor) DecryptString(blob []byte) (string, error)

DecryptString decrypts a blob to a string.

func (*SecretEncryptor) Encrypt

func (e *SecretEncryptor) Encrypt(value any) ([]byte, error)

Encrypt encrypts the given value to a blob. The value is JSON-marshaled before encryption. Format: version(1) || nonce(12) || ciphertext

func (*SecretEncryptor) EncryptString

func (e *SecretEncryptor) EncryptString(s string) ([]byte, error)

EncryptString encrypts a simple string value.

type SessionStore

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

SessionStore implements driven.SessionStore using PostgreSQL

func NewSessionStore

func NewSessionStore(db *DB) *SessionStore

NewSessionStore creates a new SessionStore

func (*SessionStore) Delete

func (s *SessionStore) Delete(ctx context.Context, id string) error

Delete deletes a session

func (*SessionStore) DeleteByToken

func (s *SessionStore) DeleteByToken(ctx context.Context, token string) error

DeleteByToken deletes a session by token

func (*SessionStore) DeleteByUser

func (s *SessionStore) DeleteByUser(ctx context.Context, userID string) error

DeleteByUser deletes all sessions for a user (logout everywhere)

func (*SessionStore) Get

func (s *SessionStore) Get(ctx context.Context, id string) (*domain.Session, error)

Get retrieves a session by ID

func (*SessionStore) GetByRefreshToken

func (s *SessionStore) GetByRefreshToken(ctx context.Context, refreshToken string) (*domain.Session, error)

GetByRefreshToken retrieves a session by refresh token value

func (*SessionStore) GetByToken

func (s *SessionStore) GetByToken(ctx context.Context, token string) (*domain.Session, error)

GetByToken retrieves a session by token value

func (*SessionStore) ListByUser

func (s *SessionStore) ListByUser(ctx context.Context, userID string) ([]*domain.Session, error)

ListByUser lists all active sessions for a user

func (*SessionStore) Save

func (s *SessionStore) Save(ctx context.Context, session *domain.Session) error

Save stores a session

type SettingsStore

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

SettingsStore implements driven.SettingsStore using PostgreSQL

func NewSettingsStore

func NewSettingsStore(db *DB) *SettingsStore

NewSettingsStore creates a new SettingsStore

func (*SettingsStore) GetAISettings

func (s *SettingsStore) GetAISettings(ctx context.Context, teamID string) (*domain.AISettings, error)

GetAISettings retrieves AI-specific settings for a team Note: API keys and base URLs are NOT stored in database - they come from environment variables

func (*SettingsStore) GetSettings

func (s *SettingsStore) GetSettings(ctx context.Context, teamID string) (*domain.Settings, error)

GetSettings retrieves settings for a team Note: AI configuration is managed via AISettings (ai_settings table), not here Note: semantic_search_enabled column is deprecated - use capability_preferences table instead

func (*SettingsStore) SaveAISettings

func (s *SettingsStore) SaveAISettings(ctx context.Context, teamID string, settings *domain.AISettings) error

SaveAISettings persists AI-specific settings Note: Only provider and model are stored - API keys and base URLs come from environment

func (*SettingsStore) SaveSettings

func (s *SettingsStore) SaveSettings(ctx context.Context, settings *domain.Settings) error

SaveSettings persists team settings Note: AI configuration is managed via SaveAISettings, not here Note: semantic_search_enabled column is deprecated - use capability_preferences table instead

type SourceStore

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

SourceStore implements driven.SourceStore using PostgreSQL

func NewSourceStore

func NewSourceStore(db *DB) *SourceStore

NewSourceStore creates a new SourceStore

func (*SourceStore) CountByConnection

func (s *SourceStore) CountByConnection(ctx context.Context, connectionID string) (int, error)

CountByConnection returns the number of sources using a connection

func (*SourceStore) Delete

func (s *SourceStore) Delete(ctx context.Context, id string) error

Delete deletes a source

func (*SourceStore) Get

func (s *SourceStore) Get(ctx context.Context, id string) (*domain.Source, error)

Get retrieves a source by ID

func (*SourceStore) GetByName

func (s *SourceStore) GetByName(ctx context.Context, name string) (*domain.Source, error)

GetByName retrieves a source by name

func (*SourceStore) List

func (s *SourceStore) List(ctx context.Context) ([]*domain.Source, error)

List retrieves all sources

func (*SourceStore) ListByConnection

func (s *SourceStore) ListByConnection(ctx context.Context, connectionID string) ([]*domain.Source, error)

ListByConnection returns sources using a connection

func (*SourceStore) ListEnabled

func (s *SourceStore) ListEnabled(ctx context.Context) ([]*domain.Source, error)

ListEnabled retrieves all enabled sources

func (*SourceStore) Save

func (s *SourceStore) Save(ctx context.Context, source *domain.Source) error

Save creates or updates a source

func (*SourceStore) SetEnabled

func (s *SourceStore) SetEnabled(ctx context.Context, id string, enabled bool) error

SetEnabled updates the enabled status

func (*SourceStore) UpdateContainers

func (s *SourceStore) UpdateContainers(ctx context.Context, id string, containers []domain.Container) error

UpdateContainers updates the selected containers for a source

type SyncEventRepository added in v0.3.0

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

SyncEventRepository implements driven.SyncEventRepository using PostgreSQL

func NewSyncEventRepository added in v0.3.0

func NewSyncEventRepository(db *DB) *SyncEventRepository

NewSyncEventRepository creates a new SyncEventRepository

func (*SyncEventRepository) List added in v0.3.0

func (r *SyncEventRepository) List(ctx context.Context, teamID string, limit int) ([]*domain.SyncEvent, error)

List retrieves recent sync events for a team

func (*SyncEventRepository) ListBySource added in v0.3.0

func (r *SyncEventRepository) ListBySource(ctx context.Context, sourceID string, limit int) ([]*domain.SyncEvent, error)

ListBySource retrieves recent sync events for a specific source

func (*SyncEventRepository) Save added in v0.3.0

Save logs a sync event for audit tracking

type SyncFailedDocStore added in v0.4.0

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

SyncFailedDocStore is the Postgres-backed skip-list / retry-ledger the sync orchestrator uses to keep per-doc failures from stalling cursor advance. See port godoc for the contract; see migration 0003_sync_failed_documents.sql for the table.

func NewSyncFailedDocStore added in v0.4.0

func NewSyncFailedDocStore(db *DB) *SyncFailedDocStore

NewSyncFailedDocStore wires the store. db is required.

func (*SyncFailedDocStore) CountBySource added in v0.4.0

func (s *SyncFailedDocStore) CountBySource(ctx context.Context, sourceID string) (int, error)

CountBySource returns the row count for a source. Cheap; used for the small "12 docs failing" badge on the source detail page.

func (*SyncFailedDocStore) ListBySource added in v0.4.0

func (s *SyncFailedDocStore) ListBySource(ctx context.Context, sourceID string, limit int) ([]domain.SyncFailedDoc, error)

ListBySource returns every row for the source, regardless of retry status. Used by the admin endpoint that surfaces failing docs.

func (*SyncFailedDocStore) ListReadyForRetry added in v0.4.0

func (s *SyncFailedDocStore) ListReadyForRetry(ctx context.Context, sourceID string, now time.Time, limit int) ([]domain.SyncFailedDoc, error)

ListReadyForRetry returns the rows due for retry for sourceID. Bounded by limit so a source with a large backlog doesn't dominate one run; the ones not picked up will be retried on a subsequent tick.

func (*SyncFailedDocStore) MarkSucceeded added in v0.4.0

func (s *SyncFailedDocStore) MarkSucceeded(ctx context.Context, sourceID, externalID string) error

MarkSucceeded clears the skip-list row for (source_id, external_id). Called after the orchestrator's retry pre-pass successfully ingests a previously-failing doc. Idempotent — no error when no row exists.

func (*SyncFailedDocStore) Record added in v0.4.0

Record inserts a fresh row or bumps an existing one for (source_id, external_id). Attempt count, next_retry_after, and the terminal flag are computed from the supplied backoff policy plus any prior row's state.

Implementation note: the UPSERT uses a single round-trip with a CASE expression so attempt_count increments are atomic — no read, modify, write race possible. Backoff math is also done in SQL so the policy applied at INSERT is the same as the policy applied at UPDATE without re-implementing the formula in two places.

type SyncStateStore

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

SyncStateStore implements driven.SyncStateStore using PostgreSQL

func NewSyncStateStore

func NewSyncStateStore(db *DB) *SyncStateStore

NewSyncStateStore creates a new SyncStateStore

func (*SyncStateStore) Delete

func (s *SyncStateStore) Delete(ctx context.Context, sourceID string) error

Delete deletes sync state for a source

func (*SyncStateStore) Get

func (s *SyncStateStore) Get(ctx context.Context, sourceID string) (*domain.SyncState, error)

Get retrieves sync state for a source

func (*SyncStateStore) List

func (s *SyncStateStore) List(ctx context.Context) ([]*domain.SyncState, error)

List retrieves sync states for all sources

func (*SyncStateStore) Save

func (s *SyncStateStore) Save(ctx context.Context, state *domain.SyncState) error

Save creates or updates sync state

func (*SyncStateStore) UpdateCursor

func (s *SyncStateStore) UpdateCursor(ctx context.Context, sourceID string, cursor string) error

UpdateCursor updates the sync cursor

func (*SyncStateStore) UpdateStatus

func (s *SyncStateStore) UpdateStatus(ctx context.Context, sourceID string, status domain.SyncStatus) error

UpdateStatus updates only the status field

type UserStore

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

UserStore implements driven.UserStore using PostgreSQL

func NewUserStore

func NewUserStore(db *DB) *UserStore

NewUserStore creates a new UserStore

func (*UserStore) Delete

func (s *UserStore) Delete(ctx context.Context, id string) error

Delete deletes a user

func (*UserStore) Get

func (s *UserStore) Get(ctx context.Context, id string) (*domain.User, error)

Get retrieves a user by ID

func (*UserStore) GetByEmail

func (s *UserStore) GetByEmail(ctx context.Context, email string) (*domain.User, error)

GetByEmail retrieves a user by email

func (*UserStore) List

func (s *UserStore) List(ctx context.Context, teamID string) ([]*domain.User, error)

List retrieves all users for a team

func (*UserStore) Save

func (s *UserStore) Save(ctx context.Context, user *domain.User) error

Save creates or updates a user

func (*UserStore) UpdateLastLogin

func (s *UserStore) UpdateLastLogin(ctx context.Context, id string) error

UpdateLastLogin updates the last login timestamp

Jump to

Keyboard shortcuts

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