sqlite

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a resource is not found
	ErrNotFound = errors.New("resource not found")

	// ErrUserNotFound is returned when a user is not found
	ErrUserNotFound = fmt.Errorf("%w: user", ErrNotFound)

	// ErrTeamNotFound is returned when a team is not found
	ErrTeamNotFound = fmt.Errorf("%w: team", ErrNotFound)

	// ErrSourceNotFound is returned when a source is not found
	ErrSourceNotFound = fmt.Errorf("%w: source", ErrNotFound)

	// ErrSessionNotFound is returned when a session is not found
	ErrSessionNotFound = fmt.Errorf("%w: session", ErrNotFound)

	// ErrQueryNotFound is returned when a query is not found
	ErrQueryNotFound = fmt.Errorf("%w: query", ErrNotFound)

	// ErrUniqueConstraint is returned when a unique constraint is violated
	ErrUniqueConstraint = errors.New("unique constraint violation")

	// ErrUserExists is returned when a user with the same email already exists
	ErrUserExists = fmt.Errorf("%w: user with this email already exists", ErrUniqueConstraint)

	// ErrTeamExists is returned when a team with the same name already exists
	ErrTeamExists = fmt.Errorf("%w: team with this name already exists", ErrUniqueConstraint)

	// ErrSourceExists is returned when a source with the same database/table already exists
	ErrSourceExists = fmt.Errorf("%w: source with this database/table already exists", ErrUniqueConstraint)
)

Define standard error types

Functions

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError checks if an error is any type of not found error

func IsSourceNotFoundError

func IsSourceNotFoundError(err error) bool

IsSourceNotFoundError checks if an error is specifically a source not found error

func IsTeamNotFoundError

func IsTeamNotFoundError(err error) bool

IsTeamNotFoundError checks if an error is specifically a team not found error

func IsUniqueConstraintError

func IsUniqueConstraintError(err error) bool

IsUniqueConstraintError checks if an error is a unique constraint violation

func IsUserNotFoundError

func IsUserNotFoundError(err error) bool

IsUserNotFoundError checks if an error is specifically a user not found error

Types

type DB

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

DB provides access to the SQLite database and generated queries. It uses separate connections for reads and writes to optimize for SQLite's WAL mode which allows concurrent reads but only one writer at a time.

func New

func New(opts Options) (*DB, error)

New establishes a connection to the SQLite database, configures it, runs migrations, and returns a DB instance ready for use.

func (*DB) AddTeamMember

func (db *DB) AddTeamMember(ctx context.Context, teamID models.TeamID, userID models.UserID, role models.TeamRole) error

AddTeamMember creates an association between a user and a team. Note: This method currently checks for team/user existence before inserting. Consider if this check is strictly necessary or if relying on FK constraints is sufficient.

func (*DB) AddTeamSource

func (db *DB) AddTeamSource(ctx context.Context, teamID models.TeamID, sourceID models.SourceID) error

AddTeamSource creates an association between a team and a data source.

func (*DB) Close

func (db *DB) Close() error

Close gracefully shuts down both database connections.

func (*DB) CountAdminUsers

func (db *DB) CountAdminUsers(ctx context.Context) (int, error)

CountAdminUsers counts active users with the admin role.

func (*DB) CountUserSessions

func (db *DB) CountUserSessions(ctx context.Context, userID models.UserID) (int, error)

CountUserSessions returns the number of currently active (non-expired) sessions for a user.

func (*DB) CreateAPIToken added in v0.2.2

func (db *DB) CreateAPIToken(ctx context.Context, params sqlc.CreateAPITokenParams) (int64, error)

CreateAPIToken inserts a new API token record into the database.

func (*DB) CreateAlert added in v0.6.0

func (db *DB) CreateAlert(ctx context.Context, alert *models.Alert) error

CreateAlert inserts a new alert definition for a team/source pair.

func (*DB) CreateSession

func (db *DB) CreateSession(ctx context.Context, session *models.Session) error

CreateSession inserts a new session record. Note: The CreatedAt timestamp is generated by the SQL query.

func (*DB) CreateSource

func (db *DB) CreateSource(ctx context.Context, source *models.Source) error

