store

package
v1.13.3 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: 0BSD Imports: 18 Imported by: 0

Documentation

Overview

Package store owns SQLite access and schema migrations.

Index

Constants

View Source
const BotUsername = "gitbay-bot"

BotUsername authors dependency-update issues. The account exists from migration 0028 with no key and no email: it authors, it never authenticates.

View Source
const MaxBuildLog = 2 << 20

MaxBuildLog caps a build's stored log; appends past it are dropped.

View Source
const StaleBuildDeadline = 90 * time.Minute

StaleBuildDeadline is how long a claimed build may stay running before the server gives up on it. Comfortably longer than the runner's own -timeout (45m by default), so this only fires when the runner never reported at all — it was killed, restarted, or lost the network mid-build.

Variables

View Source
var ErrDuplicateKey = errors.New("that key is already registered to another account; remove it there first or use a different key")

ErrDuplicateKey carries the exact user-facing message from the spec. It deliberately does not name the owning account (enumeration oracle).

View Source
var ErrExists = errors.New("already exists")

ErrExists marks unique-constraint refusals callers turn into messages.

View Source
var ErrLastAdmin = errors.New("that is the only instance admin; promote someone else first")

ErrLastAdmin refuses the demotion that would leave the instance with no admin at all.

View Source
var ErrNotFound = errors.New("not found")

Functions

func CombinedStatus added in v0.2.0

func CombinedStatus(statuses []CommitStatus) string

func FTSQuery added in v1.13.0

func FTSQuery(q string) string

FTSQuery turns what someone typed into an FTS5 MATCH expression.

FTS5's query language is not free text: bare `-`, `*`, `:`, `(`, `NOT` and an odd number of quotes are all syntax, and a syntax error surfaces as a failed query rather than no results. Nobody searching for "c++" or "foo: bar" means any of that. Every whitespace-separated run becomes a quoted phrase, which FTS5 treats as a literal and joins with an implicit AND, so the result is "rows containing all of these words".

func HashToken

func HashToken(token string) string

func IsInternal added in v1.10.0

func IsInternal(err error) bool

IsInternal reports whether err is the database or the I/O beneath it failing, as opposed to a sentinel or a message about the caller's input. Callers map it to a failure exit rather than a usage error.

func NewToken

func NewToken() (token, hash string, err error)

NewToken returns a fresh random token and its storage hash. Only the hash is persisted; the token itself goes to the user once.

Types

type APIToken

type APIToken struct {
	Name       string
	Scope      string
	CreatedAt  string
	ExpiresAt  *time.Time
	LastUsedAt *time.Time
}

type AccessEntry

type AccessEntry struct {
	Username string
	Role     string
}

type AdminRepo added in v1.4.0

type AdminRepo struct {
	Path       string // owner/name, the keyset cursor
	OwnerName  string
	Name       string
	Visibility string
	Archived   bool
	CreatedAt  string
	LastPush   string
}

AdminRepo is one repository as the instance admin lists it. LastPush is the newest push event, "" when nothing has been pushed.

type AdminUser added in v1.4.0

type AdminUser struct {
	Username  string
	IsAdmin   bool
	Pending   bool
	Disabled  bool
	CreatedAt string
	LastSeen  string
}

AdminUser is one account as the instance admin sees it. LastSeen is the most recent authentication by any of the account's SSH keys or API tokens, "" when there has been none.

type AuditEntry added in v0.2.0

type AuditEntry struct {
	ID        int64  `json:"id"`
	Actor     string `json:"actor,omitempty"`
	Action    string `json:"action"`
	Data      string `json:"data"`
	CreatedAt string `json:"created_at"`
}

type AuditFilter added in v1.4.0

type AuditFilter struct {
	Actor        string
	ActionPrefix string
	Since        string
	Limit        int
}

AuditFilter narrows AuditEntries. Actor is a username, or "-" for rows with no actor (host commands, auth failures). ActionPrefix matches the start of the action. Since is an ISO timestamp in the log's own format.

type Build added in v0.3.0

type Build struct {
	ID         int64
	RepoID     int64
	Number     int64
	Job        string
	SHA        string
	Ref        string
	Steps      string // JSON array of shell commands
	Status     string // pending|running|success|failure
	CreatedAt  string
	StartedAt  string
	FinishedAt string
	// Trusted is false for a merge request head fetched from another
	// repository: its steps run without the target's secrets.
	Trusted bool
}

Build is one CI job execution for one commit.

func (Build) Elapsed added in v1.2.0

func (b Build) Elapsed() time.Duration

Elapsed reports how long a build ran. Zero until it has both a start and a finish, which is every state but success and failure.

type Check added in v1.2.0

type Check struct {
	CommitStatus
	Build    int64         // build number, 0 when the check is not CI's
	Duration time.Duration // 0 until that build has finished
}

Check is a commit status paired with the build behind it. Only ci/<job> statuses have one; anything posted through `status set` reports just the state and when it last changed.

type CommitStatus added in v0.2.0

type CommitStatus struct {
	Context     string
	State       string // pending | success | failure | error
	Description string
	TargetURL   string
	Creator     string
	UpdatedAt   string
}

type Counts added in v0.2.0

type Counts struct {
	Users      int64 `json:"users"`
	Orgs       int64 `json:"orgs"`
	Repos      int64 `json:"repos"`
	Issues     int64 `json:"issues"`
	OpenIssues int64 `json:"open_issues"`
	MRs        int64 `json:"mrs"`
	OpenMRs    int64 `json:"open_mrs"`
}

type DashboardBuild added in v1.0.1

type DashboardBuild struct {
	RepoPath   string
	Number     int64
	Job        string
	Status     string
	SHA        string
	Ref        string
	CreatedAt  string
	FinishedAt string
}

DashboardBuild is one build row on the dashboard, with its repo resolved.

type DashboardItem added in v0.2.0

type DashboardItem struct {
	RepoPath  string
	Number    int64
	Title     string
	Author    string
	State     string
	UpdatedAt string
}

DashboardItem is one open issue or MR row on the logged-in homepage.

type Delivery

type Delivery struct {
	ID        int64
	WebhookID int64
	URL       string
	Secret    string
	EventID   int64
	EventKind string
	RepoPath  string
	Actor     string
	DataJSON  string
	EventAt   string
	Attempts  int
}

type DeliveryStatus

type DeliveryStatus struct {
	ID         int64
	URL        string
	EventKind  string
	Status     string // pending | delivered | failed
	Attempts   int
	LastStatus int
	LastError  string
	CreatedAt  string
}

type DepCheck added in v1.1.0

type DepCheck struct {
	RepoID      int64
	LastCheck   string
	LastError   string
	IssueNumber int64 // 0 until an issue has been opened
}

DepCheck is a repo's opt-in dependency sweep state. A row exists only while checking is enabled.

type DepReport added in v1.1.0

type DepReport struct {
	Ecosystem string
	Name      string
	Current   string
	Latest    string
}

DepReport is one dependency found to be behind, as last reported.

type DiffComment added in v0.2.0

type DiffComment struct {
	ID         int64
	Author     string
	HeadSHA    string
	Path       string
	Side       string
	Line       int64
	Body       string
	ReplyTo    int64 // 0 for thread roots
	ResolvedBy string
	// Pending marks a comment in a review its author has not submitted.
	// Only they can see it, and `mr review` publishes it.
	Pending   bool
	CreatedAt string
}

type Email added in v1.0.0

type Email struct {
	Address    string
	Verified   bool
	VerifiedBy string // smtp | admin, empty when unverified
	Primary    bool
}

Email is one address on an account, with the state the signature rules and notification routing depend on.

type FeedEvent added in v0.5.0

type FeedEvent struct {
	ID        int64
	RepoPath  string
	Actor     string
	Kind      string
	Data      string
	CreatedAt string
}

FeedEvent is one line of the dashboard's activity feed.

type Issue

type Issue struct {
	ID         int64
	RepoID     int64
	Number     int64
	Author     string
	Title      string
	Body       string
	BodyFormat string // md | org
	State      string // open | closed
	Milestone  string
	CreatedAt  string
	UpdatedAt  string
	Labels     []string
	Assignees  []string
}

type IssueComment

type IssueComment struct {
	Author     string
	Body       string
	BodyFormat string // md | org
	CreatedAt  string
	Kind       string // comment | system
}

type IssueFilter added in v1.8.0

type IssueFilter struct {
	State     string
	Label     string
	Assignee  string
	Author    string
	Milestone string
	Search    string // full-text over title and body
	Limit     int
	Before    int64
}

ListIssues returns issues for a repo; state is "open", "closed", or "all". limit 0 means everything; before (an issue number) starts the page strictly below it, matching the number-descending order. IssueFilter narrows a listing. Empty strings match anything; State "all" too. Milestone "none" selects issues with no milestone.

type Label added in v1.8.0

type Label struct {
	Name   string `json:"name"`
	Color  string `json:"color,omitempty"`
	Issues int64  `json:"issues"`
}

Label is one of a repository's issue labels with its colour, "" when none was set (the web then derives one from the name), and how many issues carry it.

type MR

type MR struct {
	ID           int64
	RepoID       int64
	Number       int64
	Author       string
	SourceRepoID int64  // 0 when the source repo is gone
	SourcePath   string // owner/name of source repo, "" when gone
	SourceRef    string
	TargetRef    string
	Title        string
	Body         string
	BodyFormat   string // md | org
	State        string // open | merged | closed | source_gone
	// Draft marks an open merge request that is not asking to be merged
	// yet. Not a state: see migration 0037.
	Draft      bool
	Milestone  string
	HeadSHA    string
	MergedBase string // target tip at merge time; base for historical diffs
	MergedAt   string // "" unless merged
	MergedBy   string // "" when unknown (imports) or the account is gone
	ClosedAt   string // "" unless closed without merging
	ClosedBy   string
	CreatedAt  string
	UpdatedAt  string
}

type MRFilter added in v1.8.0

type MRFilter struct {
	State     string
	Author    string
	Milestone string
	Search    string // full-text over title and body
	Limit     int
	Before    int64
}

ListMRs returns merge requests for a repo. limit 0 means everything; before (an MR number) starts the page strictly below it, matching the number-descending order. MRFilter narrows a listing. Empty strings match anything; State "all" too. Milestone "none" selects merge requests with no milestone.

type MRHead added in v1.13.0

type MRHead struct {
	SHA       string
	BaseSHA   string
	CreatedAt string
}

MRHead is one revision a merge request has had.

type MRReview

type MRReview struct {
	Reviewer  string
	Verdict   string
	HeadSHA   string
	Stale     bool
	CreatedAt string
}

type Milestone added in v0.2.0

type Milestone struct {
	ID          int64
	RepoID      int64
	Title       string
	Description string
	DueDate     string
	State       string // open | closed
	CreatedAt   string
	OpenItems   int // open issues + open MRs attached
	ClosedItems int // closed issues + merged/closed MRs attached
}

type Mirror added in v0.2.0

type Mirror struct {
	ID        int64
	RepoID    int64
	Direction string // push | pull
	URL       string
	Username  string
	Token     string
	Dirty     bool
	LastSync  string
	LastError string
}

Mirror propagates refs to (push) or from (pull) a foreign remote. The token is stored server-side — unlike import, mirroring is recurring — and must never be echoed back in listings.

type Notice added in v1.11.0

type Notice struct {
	ID        int64
	RepoPath  string
	Kind      string
	Actor     string
	Summary   string
	Path      string
	CreatedAt string
	ReadAt    string
}

Notice is one inbox row: what happened, where, and whether it has been read. Path is the web path without a leading slash, so a client turns it into a link by prefixing the site URL.

type Org

type Org struct {
	ID   int64
	Name string
}

type OrgMember

type OrgMember struct {
	Username string
	Role     string // member | admin
}

type PGPKey

type PGPKey struct {
	Fingerprint string
	UIDsJSON    string
	ExpiresAt   *time.Time
	RevokedAt   *time.Time
}

type PageDomain added in v0.3.0

type PageDomain struct {
	Domain     string
	RepoID     int64
	UserID     int64
	Token      string
	CreatedAt  string
	VerifiedAt string
}

PageDomain is one custom-domain claim. A claim starts pending — it holds the domain but serves nothing — and activates when the DNS challenge verifies. Pending claims expire so a squatted claim frees itself.

func (PageDomain) Verified added in v0.3.0

func (d PageDomain) Verified() bool

type Profile

type Profile struct {
	Description string `json:"description,omitempty"`
	Website     string `json:"website,omitempty"`
	About       string `json:"about,omitempty"`
	// AboutFormat is "md" or "org"; About has no filename to dispatch on.
	AboutFormat string        `json:"about_format,omitempty"`
	Links       []ProfileLink `json:"links,omitempty"`
}

Profile is the presentational half of a user or org.

type ProfileLink struct {
	Label string `json:"label,omitempty"`
	URL   string `json:"url"`
}

ProfileLink is one free-form link. The label is optional; a link without one renders as its URL.

type QueueBuildRow added in v1.4.0

type QueueBuildRow struct {
	Repo      string `json:"repo"`
	Number    int64  `json:"number"`
	Job       string `json:"job"`
	StartedAt string `json:"started_at"`
}

type QueueBuilds added in v1.4.0

type QueueBuilds struct {
	Pending       int64           `json:"pending"`
	Running       int64           `json:"running"`
	OldestPending string          `json:"oldest_pending,omitempty"`
	Items         []QueueBuildRow `json:"items"` // running builds, oldest first
}

type QueueDeliveryRow added in v1.4.0

type QueueDeliveryRow struct {
	ID        int64  `json:"id"`
	Repo      string `json:"repo"`
	URL       string `json:"url"`
	Attempts  int64  `json:"attempts"`
	Status    int64  `json:"last_status,omitempty"`
	LastError string `json:"last_error,omitempty"`
	FailedAt  string `json:"failed_at,omitempty"`
	CreatedAt string `json:"created_at"`
}

type QueueDepRow added in v1.4.0

type QueueDepRow struct {
	Repo      string `json:"repo"`
	LastCheck string `json:"last_check,omitempty"`
	LastError string `json:"last_error"`
}

type QueueDeps added in v1.4.0

type QueueDeps struct {
	Errors int64         `json:"errors"`
	Items  []QueueDepRow `json:"items"`
}

type QueueMail added in v1.4.0

type QueueMail struct {
	Pending       int64          `json:"pending"`
	Retrying      int64          `json:"retrying"`
	Failed        int64          `json:"failed"`
	OldestPending string         `json:"oldest_pending,omitempty"`
	Items         []QueueMailRow `json:"items"`
}

type QueueMailRow added in v1.4.0

type QueueMailRow struct {
	ID        int64  `json:"id"`
	Recipient string `json:"recipient"`
	Subject   string `json:"subject"`
	Attempts  int64  `json:"attempts"`
	LastError string `json:"last_error,omitempty"`
	FailedAt  string `json:"failed_at,omitempty"`
	CreatedAt string `json:"created_at"`
}

type QueueMirrorRow added in v1.4.0

type QueueMirrorRow struct {
	ID        int64  `json:"id"`
	Repo      string `json:"repo"`
	Direction string `json:"direction"`
	URL       string `json:"url"`
	LastSync  string `json:"last_sync,omitempty"`
	LastError string `json:"last_error"`
}

type QueueMirrors added in v1.4.0

type QueueMirrors struct {
	Dirty  int64            `json:"dirty"` // waiting for a sync
	Errors int64            `json:"errors"`
	Items  []QueueMirrorRow `json:"items"` // the ones whose last sync failed
}

type QueueWebhooks added in v1.4.0

type QueueWebhooks struct {
	Pending       int64              `json:"pending"`
	Retrying      int64              `json:"retrying"` // pending with at least one failed attempt
	Failed        int64              `json:"failed"`   // dead-lettered
	OldestPending string             `json:"oldest_pending,omitempty"`
	Items         []QueueDeliveryRow `json:"items"` // retrying and dead-lettered, newest first
}

type QueuedMail added in v0.2.0

type QueuedMail struct {
	ID        int64
	Recipient string
	Subject   string
	Body      string
	Attempts  int
}

type Queues added in v1.4.0

type Queues struct {
	Webhooks QueueWebhooks `json:"webhooks"`
	Mail     QueueMail     `json:"mail"`
	Mirrors  QueueMirrors  `json:"mirrors"`
	Builds   QueueBuilds   `json:"builds"`
	Deps     QueueDeps     `json:"deps"`
}

Queues is the state of every background worker, for the instance admin: what is waiting, what is retrying, and what has given up. Item lists are capped so a flood of one kind cannot bury the others.

type Release added in v0.2.0

type Release struct {
	ID          int64
	RepoID      int64
	Tag         string
	Title       string
	Notes       string
	NotesFormat string // md | org
	Author      string
	CreatedAt   string
	Assets      []ReleaseAsset
}

type ReleaseAsset added in v0.2.0

type ReleaseAsset struct {
	ID         int64
	Name       string
	Size       int64
	SHA256     string
	UploadedAt string
}

type Repo

type Repo struct {
	ID            int64
	OwnerKind     string // user | org
	OwnerID       int64
	OwnerName     string // resolved for display and disk paths
	Name          string
	Visibility    string // public | private
	DefaultBranch string
	ForkOf        int64 // 0 when not a fork
	Settings      RepoSettings
}

func (Repo) Path

func (r Repo) Path() string

Path returns the canonical owner/name form.

type RepoSettings

type RepoSettings struct {
	ProtectedBranches    []string `json:"protected_branches,omitempty"`
	RequireSignedCommits bool     `json:"require_signed_commits,omitempty"`
	RequireChecks        bool     `json:"require_checks,omitempty"`
	RequireApprovals     int      `json:"require_approvals,omitempty"`
	RequireResolved      bool     `json:"require_resolved,omitempty"`
	RequireCodeowners    bool     `json:"require_codeowners,omitempty"`
	GitDaemon            bool     `json:"git_daemon,omitempty"`
	Archived             bool     `json:"archived,omitempty"`
	Website              string   `json:"website,omitempty"`
}

type Retention added in v1.12.0

type Retention struct {
	Audit             time.Duration
	Events            time.Duration
	WebhookDeliveries time.Duration
	Mail              time.Duration
}

Retention says how long each capped table keeps a row. A zero duration means keep forever, which is what an instance that has not configured retention gets: growing is a decision, but so is deleting an audit trail, and the second one is not made on an operator's behalf.