CreateSource inserts a new source record into the database using sqlc generated queries. It maps the domain model to the sqlc parameters and handles potential unique constraint errors. The source ID and timestamps are populated back into the input source model upon success.

func (*DB) CreateTeam

func (db *DB) CreateTeam(ctx context.Context, team *models.Team) error

CreateTeam inserts a new team record. Populates the team ID and timestamps on the input model upon success.

func (*DB) CreateTeamSourceQuery

func (db *DB) CreateTeamSourceQuery(ctx context.Context, query *models.TeamQuery) error

CreateTeamSourceQuery inserts a new saved query record associated with a team and source. It populates the ID field on the input query model upon success.

func (*DB) CreateUser

func (db *DB) CreateUser(ctx context.Context, user *models.User) error

CreateUser inserts a new user record into the database. It sets default status if necessary and handles potential unique email constraint errors. Populates the user ID and timestamps on the input model upon success.

func (*DB) DeleteAPIToken added in v0.2.2

func (db *DB) DeleteAPIToken(ctx context.Context, params sqlc.DeleteAPITokenParams) error

DeleteAPIToken deletes an API token by ID and user ID (ensures user owns the token).

func (*DB) DeleteAlert added in v0.6.0

func (db *DB) DeleteAlert(ctx context.Context, alertID models.AlertID) error

DeleteAlert removes an alert definition.

func (*DB) DeleteExpiredAPITokens added in v0.2.2

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

DeleteExpiredAPITokens removes all expired API tokens.

func (*DB) DeleteSession

func (db *DB) DeleteSession(ctx context.Context, sessionID models.SessionID) error

DeleteSession removes a specific session record by ID. Returns nil if the session was deleted or did not exist.

func (*DB) DeleteSetting added in v0.6.0

func (db *DB) DeleteSetting(ctx context.Context, key string) error

DeleteSetting deletes a setting.

func (*DB) DeleteSource

func (db *DB) DeleteSource(ctx context.Context, id models.SourceID) error

DeleteSource removes a source record from the database by its ID.

func (*DB) DeleteTeam

func (db *DB) DeleteTeam(ctx context.Context, teamID models.TeamID) error

DeleteTeam removes a team record by ID. Associated memberships, source links, and queries should be handled by DB constraints (CASCADE DELETE).

func (*DB) DeleteTeamSourceQuery

func (db *DB) DeleteTeamSourceQuery(ctx context.Context, teamID models.TeamID, sourceID models.SourceID, queryID int) error

DeleteTeamSourceQuery removes a specific saved query record.

func (*DB) DeleteUser

func (db *DB) DeleteUser(ctx context.Context, id models.UserID) error

DeleteUser removes a user record by ID.

func (*DB) DeleteUserSessions

func (db *DB) DeleteUserSessions(ctx context.Context, userID models.UserID) error

DeleteUserSessions removes all session records associated with a specific user ID.

func (*DB) GetAPIToken added in v0.2.2

func (db *DB) GetAPIToken(ctx context.Context, id int64) (sqlc.ApiToken, error)

GetAPIToken retrieves an API token by ID.

func (*DB) GetAPITokenByHash added in v0.2.2

func (db *DB) GetAPITokenByHash(ctx context.Context, tokenHash string) (sqlc.ApiToken, error)

GetAPITokenByHash retrieves an API token by its hash (for authentication).

func (*DB) GetAlert added in v0.6.0

func (db *DB) GetAlert(ctx context.Context, alertID models.AlertID) (*models.Alert, error)

GetAlert retrieves an alert by ID.

func (*DB) GetAlertForTeamSource added in v0.6.0

func (db *DB) GetAlertForTeamSource(ctx context.Context, teamID models.TeamID, sourceID models.SourceID, alertID models.AlertID) (*models.Alert, error)

GetAlertForTeamSource retrieves an alert by ID ensuring it belongs to the specified team/source.

func (*DB) GetBoolSetting added in v0.6.0

func (db *DB) GetBoolSetting(ctx context.Context, key string, defaultValue bool) bool

GetBoolSetting retrieves a boolean setting value.

func (*DB) GetDurationSetting added in v0.6.0