type Runner added in v1.6.0

type Runner struct {
	Username string `json:"username"`
	LastSeen string `json:"last_seen"`
	Scope    string `json:"scope,omitempty"` // comma-joined owner/name, "" for any
	// The build it holds, if any.
	BuildRepo   string `json:"build_repo,omitempty"`
	BuildNumber int64  `json:"build_number,omitempty"`
	BuildJob    string `json:"build_job,omitempty"`
	StartedAt   string `json:"started_at,omitempty"`
}

Runner is one runner account as the instance admin sees it.

type SSHKey

type SSHKey struct {
	ID          int64
	UserID      int64
	Fingerprint string
	Algo        string
	Blob        []byte
	Scope       string
	CreatedAt   string
	LastUsedAt  string // "" when the key has never authenticated
}

type Schedule added in v0.3.0

type Schedule struct {
	RepoID  int64
	Job     string
	Cron    string
	NextRun string
}

Schedule is one repo job's cron entry.

type SigDB

type SigDB struct{ *Store }

SigDB adapts Store to the verifier's interface and owns the epoch cache.

func (SigDB) PGPKeyByIssuer

func (d SigDB) PGPKeyByIssuer(keyIDHex string) (sig.PGPKeyInfo, string, bool, error)

func (SigDB) SSHSignerByFingerprint

func (d SigDB) SSHSignerByFingerprint(fp string) (sig.SSHKeyInfo, bool, error)

func (SigDB) VerifiedEmails

func (d SigDB) VerifiedEmails(userID int64) ([]string, error)

type Store

type Store struct {
	DB *sql.DB
}

func Open

func Open(path string) (*Store, error)

Open opens (creating if needed) the database at path with WAL mode and foreign keys enforced. Use ":memory:" in tests.

_txlock=immediate is what serialises writers. Every transaction in this package writes, and a deferred one takes the write lock only when it reaches its first write — by which point another writer may hold it. SQLite answers that with SQLITE_BUSY and does not invoke the busy handler, because waiting would deadlock two transactions each holding a read lock the other needs; busy_timeout cannot help. Measured with eight concurrent read-then-write transactions, 44% of them failed. Beginning immediate takes the write lock up front, where busy_timeout does apply, so a second writer waits its turn: the same load runs with no failures, and readers, which WAL keeps out of the way, are unaffected (#121).

func (*Store) APITokenUser

func (s *Store) APITokenUser(tokenHash string) (User, string, error)

APITokenUser resolves a presented token to its user and scope; expired and unknown tokens fail identically.

func (*Store) AccessRole

func (s *Store) AccessRole(repoID, userID int64) (string, error)

AccessRole returns the user's effective role on the repo ("" if none): the strongest of any explicit grant, the role derived from org membership (org admin -> admin; plain member -> the org's members_role, 'write' by default so the pre-teams model is the degenerate case), and any team grants on the repo.

func (*Store) ActivityByDay added in v0.3.0

func (s *Store) ActivityByDay(userID int64, sinceDay string) (map[string]int, error)

ActivityByDay aggregates a user's activity per day since the given day: commits landed on default branches plus everything the events table attributes to them (issues, MRs, comments, releases, pushes).

func (*Store) AddDiffComment added in v0.2.0

func (s *Store) AddDiffComment(mrID, authorID int64, headSHA, path, side string, line int64, body string, replyTo int64, pending bool) (int64, error)

AddDiffComment creates a thread root (replyTo 0) or a reply. Replies inherit the root's anchor and must belong to the same MR.

func (*Store) AddEmail

func (s *Store) AddEmail(userID int64, address, verifiedBy string, primary bool) error

AddEmail adds an address; verifiedBy is "" (unverified), "smtp", or "admin". Adding an already-verified address bumps the key epoch: it is a trust input for signature states.

func (*Store) AddIssueComment

func (s *Store) AddIssueComment(issueID, authorID int64, body, format string) error

func (*Store) AddIssueSystemComment added in v0.2.0

func (s *Store) AddIssueSystemComment(issueID, actorID int64, body string) error

AddIssueSystemComment records an informational entry (commit references, automated closes). The actor is kept for provenance but the entry displays as coming from the system, not the user.

func (*Store) AddMRComment

func (s *Store) AddMRComment(mrID, authorID int64, body, format string) error

func (*Store) AddMRReview

func (s *Store) AddMRReview(mrID, reviewerID int64, verdict, headSHA string) error

func (*Store) AddMRSystemComment added in v0.2.0

func (s *Store) AddMRSystemComment(mrID, actorID int64, body string) error

AddMRSystemComment is the informational counterpart of AddMRComment.

func (*Store) AddMirror added in v0.2.0

func (s *Store) AddMirror(repoID int64, direction, url, username, token string) (int64, error)

func (*Store) AddNotice added in v1.11.0

func (s *Store) AddNotice(userID, repoID int64, kind, actor, summary, path string) error

AddNotice files one inbox row. Best-effort like the mail it accompanies: the action it reports has already succeeded.

func (*Store) AddPGPKey

func (s *Store) AddPGPKey(userID int64, fingerprint, armored, uidsJSON string, expiresAt, revokedAt *time.Time) error

AddPGPKey registers an OpenPGP key and bumps the key epoch.

func (*Store) AddPageDomain added in v0.3.0

func (s *Store) AddPageDomain(domain string, repoID, userID int64, token string, ttlSeconds int) error

AddPageDomain claims a domain for a repo. Expired pending claims (any repo's) are cleared first, so abandonment frees the name; live claims make the insert fail with ErrExists.

func (*Store) AddReleaseAsset added in v0.2.0

func (s *Store) AddReleaseAsset(releaseID int64, name string, size int64, sha256 string) error

func (*Store) AddSSHKey

func (s *Store) AddSSHKey(userID int64, fingerprint, algo string, blob []byte, scope string) error

AddSSHKey registers a key and bumps the key epoch in one transaction.

func (*Store) AddTeamMember added in v0.3.0

func (s *Store) AddTeamMember(teamID, userID int64) error

func (*Store) AddTopic added in v0.2.0

func (s *Store) AddTopic(repoID int64, topic string) error

AddTopic is idempotent: adding an existing topic is not an error.

func (*Store) AddWebhook

func (s *Store) AddWebhook(repoID int64, url, secret, events string) (int64, error)

func (*Store) AdminUserByName added in v1.4.0

func (s *Store) AdminUserByName(name string) (AdminUser, error)

AdminUserByName is the ListUsers row for one account.

func (*Store) AppendBuildLog added in v0.3.0

func (s *Store) AppendBuildLog(id int64, chunk []byte) error

AppendBuildLog adds a chunk to the build's log, dropping bytes past the cap.

func (*Store) AssignedIssues added in v0.5.0

func (s *Store) AssignedIssues(userID int64) ([]DashboardItem, error)

func (*Store) Audit added in v0.2.0

func (s *Store) Audit(actorID int64, action string, data map[string]any)

Audit appends to the security feed. Events are the product feed; this records who did what, from where, for an operator. actorID 0 means the host admin (gitbayd admin commands) or an unauthenticated source.

func (*Store) AuditEntries added in v0.2.0

func (s *Store) AuditEntries(f AuditFilter) ([]AuditEntry, error)

func (*Store) BuildByID added in v0.3.0

func (s *Store) BuildByID(id int64) (Build, error)

func (*Store) BuildByNumber added in v0.3.0

func (s *Store) BuildByNumber(repoID, number int64) (Build, error)

func (*Store) BuildLog added in v0.3.0

func (s *Store) BuildLog(id int64) ([]byte, error)

BuildLog returns the stored log bytes.

func (*Store) BuildSecrets added in v0.3.0

func (s *Store) BuildSecrets(repoID int64) (map[string]string, error)

BuildSecrets returns the values, for injection into a claimed build.

func (*Store) BuildsForCommit added in v1.2.0

func (s *Store) BuildsForCommit(repoID int64, sha string) (map[string]Build, error)

BuildsForCommit returns the newest build per job for one commit. A merge request's checks are ci/<job> statuses; this is where their timing comes from, in one query rather than one per check.

func (*Store) CachedSignature

func (s *Store) CachedSignature(repoID int64, sha string, epoch int64) (sig.Result, bool, error)

CachedSignature returns a cached result and whether it is current at the given epoch.

func (*Store) CancelBuild added in v1.6.0

func (s *Store) CancelBuild(id int64) error

CancelBuild withdraws a queued or running build. A running one is ended by the runner, which learns of the cancellation when its log session is closed, and whose later report lands on a row that already says cancelled.

func (*Store) ChecksForCommit added in v1.2.0

func (s *Store) ChecksForCommit(repoID int64, sha string) ([]Check, string, error)

ChecksForCommit lists a commit's checks with their timing, and reduces them to one combined state. Two queries at most, whatever the surface.

func (*Store) ClaimBuild added in v0.3.0

func (s *Store) ClaimBuild(repoIDs []int64) (Build, bool, error)

ClaimBuild atomically hands the oldest pending build to a runner. ClaimBuild takes the oldest pending build and marks it running. A non-empty repoIDs restricts the claim to those repositories, which is how a runner on a machine that should not execute every repository's steps limits what it picks up.

func (*Store) ClearPending

func (s *Store) ClearPending(userID int64) error

ClearPending activates a pending account.

func (*Store) Close

func (s *Store) Close() error

func (*Store) CombinedStatusFor added in v1.0.0

func (s *Store) CombinedStatusFor(repoID int64, shas []string) (map[string]string, error)

CombinedStatus reduces per-context states to one: error/failure dominate, then pending, then success; "" when no statuses exist. CombinedStatusFor returns the combined state for each of several commits in one query. The log lists fifty commits at a time; asking per commit turns one page into fifty round trips.

func (*Store) ConsumeEmailToken

func (s *Store) ConsumeEmailToken(userID int64, tokenHash string) (string, error)

ConsumeEmailToken redeems a verification code for the given user.

func (*Store) ConsumeInvite

func (s *Store) ConsumeInvite(codeHash string) (string, error)

ConsumeInvite redeems an invite exactly once, returning the address it was issued for. Used and unknown codes fail identically.

func (*Store) ConsumeLoginToken

func (s *Store) ConsumeLoginToken(hash string) (int64, error)

ConsumeLoginToken redeems a token exactly once; expired or used tokens fail identically.

func (*Store) CountEmailTokensSince added in v1.9.0

func (s *Store) CountEmailTokensSince(userID int64, since time.Time) (int, error)

CountEmailTokensSince is how many verification codes an account has asked for since a moment, used or not.

func (*Store) CountPendingComments added in v1.13.0

func (s *Store) CountPendingComments(mrID, authorID int64) int

CountPendingComments is how many unsubmitted comments an author holds on an MR, for the reminder that they have a review in progress.

func (*Store) CreateAPIToken

func (s *Store) CreateAPIToken(userID int64, name, tokenHash, scope string, expires *time.Time) error

CreateAPIToken stores a token hash; expires nil means no expiry.

func (*Store) CreateBuild added in v0.3.0

func (s *Store) CreateBuild(repoID int64, job, sha, ref, stepsJSON string, trusted bool) (int64, error)

CreateBuild allocates the per-repo build number in the same transaction as the insert, like issue and MR numbers.

func (*Store) CreateEmailToken

func (s *Store) CreateEmailToken(userID int64, address, tokenHash string, ttl time.Duration) error

CreateEmailToken stores a verification code hash for one address.

func (*Store) CreateFork added in v1.10.0

func (s *Store) CreateFork(ownerKind string, ownerID int64, name, visibility string, forkOf int64) (int64, error)

CreateFork is CreateRepo with fork_of set in the same insert, so a fork never exists for a moment as a plain repository (#108).

func (*Store) CreateInvite

func (s *Store) CreateInvite(codeHash, email string) error

CreateInvite stores an invite code hash bound to an email address.

func (*Store) CreateIssue

func (s *Store) CreateIssue(repoID, authorID int64, title, body, format string) (int64, error)

CreateIssue allocates the per-repo number from the repo counter inside the same transaction as the insert — MAX(number)+1 races.

func (*Store) CreateLoginToken

func (s *Store) CreateLoginToken(userID int64, hash string, ttl time.Duration) error

CreateLoginToken stores a one-time login token hash.

func (*Store) CreateMR

func (s *Store) CreateMR(repoID, authorID, sourceRepoID int64, sourceRef, targetRef, title, body, headSHA, format string, draft bool) (int64, error)

func (*Store) CreateMilestone added in v0.2.0

func (s *Store) CreateMilestone(repoID int64, title, description, due string) (int64, error)

func (*Store) CreateOrg

func (s *Store) CreateOrg(name string, creatorID int64) (int64, error)

CreateOrg makes an organization with the creator as its first admin.

func (*Store) CreateRegisteredUser

func (s *Store) CreateRegisteredUser(username string, pending bool) (int64, error)

CreateRegisteredUser makes a self-registered account, pending until its email is verified.

func (*Store) CreateRelease added in v0.2.0

func (s *Store) CreateRelease(repoID int64, tag, title, notes string, authorID int64, format string) (int64, error)

func (*Store) CreateRepo

func (s *Store) CreateRepo(ownerKind string, ownerID int64, name, visibility string) (int64, error)

func (*Store) CreateTeam added in v0.3.0

func (s *Store) CreateTeam(orgID int64, name string) (int64, error)

func (*Store) CreateUser

func (s *Store) CreateUser(username string, isAdmin bool) (int64, error)

func (*Store) CreateWebSession

func (s *Store) CreateWebSession(hash string, userID int64, ttl time.Duration) error

func (*Store) DashboardIssues added in v0.2.0

func (s *Store) DashboardIssues(userID int64) ([]DashboardItem, error)

func (*Store) DashboardMRs added in v0.2.0

func (s *Store) DashboardMRs(userID int64) ([]DashboardItem, error)

DashboardMRs returns open merge requests involving the user: on their repositories (owned, granted, org) or authored by them anywhere.

func (*Store) DeleteLabel added in v1.8.0

func (s *Store) DeleteLabel(repoID int64, name string) error

DeleteLabel removes a label and takes it off every issue.

func (*Store) DeleteOrg

func (s *Store) DeleteOrg(orgID int64) error

DeleteOrg removes an empty organization; orgs still owning repositories are refused.

func (*Store) DeleteRelease added in v0.2.0

func (s *Store) DeleteRelease(id int64) error

func (*Store) DeleteRepo

func (s *Store) DeleteRepo(repoID int64) error

func (*Store) DeleteTeam added in v0.3.0

func (s *Store) DeleteTeam(teamID int64) error

func (*Store) DeleteUser added in v0.3.0

func (s *Store) DeleteUser(id int64) error

DeleteUser removes an account whose removal orphans nothing: no owned repositories, no authored issues, MRs, comments, or reviews, and not the only admin of an org. Everything else (keys, emails, sessions, tokens, pins, memberships, activity) cascades. Blockers come back as an error naming what stands in the way, so the operator can transfer, delete, or disable instead.

func (*Store) DeleteWebSession

func (s *Store) DeleteWebSession(hash string) error

func (*Store) DepCheckFor added in v1.1.0

func (s *Store) DepCheckFor(repoID int64) (DepCheck, error)

func (*Store) DiffCommentAuthor added in v0.2.0

func (s *Store) DiffCommentAuthor(mrID, id int64) (int64, error)

DiffCommentAuthor returns the author id of one comment.

func (*Store) DisableDepCheck added in v1.1.0

func (s *Store) DisableDepCheck(repoID int64) error

DisableDepCheck stops checking and forgets what was reported, so re-enabling reports the current state afresh.

func (*Store) DiscardPendingComments added in v1.13.0

func (s *Store) DiscardPendingComments(mrID, authorID int64) (int64, error)

DiscardPendingComments deletes an author's unsubmitted comments. Only pending rows: a published comment is part of the conversation and is not something its author can quietly take back.

func (*Store) DueDeliveries

func (s *Store) DueDeliveries(limit int) ([]Delivery, error)

DueDeliveries returns pending deliveries whose time has come, with the event and hook context needed to send them.

func (*Store) DueDepChecks added in v1.1.0

func (s *Store) DueDepChecks(intervalSeconds int) ([]Repo, error)

DueDepChecks returns repos whose last check is older than intervalSeconds. Archived repos are skipped: nobody is going to act on the issue.

func (*Store) DueMail added in v0.2.0

func (s *Store) DueMail(limit int) ([]QueuedMail, error)

func (*Store) DueMirrors added in v0.2.0

func (s *Store) DueMirrors(intervalSeconds int) ([]Mirror, error)

DueMirrors returns mirrors needing a sync: anything dirty, plus pull mirrors whose last sync is older than intervalSeconds.

func (*Store) DueSchedules added in v0.3.0

func (s *Store) DueSchedules(nowISO string) ([]Schedule, error)

DueSchedules returns entries whose next_run is at or before now.

func (*Store) EmailInUse added in v0.2.0

func (s *Store) EmailInUse(address string) (bool, error)

EmailInUse reports whether an address is attached to any account.

func (*Store) EmailTokenBelongsToAnotherUser added in v1.0.1

func (s *Store) EmailTokenBelongsToAnotherUser(userID int64, tokenHash string) (bool, error)

EmailTokenBelongsToAnotherUser reports whether a live code exists but is owned by someone else. It answers only yes or no: naming the owner would turn a guessed code into an account oracle.

func (*Store) EnableDepCheck added in v1.1.0

func (s *Store) EnableDepCheck(repoID int64) error

func (*Store) EnqueueMail added in v0.2.0

func (s *Store) EnqueueMail(recipient, subject, body string) error

func (*Store) FinishBuild added in v0.3.0

func (s *Store) FinishBuild(id int64, status string) error

FinishBuild records the outcome of a running build.

func (*Store) GrantAccess

func (s *Store) GrantAccess(repoID, userID int64, role string) error

func (*Store) GrantTeamRepo added in v0.3.0

func (s *Store) GrantTeamRepo(teamID, repoID int64, role string) error

GrantTeamRepo attaches (or updates) a team's role on a repo.

func (*Store) ImportMarker added in v0.2.0

func (s *Store) ImportMarker(repoID int64, key string) (string, bool, error)

ImportMarker returns the stored value for an import progress key, and whether it exists. Markers make history imports resumable: items and comments already imported are skipped on re-run.

func (*Store) Inbox added in v1.11.0

func (s *Store) Inbox(userID int64, unreadOnly bool, limit int, afterID int64) ([]Notice, error)

Inbox returns a user's notices, newest first. unreadOnly drops what has been read; afterID pages backwards from a previous page's last row.

func (*Store) InstanceCounts added in v0.2.0

func (s *Store) InstanceCounts() (Counts, error)

func (*Store) IsPinned added in v0.2.0

func (s *Store) IsPinned(userID, repoID int64) bool

func (*Store) IssueByNumber

func (s *Store) IssueByNumber(repoID, number int64) (Issue, error)

func (*Store) IssueParticipants added in v0.2.0

func (s *Store) IssueParticipants(issueID int64) ([]int64, error)

IssueParticipants returns distinct user ids involved in an issue: the author and every commenter.

func (*Store) KeyEpoch

func (s *Store) KeyEpoch() (int64, error)

func (*Store) LFSSecret added in v0.4.0

func (s *Store) LFSSecret(gen func() string) (string, error)

LFSSecret returns the instance's LFS token-signing secret, minting and persisting one on first use. gen supplies the new value so this package stays free of crypto choices.

func (*Store) LabelColors added in v0.2.0

func (s *Store) LabelColors(repoID int64) (map[string]string, error)

LabelColors returns the repo's label colors keyed by label name. Labels with no stored color map to "".

func (*Store) LatestBuild added in v0.5.0

func (s *Store) LatestBuild(repoID int64, job string) (Build, error)

LatestBuild returns the newest build for a repo, optionally narrowed to one job. It is what a status badge reports.

func (*Store) ListAPITokens

func (s *Store) ListAPITokens(userID int64) ([]APIToken, error)

func (*Store) ListAccess

func (s *Store) ListAccess(repoID int64) ([]AccessEntry, error)

func (*Store) ListAllRepos added in v0.2.0

func (s *Store) ListAllRepos() ([]Repo, error)

ListAllRepos returns every repository, for host-local admin tooling.

func (*Store) ListBuildSecretNames added in v0.3.0

func (s *Store) ListBuildSecretNames(repoID int64) ([]string, error)

ListBuildSecretNames returns names only; values are for builds.

func (*Store) ListBuilds added in v0.3.0

func (s *Store) ListBuilds(repoID int64, limit int) ([]Build, error)

func (*Store) ListCommitStatuses added in v0.2.0

func (s *Store) ListCommitStatuses(repoID int64, sha string) ([]CommitStatus, error)

ListCommitStatuses returns the latest status per context for a commit.

func (*Store) ListDeliveries

func (s *Store) ListDeliveries(repoID int64, limit int) ([]DeliveryStatus, error)

func (*Store) ListDeployKeys added in v0.2.0

func (s *Store) ListDeployKeys(repoID int64) ([]SSHKey, error)

ListDeployKeys returns the deploy keys bound to a repository.

func (*Store) ListDiffComments added in v0.2.0

func (s *Store) ListDiffComments(mrID, viewer int64) ([]DiffComment, error)

ListDiffComments returns the diff comments on an MR that viewer may see: everything published, plus their own pending ones. viewer 0 is an anonymous reader, who sees only what is published.

func (*Store) ListEmails added in v1.0.0

func (s *Store) ListEmails(userID int64) ([]Email, error)

ListEmails returns every address on the account with its state.

func (*Store) ListIssueComments

func (s *Store) ListIssueComments(issueID int64) ([]IssueComment, error)

func (*Store) ListIssueLabels added in v0.2.0

func (s *Store) ListIssueLabels(repoID int64) (map[int64][]string, error)

ListIssueLabels returns the label names attached to each issue of a repo, keyed by issue id. Used by the web issue listing; ListIssues itself stays label-free for the CLI's lean list output.

func (*Store) ListIssues

func (s *Store) ListIssues(repoID int64, state string, limit int, before int64) ([]Issue, error)

func (*Store) ListLabels added in v1.8.0

func (s *Store) ListLabels(repoID int64) ([]Label, error)

ListLabels lists a repository's labels by name.

func (*Store) ListMRComments

func (s *Store) ListMRComments(mrID int64) ([]IssueComment, error)

func (*Store) ListMRReviews

func (s *Store) ListMRReviews(mrID int64) ([]MRReview, error)

func (*Store) ListMRs

func (s *Store) ListMRs(repoID int64, state string, limit int, before int64) ([]MR, error)

func (*Store) ListMilestones added in v0.2.0

func (s *Store) ListMilestones(repoID int64, state string) ([]Milestone, error)

func (*Store) ListMirrors added in v0.2.0

func (s *Store) ListMirrors(repoID int64) ([]Mirror, error)

func (*Store) ListOrgsForUser

func (s *Store) ListOrgsForUser(userID int64) ([]OrgMember, error)

ListOrgsForUser returns the orgs the user belongs to, with their role.

func (*Store) ListPGPKeys

func (s *Store) ListPGPKeys(userID int64) ([]PGPKey, error)

func (*Store) ListPageDomains added in v0.3.0

func (s *Store) ListPageDomains(repoID int64) ([]PageDomain, error)

func (*Store) ListPublicRepos

func (s *Store) ListPublicRepos() ([]Repo, error)

ListPublicRepos returns all public repositories, for the anonymous index.

func (*Store) ListReleases added in v0.2.0

func (s *Store) ListReleases(repoID int64) ([]Release, error)

ListReleases returns releases newest-first, assets included.

func (*Store) ListReposAdmin added in v1.4.0

func (s *Store) ListReposAdmin(owner, visibility string, limit int, after string) ([]AdminRepo, error)

ListReposAdmin lists repositories across every owner, by path. owner and visibility narrow the set when non-empty; after is the path keyset cursor; limit 0 means no cap.

func (*Store) ListReposForOwner

func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error)

ListReposForOwner returns every repo owned by one user or org; the caller filters by viewer visibility.

func (*Store) ListReposForUser

func (s *Store) ListReposForUser(userID int64, limit int, after string) ([]Repo, error)

ListReposForUser returns repos the user owns, reaches through an org (unless the org scopes members to 'none'), has an explicit grant on, or reaches through a team. limit 0 means everything; after (an owner/name path) starts the page strictly beyond it, matching the path-ascending order.

func (*Store) ListRunners added in v1.6.0

func (s *Store) ListRunners() ([]Runner, error)

ListRunners lists every account that has ever polled as a runner, most recently seen first.

func (*Store) ListSSHKeys

func (s *Store) ListSSHKeys(userID int64) ([]SSHKey, error)

func (*Store) ListTeams added in v0.3.0

func (s *Store) ListTeams(orgID int64) ([]Team, error)

func (*Store) ListTopics added in v0.2.0

func (s *Store) ListTopics(repoID int64) ([]string, error)

func (*Store) ListUsers added in v1.4.0

func (s *Store) ListUsers(state string, limit int, after string) ([]AdminUser, error)

ListUsers returns accounts by username. state narrows the set: "" for every account, active (neither pending nor disabled), pending, disabled, or admin. after is the keyset cursor: usernames strictly greater than it, "" from the start. limit 0 means no cap.

func (*Store) ListWebSessions added in v1.7.0

func (s *Store) ListWebSessions(userID int64) ([]WebSession, error)

ListWebSessions lists the user's unexpired browser sessions, newest first.

func (*Store) ListWebhooks

func (s *Store) ListWebhooks(repoID int64) ([]Webhook, error)

func (*Store) MRByNumber

func (s *Store) MRByNumber(repoID, number int64) (MR, error)

func (*Store) MRHeads added in v1.13.0

func (s *Store) MRHeads(mrID int64) ([]MRHead, error)

MRHeads returns a merge request's revisions, oldest first.

func (*Store) MRParticipants added in v0.2.0

func (s *Store) MRParticipants(mrID int64) ([]int64, error)

MRParticipants returns distinct user ids involved in an MR: author, commenters, reviewers.

func (*Store) MarkAttemptFailed

func (s *Store) MarkAttemptFailed(id int64, status int, errMsg string, nextAt *time.Time) error

MarkAttemptFailed records a failed attempt; nextAt nil dead-letters it.

func (*Store) MarkClosed added in v1.2.0

func (s *Store) MarkClosed(mrID, actorID int64, at string) error

MarkClosed is MarkMerged's counterpart for a merge request closed without merging.

func (*Store) MarkDelivered

func (s *Store) MarkDelivered(id int64, status int) error

func (*Store) MarkMailFailed added in v0.2.0

func (s *Store) MarkMailFailed(id int64, errMsg string, nextAt *time.Time) error

func (*Store) MarkMailSent added in v0.2.0

func (s *Store) MarkMailSent(id int64) error

func (*Store) MarkMerged

func (s *Store) MarkMerged(mrID int64, baseSHA string, actorID int64, at string) error

MarkMerged records the merge along with the target tip it landed on, so the MR's diff stays reconstructable after fast-forwards. actorID 0 and an empty at leave the merger unknown and stamp the current time, which is what an import that carries neither can say.

func (*Store) MarkMirrorsDirty added in v0.2.0

func (s *Store) MarkMirrorsDirty(repoID int64, direction string) error

MarkMirrorsDirty schedules a sync. An empty direction marks both.

func (*Store) MarkNoticesRead added in v1.11.0

func (s *Store) MarkNoticesRead(userID int64, ids []int64) (int64, error)

MarkNoticesRead marks the given ids read, or every unread notice when ids is empty. It returns how many rows changed. Ids belonging to another user match nothing, so one user cannot touch another's inbox.

func (*Store) MarkSourceGoneForRepo

func (s *Store) MarkSourceGoneForRepo(sourceRepoID int64) error

MarkSourceGoneForRepo flags every open MR sourced from the repo; called when a fork is deleted. Head refs in the target repos are retained.

func (*Store) MigrateCommitRefComments added in v0.3.0

func (s *Store) MigrateCommitRefComments() (int, error)

MigrateCommitRefComments converts legacy commit-reference comments into system messages with a linked sha, matching what new references produce. It is idempotent: only kind='comment' rows are considered, and converted rows become kind='system'. Returns the number converted.

func (*Store) MigrateTo

func (s *Store) MigrateTo(target int) error

MigrateTo migrates up or down to the given version. 0 empties the schema.

func (*Store) MigrateUp

func (s *Store) MigrateUp() error

MigrateUp applies all pending migrations.

func (*Store) MilestoneByTitle added in v0.2.0

func (s *Store) MilestoneByTitle(repoID int64, title string) (Milestone, error)

func (*Store) NotifyRecipients added in v1.11.0

func (s *Store) NotifyRecipients(repoID, actorID int64, targets []int64) ([]int64, error)

NotifyRecipients is who actually hears about something on a repository: the callers targets — owners, or a thread's participants — widened by the repository's watchers, minus the actor and minus anyone who muted it. Muting wins over every other reason to be told, including owning the repository or having written the thread.

func (*Store) OpenCounts added in v0.5.0

func (s *Store) OpenCounts(repoID int64) (issues, mrs int)

OpenCounts returns the repo's open issue and open merge request counts, for the repo tab badges.

func (*Store) OpenMRBySource added in v1.5.0

func (s *Store) OpenMRBySource(repoID int64, sourceRef string) (MR, bool, error)

OpenMRBySource finds the open merge request in repoID whose source is the repository's own branch sourceRef. ok is false when there is none.

func (*Store) OpenMRsBySource

func (s *Store) OpenMRsBySource(sourceRepoID int64, sourceRef string) ([]MR, error)

OpenMRsBySource returns open (and source_gone) MRs fed by the given source repo branch — the cross-repo hook effect consults this.

func (*Store) OpenMRsByTarget added in v1.5.0

func (s *Store) OpenMRsByTarget(repoID int64, targetRef string) ([]MR, error)

OpenMRsByTarget lists the open merge requests in repoID targeting targetRef, oldest first.

func (*Store) OrgActivityByDay added in v0.3.0

func (s *Store) OrgActivityByDay(orgID int64, sinceDay string) (map[string]int, error)

OrgActivityByDay aggregates activity across an org's repositories.

func (*Store) OrgByName

func (s *Store) OrgByName(name string) (Org, error)

func (*Store) OrgMembers

func (s *Store) OrgMembers(orgID int64) ([]OrgMember, error)

func (*Store) OrgRole

func (s *Store) OrgRole(orgID, userID int64) (string, error)

OrgRole returns the user's role in the org ("" for non-members).

func (*Store) OwnedRepoCount added in v1.4.0

func (s *Store) OwnedRepoCount(userID int64) (int64, error)

OwnedRepoCount counts repositories the user owns directly, not through an org.

func (*Store) OwnerExists added in v0.3.0

func (s *Store) OwnerExists(name string) bool

OwnerExists reports whether a user or org owns the name — the ACME host policy check for pages subdomains.

func (*Store) OwnerProfile

func (s *Store) OwnerProfile(kind string, id int64) (Profile, error)

OwnerProfile reads the profile for kind "user" or "org".

func (*Store) PageDomainClaim added in v0.3.0

func (s *Store) PageDomainClaim(domain string, repoID int64) (PageDomain, error)

PageDomainClaim returns a repo's claim on a domain, verified or pending.

func (*Store) PageDomainExpired added in v0.3.0

func (s *Store) PageDomainExpired(d PageDomain, ttlSeconds int) bool

PageDomainExpired reports whether a pending claim has outlived the TTL.

func (*Store) PageDomainRepo added in v0.3.0

func (s *Store) PageDomainRepo(domain string) (Repo, error)

PageDomainRepo resolves a request host to the repo serving it. Only verified claims serve.

func (*Store) PinRepo added in v0.2.0

func (s *Store) PinRepo(userID, repoID int64) error

func (*Store) PinnedRepos added in v0.2.0

func (s *Store) PinnedRepos(userID int64) ([]Repo, error)

PinnedRepos returns the user's pinned repositories in pin order. The caller applies visibility checks before rendering.

func (*Store) PrimaryVerifiedEmail

func (s *Store) PrimaryVerifiedEmail(userID int64) (string, error)

PrimaryVerifiedEmail returns the user's primary email if verified, else "".

func (*Store) PublishPendingComments added in v1.13.0

func (s *Store) PublishPendingComments(mrID, authorID int64) (int64, error)

PublishPendingComments makes an author's pending comments on an MR visible, and reports how many. This is what `mr review` does with the batch the reviewer composed.

func (*Store) PullMirrored added in v0.2.0

func (s *Store) PullMirrored(repoID int64) (bool, error)

PullMirrored reports whether the repo has a pull mirror, which makes it read-only locally: its refs belong to the upstream.

func (*Store) QueryIssues added in v1.8.0

func (s *Store) QueryIssues(repoID int64, f IssueFilter) ([]Issue, error)

QueryIssues lists a repository's issues, newest first, narrowed by f.

func (*Store) QueryMRs added in v1.8.0

func (s *Store) QueryMRs(repoID int64, f MRFilter) ([]MR, error)

QueryMRs lists a repository's merge requests, newest first, narrowed by f.

func (*Store) QueueStatus added in v1.4.0

func (s *Store) QueueStatus() (Queues, error)

QueueStatus reads every worker queue. Read-only; safe on a live daemon.

func (*Store) ReapPendingUsers added in v1.7.0

func (s *Store) ReapPendingUsers(maxAge time.Duration) ([]string, error)

ReapPendingUsers deletes self-registered accounts still unverified after maxAge. A pending account owns nothing (it cannot create a repository before verifying), so DeleteUser has nothing to refuse; an account that somehow anchors content is left alone and reported.

func (*Store) ReapStaleBuilds added in v1.0.1

func (s *Store) ReapStaleBuilds() ([]Build, error)

ReapStaleBuilds fails every build that has been running past the deadline and returns them, so the caller can resolve their commit statuses. A runner that dies between claiming a build and reporting it otherwise leaves the row claimed forever, and the commit pending forever with it.

func (*Store) RecentBuilds added in v1.0.1

func (s *Store) RecentBuilds(userID int64, limit int) ([]DashboardBuild, error)

RecentBuilds returns the newest builds on repositories the user can reach, most recent first.

func (*Store) RecentEvents added in v0.5.0

func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent, error)