func (db *DB) GetDurationSetting(ctx context.Context, key string, defaultValue time.Duration) time.Duration

GetDurationSetting retrieves a duration setting value.

func (*DB) GetFloat64Setting added in v0.6.0

func (db *DB) GetFloat64Setting(ctx context.Context, key string, defaultValue float64) float64

GetFloat64Setting retrieves a float64 setting value.

func (*DB) GetIntSetting added in v0.6.0

func (db *DB) GetIntSetting(ctx context.Context, key string, defaultValue int) int

GetIntSetting retrieves an integer setting value.

func (*DB) GetLatestUnresolvedAlertHistory added in v0.6.0

func (db *DB) GetLatestUnresolvedAlertHistory(ctx context.Context, alertID models.AlertID) (*models.AlertHistoryEntry, error)

GetLatestUnresolvedAlertHistory fetches the newest unresolved history entry.

func (*DB) GetSession

func (db *DB) GetSession(ctx context.Context, sessionID models.SessionID) (*models.Session, error)

GetSession retrieves a session by its unique ID. Returns core.ErrSessionNotFound (via handleNotFoundError) if not found.

func (*DB) GetSetting added in v0.6.0

func (db *DB) GetSetting(ctx context.Context, key string) (string, error)

GetSetting retrieves a setting value from the database.

func (*DB) GetSettingWithDefault added in v0.6.0

func (db *DB) GetSettingWithDefault(ctx context.Context, key, defaultValue string) string

GetSettingWithDefault retrieves a setting value or returns the default if not found.

func (*DB) GetSource

func (db *DB) GetSource(ctx context.Context, id models.SourceID) (*models.Source, error)

GetSource retrieves a single source by its ID. It returns models.ErrNotFound if the source does not exist.

func (*DB) GetSourceByName

func (db *DB) GetSourceByName(ctx context.Context, database, tableName string) (*models.Source, error)

GetSourceByName retrieves a single source by its database and table name combination. It returns models.ErrNotFound if no matching source exists.

func (*DB) GetTeam

func (db *DB) GetTeam(ctx context.Context, teamID models.TeamID) (*models.Team, error)

GetTeam retrieves a single team by its ID. Returns core.ErrTeamNotFound if not found.

func (*DB) GetTeamByName

func (db *DB) GetTeamByName(ctx context.Context, name string) (*models.Team, error)

GetTeamByName retrieves a team by its unique name.

func (*DB) GetTeamMember

func (db *DB) GetTeamMember(ctx context.Context, teamID models.TeamID, userID models.UserID) (*models.TeamMember, error)

GetTeamMember retrieves a specific team membership record. Returns nil, nil if the user is not a member of the team.

func (*DB) GetTeamSourceQuery

func (db *DB) GetTeamSourceQuery(ctx context.Context, teamID models.TeamID, sourceID models.SourceID, queryID int) (*models.SavedTeamQuery, error)

GetTeamSourceQuery retrieves a specific saved query by its ID, scoped to a team and source. Returns core.ErrQueryNotFound if not found.

func (*DB) GetUser

func (db *DB) GetUser(ctx context.Context, id models.UserID) (*models.User, error)

GetUser retrieves a single user by their ID. Returns core.ErrUserNotFound if not found.

func (*DB) GetUserByEmail

func (db *DB) GetUserByEmail(ctx context.Context, email string) (*models.User, error)

GetUserByEmail retrieves a single user by their email address. Returns core.ErrUserNotFound if not found.

func (*DB) InsertAlertHistory added in v0.6.0

func (db *DB) InsertAlertHistory(ctx context.Context, alertID models.AlertID, status models.AlertStatus, value *float64, message string, payload map[string]any) (*models.AlertHistoryEntry, error)

InsertAlertHistory records a history entry and returns the hydrated entry.

func (*DB) ListAPITokensForUser added in v0.2.2

func (db *DB) ListAPITokensForUser(ctx context.Context, userID int64) ([]sqlc.ApiToken, error)

ListAPITokensForUser retrieves all API tokens for a specific user.

func (*DB) ListActiveAlertsDue added in v0.6.0

func (db *DB) ListActiveAlertsDue(ctx context.Context) ([]*models.Alert, error)