RecentEvents returns activity on repositories the user can reach. Push events are excluded: they repeat what the commit lists already show. before (an event id) starts the page strictly below it, matching the id-descending order; 0 starts at the newest.

func (*Store) RecordCommitActivity added in v0.3.0

func (s *Store) RecordCommitActivity(repoID int64, sha string, userID int64, day string) bool

RecordCommitActivity is idempotent per (repo, sha); it reports whether this call recorded a new row.

func (*Store) RecordEvent

func (s *Store) RecordEvent(repoID, actorID int64, kind, dataJSON string) error

RecordEvent appends to the event log and enqueues a delivery for every active webhook on the repo whose event filter matches.

func (*Store) RedeemInvite added in v0.2.0

func (s *Store) RedeemInvite(codeHash, username, keyFP, keyAlgo string, keyBlob []byte) (string, error)

RedeemInvite performs the whole invite registration in one transaction: consume the code, create the user, attach the invite's email as verified, register the key. Any failure rolls everything back — the invite stays redeemable and no partial account exists.

func (*Store) Redeliver

func (s *Store) Redeliver(repoID, deliveryID int64) error

Redeliver resets a delivery for an immediate retry.

func (*Store) RegisterOpen added in v0.2.0

func (s *Store) RegisterOpen(username, email, keyFP, keyAlgo string, keyBlob []byte) (int64, error)

RegisterOpen performs open registration in one transaction: pending user, unverified email, key. Failure leaves nothing behind.

func (*Store) ReleaseByTag added in v0.2.0

func (s *Store) ReleaseByTag(repoID int64, tag string) (Release, error)

func (*Store) RemoveBuildSecret added in v0.3.0

func (s *Store) RemoveBuildSecret(repoID int64, name string) error

func (*Store) RemoveDeployKey added in v0.2.0

func (s *Store) RemoveDeployKey(repoID int64, fingerprint string) error

RemoveDeployKey removes a deploy key from a repository by fingerprint; any repo admin may remove it regardless of who added it.

func (*Store) RemoveMirror added in v0.2.0

func (s *Store) RemoveMirror(repoID, id int64) error

func (*Store) RemoveOrgMember

func (s *Store) RemoveOrgMember(orgID, userID int64) error

RemoveOrgMember drops a member, refusing to remove the last admin.

func (*Store) RemovePGPKey

func (s *Store) RemovePGPKey(userID int64, fingerprint string) error

func (*Store) RemovePageDomain added in v0.3.0

func (s *Store) RemovePageDomain(domain string, repoID int64) error

func (*Store) RemoveReleaseAsset added in v0.2.0

func (s *Store) RemoveReleaseAsset(releaseID int64, name string) error