ListActiveAlertsDue returns alerts that need evaluation.

func (*DB) ListAlertHistory added in v0.6.0

func (db *DB) ListAlertHistory(ctx context.Context, alertID models.AlertID, limit int) ([]*models.AlertHistoryEntry, error)

ListAlertHistory returns recent history entries for an alert.

func (*DB) ListAlertsByTeamAndSource added in v0.6.0

func (db *DB) ListAlertsByTeamAndSource(ctx context.Context, teamID models.TeamID, sourceID models.SourceID) ([]*models.Alert, error)

ListAlertsByTeamAndSource returns alerts for the given team/source.

func (*DB) ListQueriesByTeam added in v1.2.0

func (db *DB) ListQueriesByTeam(ctx context.Context, teamID models.TeamID) ([]*models.SavedTeamQuery, error)

ListQueriesByTeam retrieves all saved queries for a team across all sources.

func (*DB) ListQueriesByTeamAndSource

func (db *DB) ListQueriesByTeamAndSource(ctx context.Context, teamID models.TeamID, sourceID models.SourceID) ([]*models.SavedTeamQuery, error)

ListQueriesByTeamAndSource retrieves all saved queries for a specific team and source.

func (*DB) ListSettings added in v0.6.0

func (db *DB) ListSettings(ctx context.Context) ([]sqlc.SystemSetting, error)

ListSettings retrieves all settings.

func (*DB) ListSettingsByCategory added in v0.6.0

func (db *DB) ListSettingsByCategory(ctx context.Context, category string) ([]sqlc.SystemSetting, error)

ListSettingsByCategory retrieves settings for a specific category.

func (*DB) ListSourceTeams

func (db *DB) ListSourceTeams(ctx context.Context, sourceID models.SourceID) ([]*models.Team, error)

ListSourceTeams retrieves all teams that have access to a specific data source.

func (*DB) ListSources

func (db *DB) ListSources(ctx context.Context) ([]*models.Source, error)

ListSources retrieves all source records from the database, ordered by creation date.

func (*DB) ListSourcesForUser

func (db *DB) ListSourcesForUser(ctx context.Context, userID models.UserID) ([]*models.Source, error)

ListSourcesForUser lists all unique sources a user has access to across all their teams.

func (*DB) ListTeamMembers

func (db *DB) ListTeamMembers(ctx context.Context, teamID models.TeamID) ([]*models.TeamMember, error)

ListTeamMembers retrieves basic membership info for all members of a team.

func (*DB) ListTeamMembersWithDetails

func (db *DB) ListTeamMembersWithDetails(ctx context.Context, teamID models.TeamID) ([]*models.TeamMember, error)

ListTeamMembersWithDetails retrieves membership info including user email and full name.

func (*DB) ListTeamSources

func (db *DB) ListTeamSources(ctx context.Context, teamID models.TeamID) ([]*models.Source, error)

ListTeamSources retrieves all data sources associated with a specific team.

func (*DB) ListTeams

func (db *DB) ListTeams(ctx context.Context) ([]*models.Team, error)

ListTeams retrieves all teams along with their member counts.

func (*DB) ListTeamsForUser

func (db *DB) ListTeamsForUser(ctx context.Context, userID models.UserID) ([]sqlc.ListTeamsForUserRow, error)

ListTeamsForUser retrieves all teams a specific user is a member of, along with their role and team member count. This function now returns the raw sqlc-generated rows, and mapping is handled in the core layer.

func (*DB) ListUserTeams

func (db *DB) ListUserTeams(ctx context.Context, userID models.UserID) ([]*models.Team, error)

ListUserTeams retrieves all teams a specific user is a member of.

func (*DB) ListUsers

func (db *DB) ListUsers(ctx context.Context) ([]*models.User, error)

ListUsers retrieves all user records, ordered by creation date.

func (*DB) MarkAlertEvaluated added in v0.6.0

func (db *DB) MarkAlertEvaluated(ctx context.Context, alertID models.AlertID) error

MarkAlertEvaluated updates state after evaluation finishes without triggering.

func (*DB) MarkAlertTriggered added in v0.6.0

func (db *DB) MarkAlertTriggered(ctx context.Context, alertID models.AlertID) error