func (*Store) RemoveSSHKey

func (s *Store) RemoveSSHKey(userID int64, fingerprint string) error

RemoveSSHKey removes a key owned by userID and bumps the key epoch.

func (*Store) RemoveSchedule added in v0.3.0

func (s *Store) RemoveSchedule(repoID int64, job string) error

func (*Store) RemoveTeamMember added in v0.3.0

func (s *Store) RemoveTeamMember(teamID, userID int64) error

func (*Store) RemoveTopic added in v0.2.0

func (s *Store) RemoveTopic(repoID int64, topic string) error

func (*Store) RemoveWebhook

func (s *Store) RemoveWebhook(repoID, hookID int64) error

func (*Store) RenameOrg

func (s *Store) RenameOrg(orgID int64, newName string) error

RenameOrg changes an org's name, holding the shared owner-namespace invariant. The caller moves the on-disk repos directory afterward.

func (*Store) ReplaceDepReports added in v1.1.0

func (s *Store) ReplaceDepReports(repoID int64, reports []DepReport) error

ReplaceDepReports swaps in the current outdated set wholesale: a dependency that was updated, removed, or renamed leaves no trace.

func (*Store) RepoByID

func (s *Store) RepoByID(id int64) (Repo, error)

func (*Store) RepoByPath

func (s *Store) RepoByPath(path string) (Repo, error)

RepoByPath resolves "owner/name"; the owner may be a user or an org.

func (*Store) RepoNotifyTargets added in v0.2.0

func (s *Store) RepoNotifyTargets(repo Repo) ([]int64, error)

RepoNotifyTargets returns who should hear about new activity on a repo: the owning user, or every admin of the owning org.

func (*Store) RepoWatchState added in v1.11.0

func (s *Store) RepoWatchState(repoID, userID int64) string

RepoWatchState returns "watching", "muted", or "" for the default.

func (*Store) ReportedDeps added in v1.1.0

func (s *Store) ReportedDeps(repoID int64) ([]DepReport, error)

func (*Store) RetargetKeepingReviews added in v1.5.0

func (s *Store) RetargetKeepingReviews(mrID int64, targetRef string) error

RetargetKeepingReviews moves a merge request onto a new target without staling its reviews: used when the branch it was stacked on has merged, so the diff against the new target is the diff the reviews were of.

func (*Store) ReviewQueue added in v0.5.0

func (s *Store) ReviewQueue(userID int64) ([]DashboardItem, error)

func (*Store) RevokeAPIToken

func (s *Store) RevokeAPIToken(userID int64, name string) error

func (*Store) RevokeAccess

func (s *Store) RevokeAccess(repoID, userID int64) error

func (*Store) RevokeAllWebSessions added in v1.7.0

func (s *Store) RevokeAllWebSessions(userID int64) (int64, error)

RevokeAllWebSessions ends every browser session the user has.

func (*Store) RevokeTeamRepo added in v0.3.0

func (s *Store) RevokeTeamRepo(teamID, repoID int64) error

func (*Store) RevokeWebSession added in v1.7.0

func (s *Store) RevokeWebSession(userID int64, id string) error

RevokeWebSession ends one of the user's sessions by its listed id.

func (*Store) RunnerDone added in v1.6.0

func (s *Store) RunnerDone(userID int64) error

RunnerDone records that the runner reported and holds nothing now.

func (*Store) SSHKeyByFingerprint

func (s *Store) SSHKeyByFingerprint(fingerprint string) (SSHKey, error)

func (*Store) SSHKeyByID

func (s *Store) SSHKeyByID(id int64) (SSHKey, error)

func (*Store) SearchIssues added in v1.11.0

func (s *Store) SearchIssues(userID int64, q string, limit int) ([]DashboardItem, error)

SearchIssues returns issues matching q in title or body, newest activity first.

func (*Store) SearchMRs added in v1.11.0

func (s *Store) SearchMRs(userID int64, q string, limit int) ([]DashboardItem, error)

SearchMRs is SearchIssues for merge requests.

func (*Store) SetBuildSecret added in v0.3.0

func (s *Store) SetBuildSecret(repoID int64, name, value string) error

SetBuildSecret stores or replaces one secret. The value never leaves the server except inside a claimed build's environment.

func (*Store) SetCommitStatus added in v0.2.0

func (s *Store) SetCommitStatus(repoID int64, sha, context, state, description, targetURL string, creatorID int64) error

SetCommitStatus upserts the latest state for one context on one commit. A zero creatorID records no creator (system actions like the scheduler).

func (*Store) SetDepCheckResult added in v1.1.0

func (s *Store) SetDepCheckResult(repoID int64, checkErr string) error

SetDepCheckResult stamps a sweep. An empty checkErr records success.

func (*Store) SetDepIssue added in v1.1.0

func (s *Store) SetDepIssue(repoID, number int64) error

func (*Store) SetForkOf

func (s *Store) SetForkOf(repoID, parentID int64) error

func (*Store) SetImportMarker added in v0.2.0

func (s *Store) SetImportMarker(repoID int64, key, value string) error

func (*Store) SetIssueAssignee

func (s *Store) SetIssueAssignee(issueID, userID int64, add bool) error

SetIssueAssignee adds or removes an assignee by user id.

func (*Store) SetIssueLabel

func (s *Store) SetIssueLabel(repoID, issueID int64, name string, add bool) error

SetIssueLabel attaches (add) or detaches a label, creating the repo label on first use.

func (*Store) SetIssueMilestone added in v0.2.0

func (s *Store) SetIssueMilestone(issueID, milestoneID int64) error

SetIssueMilestone attaches (or with milestoneID 0 clears) a milestone.

func (*Store) SetIssueState

func (s *Store) SetIssueState(issueID int64, state string) error

func (*Store) SetLabel added in v1.8.0

func (s *Store) SetLabel(repoID int64, name, color string) error

SetLabel creates the label or sets its colour.

func (*Store) SetMRDraft added in v1.13.0

func (s *Store) SetMRDraft(mrID int64, draft bool) error

SetMRDraft marks an open merge request as a draft, or takes the mark off. Merging is refused while it is set.

func (*Store) SetMRMilestone added in v0.2.0

func (s *Store) SetMRMilestone(mrID, milestoneID int64) error

func (*Store) SetMRState

func (s *Store) SetMRState(mrID int64, state string) error

SetMRState moves an MR between states that carry no resolution stamp. Returning to open (a source branch that came back) clears one.

func (*Store) SetMRTarget added in v1.0.1

func (s *Store) SetMRTarget(mrID int64, targetRef string) error

SetMRTarget retargets a merge request and marks every existing review stale, in one transaction. The base of the diff is derived from the target on every read, so nothing else has to move; an approval, though, was of the diff against the old branch.

func (*Store) SetMilestoneState added in v0.2.0

func (s *Store) SetMilestoneState(id int64, state string) error

func (*Store) SetMirrorResult added in v0.2.0

func (s *Store) SetMirrorResult(id int64, syncErr string) error

SetMirrorResult records a sync outcome and clears the dirty flag.

func (*Store) SetOrgMember

func (s *Store) SetOrgMember(orgID, userID int64, role string) error

SetOrgMember adds a member or updates their role. Demoting the last admin is refused: an org must always have one.

func (*Store) SetOrgMembersRole added in v0.3.0

func (s *Store) SetOrgMembersRole(orgID int64, role string) error

func (*Store) SetOwnerProfile

func (s *Store) SetOwnerProfile(kind string, id int64, p Profile) error

SetOwnerProfile updates the profile for kind "user" or "org".

func (*Store) SetRepoVisibility added in v0.5.0

func (s *Store) SetRepoVisibility(repoID int64, visibility string) error

SetRepoVisibility switches a repository between public and private.

func (*Store) SetRepoWatch added in v1.11.0

func (s *Store) SetRepoWatch(repoID, userID int64, state string) error

SetRepoWatch records an explicit watch or mute. Re-running it with the other state replaces the row.

func (*Store) SetScheduleNext added in v0.3.0

func (s *Store) SetScheduleNext(repoID int64, job, nextRun string) error

SetScheduleNext advances one entry's next firing time.

func (*Store) SetThreadResolved added in v0.2.0

func (s *Store) SetThreadResolved(mrID, rootID, byUser int64, resolved bool) error

SetThreadResolved resolves or unresolves a thread root.

func (*Store) SetUserAdmin added in v1.4.0

func (s *Store) SetUserAdmin(userID int64, admin bool) error

SetUserAdmin grants or removes instance admin. Removing it from the last admin is refused inside the same transaction that counts them.

func (*Store) SetUserDisabled added in v0.2.0

func (s *Store) SetUserDisabled(userID int64, disabled bool) error