MarkAlertTriggered updates state when an alert fires.

func (*DB) PruneAlertHistory added in v0.6.0

func (db *DB) PruneAlertHistory(ctx context.Context, alertID models.AlertID, keep int) error

PruneAlertHistory keeps the most recent N entries for an alert.

func (*DB) RemoveTeamMember

func (db *DB) RemoveTeamMember(ctx context.Context, teamID models.TeamID, userID models.UserID) error

RemoveTeamMember removes a user's membership from a team.

func (*DB) RemoveTeamSource

func (db *DB) RemoveTeamSource(ctx context.Context, teamID models.TeamID, sourceID models.SourceID) error

RemoveTeamSource removes the association between a team and a data source.

func (*DB) ResolveAlertHistory added in v0.6.0

func (db *DB) ResolveAlertHistory(ctx context.Context, historyID int64, message string) error

ResolveAlertHistory marks a history entry as resolved with an optional message.

func (*DB) TeamHasSource

func (db *DB) TeamHasSource(ctx context.Context, teamID models.TeamID, sourceID models.SourceID) (bool, error)

TeamHasSource checks if a specific team has been granted access to a specific source.

func (*DB) ToggleQueryBookmark added in v1.1.0

func (db *DB) ToggleQueryBookmark(ctx context.Context, teamID models.TeamID, sourceID models.SourceID, queryID int) (bool, error)

ToggleQueryBookmark toggles the bookmark status of a query. Returns the new bookmark status after toggling.

func (*DB) UpdateAPITokenLastUsed added in v0.2.2

func (db *DB) UpdateAPITokenLastUsed(ctx context.Context, id int64) error

UpdateAPITokenLastUsed updates the last used timestamp for an API token.

func (*DB) UpdateAlert added in v0.6.0

func (db *DB) UpdateAlert(ctx context.Context, alert *models.Alert) error

UpdateAlert persists changes to an existing alert definition.

func (*DB) UpdateAlertHistoryPayload added in v0.6.0

func (db *DB) UpdateAlertHistoryPayload(ctx context.Context, historyID int64, payload map[string]any) error

UpdateAlertHistoryPayload updates the payload of an existing alert history entry.

func (*DB) UpdateSource

func (db *DB) UpdateSource(ctx context.Context, source *models.Source) error

UpdateSource updates an existing source record in the database. Note: This updates the entire record based on the provided model. The `updated_at` timestamp is automatically set by the query.

func (*DB) UpdateTeam

func (db *DB) UpdateTeam(ctx context.Context, team *models.Team) error

UpdateTeam updates an existing team record. The `updated_at` timestamp is automatically set by the query.

func (*DB) UpdateTeamMemberRole

func (db *DB) UpdateTeamMemberRole(ctx context.Context, teamID models.TeamID, userID models.UserID, role models.TeamRole) error

UpdateTeamMemberRole updates the role of an existing team member. Note: This method currently checks for member existence first.

func (*DB) UpdateTeamSourceQuery

func (db *DB) UpdateTeamSourceQuery(ctx context.Context, teamID models.TeamID, sourceID models.SourceID, queryID int, name, description, queryType, queryContent string) error

UpdateTeamSourceQuery updates an existing saved query record. Only non-empty fields in the input arguments are intended to be updated (though the current SQL updates all). The `updated_at` timestamp is automatically set by the query.

func (*DB) UpdateUser

func (db *DB) UpdateUser(ctx context.Context, user *models.User) error

UpdateUser updates an existing user record. Automatically sets the updated_at timestamp.

func (*DB) UpsertSetting added in v0.6.0

func (db *DB) UpsertSetting(ctx context.Context, key, value, valueType, category, description string, isSensitive bool) error

UpsertSetting inserts or updates a setting.

func (*DB) UserHasSourceAccess

func (db *DB) UserHasSourceAccess(ctx context.Context, userID models.UserID, sourceID models.SourceID) (bool, error)

UserHasSourceAccess checks if a user can access a specific source through any of their team memberships.

type Options

type Options struct {
	Logger *slog.Logger
	Config config.SQLiteConfig
}

Options holds configuration for creating a new DB instance.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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