SetUserDisabled suspends or restores an account. Disabling also drops the user's web sessions; their keys and tokens stay registered but are refused at every entry point until re-enabled.

func (*Store) SetUserLimits added in v1.7.0

func (s *Store) SetUserLimits(userID int64, l UserLimits) error

SetUserLimits writes the overrides; a nil field clears back to default.

func (*Store) StoreSignature

func (s *Store) StoreSignature(repoID int64, sha string, r sig.Result, epoch int64) error

func (*Store) SuccessBuildFor added in v1.6.0

func (s *Store) SuccessBuildFor(repoID int64, sha, job string) (Build, bool, error)

SuccessBuildFor finds a passed build of the commit for the job, on any ref: what a cancelled duplicate can point back at.

func (*Store) Sweep added in v1.12.0

func (s *Store) Sweep(r Retention, now time.Time) (Swept, error)

Sweep deletes expired sessions and tokens, then the rows older than each configured retention. Errors are returned with whatever was removed before them: a sweep that fails halfway has still done that much, and the next one picks up the rest.

func (*Store) SyncSchedules added in v0.3.0

func (s *Store) SyncSchedules(repoID int64, entries []Schedule) error

SyncSchedules replaces a repo's schedule set with the given entries, preserving next_run for entries whose cron is unchanged.

func (*Store) TeamByName added in v0.3.0

func (s *Store) TeamByName(orgID int64, name string) (Team, error)

func (*Store) TeamGrants added in v0.3.0

func (s *Store) TeamGrants(teamID int64) ([]TeamGrant, error)

func (*Store) TeamMembers added in v0.3.0

func (s *Store) TeamMembers(teamID int64) ([]string, error)

func (*Store) TouchRunner added in v1.6.0

func (s *Store) TouchRunner(userID int64, scope string, buildID int64) error

TouchRunner records a poll: the time, the scope the runner asked for, and the build it just claimed (0 for none).

func (*Store) TouchSSHKey

func (s *Store) TouchSSHKey(id int64) error

TouchSSHKey records key use; best-effort, callers ignore the error.

func (*Store) TransferRepo

func (s *Store) TransferRepo(repoID int64, newKind string, newOwnerID int64) error

TransferRepo moves a repository to a new owner. The unique index on (owner_kind, owner_id, name) refuses collisions in the target namespace.

func (*Store) TryRecordCommitRef added in v0.2.0

func (s *Store) TryRecordCommitRef(issueID int64, sha string) (bool, error)

TryRecordCommitRef marks a commit as having referenced an issue. It reports whether this pair was new — false means the reference was already processed and must not act again.

func (*Store) UnpinRepo added in v0.2.0

func (s *Store) UnpinRepo(userID, repoID int64) error

func (*Store) UnreadNotices added in v1.11.0

func (s *Store) UnreadNotices(userID int64) int

UnreadNotices counts what the badge shows.

func (*Store) UnresolvedThreadCount added in v0.2.0

func (s *Store) UnresolvedThreadCount(mrID int64) (int, error)

UnresolvedThreadCount counts unresolved thread roots on an MR.

Pending roots are excluded: an unsubmitted comment is one reviewer's note to themselves, and blocking a merge on it would let anyone stall a merge request with a thread nobody else can see or resolve.

func (*Store) UpdateDefaultBranch

func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error

func (*Store) UpdateIssueText added in v0.2.0

func (s *Store) UpdateIssueText(issueID int64, title, body, format *string) error

UpdateIssueText edits title, body, and/or markup format; nil leaves a field unchanged.

func (*Store) UpdateMRHead

func (s *Store) UpdateMRHead(mrID int64, headSHA, baseSHA string) error

UpdateMRHead records a new head and marks every review at another head stale, in one transaction. UpdateMRHead moves a merge request onto a new head, stales the reviews of the old one, and records the head in the history a range-diff reads. baseSHA is the merge base at this moment; "" when the caller could not work it out, which only costs the range-diff its precision.

func (*Store) UpdateMRText added in v0.2.0

func (s *Store) UpdateMRText(mrID int64, title, body, format *string) error

UpdateMRText edits title, body, and/or markup format; nil leaves a field unchanged.

func (*Store) UpdateRelease added in v0.4.0

func (s *Store) UpdateRelease(repoID int64, tag, title, notes, format string) error

UpdateRelease replaces a release's title, notes, and markup format.

func (*Store) UpdateRepoSettings added in v1.12.0

func (s *Store) UpdateRepoSettings(repoID int64, mutate func(*RepoSettings)) (RepoSettings, error)

UpdateRepoSettings applies mutate to the repository's settings and stores the result, returning what was stored.

settings_json is one blob, so changing one field means writing all of them. Callers used to read the struct off a Repo they had loaded earlier, change a field and write the whole blob back, which loses the other admin's change whenever two ran at once — last write wins over a value it never read. The read and the write happen here instead, inside one transaction, and BEGIN IMMEDIATE takes the write lock up front: a second updater waits at the start rather than discovering the conflict after it has already read a stale blob.

func (*Store) UserByID

func (s *Store) UserByID(id int64) (User, error)

func (*Store) UserByUsername

func (s *Store) UserByUsername(name string) (User, error)

func (*Store) UserEmailAddresses added in v0.2.0

func (s *Store) UserEmailAddresses(userID int64) ([]string, error)

UserEmailAddresses returns every address on the account, verified or not.

func (*Store) UserIDByVerifiedEmail added in v0.3.0

func (s *Store) UserIDByVerifiedEmail(address string) (int64, bool)

UserIDByVerifiedEmail resolves a commit author email to an account, only through addresses the account has verified — the same trust rule as signature attribution.

func (*Store) UserLimits added in v1.7.0

func (s *Store) UserLimits(userID int64) (UserLimits, error)

func (*Store) UsernameByVerifiedEmail added in v0.5.0

func (s *Store) UsernameByVerifiedEmail(address string) (string, bool)

UsernameByVerifiedEmail resolves a commit author address to the account that has proven it, so the forge can show its own name for a person rather than whatever git config happened to be set.

func (*Store) VerifyEmail

func (s *Store) VerifyEmail(userID int64, address, by string) error

VerifyEmail marks an address verified and bumps the key epoch (email verification is a trust input for signature states).

func (*Store) VerifyPageDomain added in v0.3.0

func (s *Store) VerifyPageDomain(domain string, repoID int64) error

VerifyPageDomain activates a pending claim.

func (*Store) Version

func (s *Store) Version() (int, error)

Version returns the current schema version (0 = empty database).

func (*Store) VisibleRepos added in v1.11.0

func (s *Store) VisibleRepos(userID int64) ([]Repo, error)

VisibleRepos returns every repository the user may read, public ones included, ordered by owner then name.

func (*Store) WebSessionCount added in v1.4.0

func (s *Store) WebSessionCount(userID int64) (int64, error)

WebSessionCount counts the user's unexpired browser sessions.

func (*Store) WebSessionUser

func (s *Store) WebSessionUser(hash string) (User, error)

WebSessionUser resolves a session cookie hash to its user.

type Swept added in v1.12.0

type Swept map[string]int64

Swept counts what one sweep removed, per table. Zero-valued entries are left in so a caller logging the result sees every table it asked about.

func (Swept) Total added in v1.12.0

func (s Swept) Total() int64

Total is how many rows the sweep removed altogether.

type Team added in v0.3.0

type Team struct {
	ID    int64
	OrgID int64
	Name  string
}

type TeamGrant added in v0.3.0

type TeamGrant struct {
	RepoPath string `json:"repo"`
	Role     string `json:"role"`
}

type User

type User struct {
	ID       int64
	Username string
	IsAdmin  bool
	Pending  bool // self-registered, email not yet verified
	Disabled bool // administratively suspended
}

type UserLimits added in v1.7.0

type UserLimits struct {
	Repos *int64
	Bytes *int64
}

UserLimits is an account's quota overrides; nil means the configured default applies.

type WebSession added in v1.7.0

type WebSession struct {
	ID        string `json:"id"`
	CreatedAt string `json:"created_at"`
	ExpiresAt string `json:"expires_at"`
}

WebSession is one browser session as its owner lists it. ID is the first twelve hex digits of the stored token hash: enough to name it, and a hash of the cookie rather than the cookie.

type Webhook

type Webhook struct {
	ID        int64
	URL       string
	Secret    string
	Events    string // "*" or comma-separated kinds
	Active    bool
	CreatedAt string
}

Source Files

  • activity.go
  • adminusers.go
  • audit.go
  • builds.go
  • cisecrets.go
  • commentmigrate.go
  • commitrefs.go
  • dashboard.go
  • deps.go
  • diffcomments.go
  • fts.go
  • importmarkers.go
  • inbox.go
  • issues.go
  • labels.go
  • lfs.go
  • milestones.go
  • mirrors.go
  • mrs.go
  • notify.go
  • orgs.go
  • pagedomains.go
  • queues.go
  • quotas.go
  • registration.go
  • releases.go
  • repos.go
  • retention.go
  • runners.go
  • search.go
  • sessions.go
  • signatures.go
  • stack.go
  • stats.go
  • statuses.go
  • store.go
  • teams.go
  • tokens.go
  • topics.go
  • users.go
  • webhooks.go

Jump to

Keyboard shortcuts

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