Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
20.5 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.31.1
// source: github_snapshot.sql

package db

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

const deleteGitHubPRCheckRuns = `-- name: DeleteGitHubPRCheckRuns :exec
DELETE FROM github_pull_request_check_run WHERE pr_id = $1
`

// First half of the atomic per-check replace. Runs inside the same transaction
// as UpdateGitHubPRSnapshot and the inserts below.
func (q *Queries) DeleteGitHubPRCheckRuns(ctx context.Context, prID pgtype.UUID) error {
	_, err := q.db.Exec(ctx, deleteGitHubPRCheckRuns, prID)
	return err
}

const getGitHubPRForRefresh = `-- name: GetGitHubPRForRefresh :one
SELECT installation_id, repo_owner, repo_name, pr_number, state, head_sha, snapshot_head_sha, snapshot_fetched_at
FROM github_pull_request
WHERE workspace_id = $1
  AND lower(repo_owner) = lower($3::text)
  AND lower(repo_name) = lower($4::text)
  AND pr_number = $2
ORDER BY updated_at DESC
LIMIT 1
`

type GetGitHubPRForRefreshParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	PrNumber    int32       `json:"pr_number"`
	RepoOwner   string      `json:"repo_owner"`
	RepoName    string      `json:"repo_name"`
}

type GetGitHubPRForRefreshRow struct {
	InstallationID    int64              `json:"installation_id"`
	RepoOwner         string             `json:"repo_owner"`
	RepoName          string             `json:"repo_name"`
	PrNumber          int32              `json:"pr_number"`
	State             string             `json:"state"`
	HeadSha           string             `json:"head_sha"`
	SnapshotHeadSha   string             `json:"snapshot_head_sha"`
	SnapshotFetchedAt pgtype.Timestamptz `json:"snapshot_fetched_at"`
}

// Looks up one mirrored PR by case-insensitive owner/repo and number so a
// chat wakeup targeting a PR can kick off an immediate snapshot refresh.
func (q *Queries) GetGitHubPRForRefresh(ctx context.Context, arg GetGitHubPRForRefreshParams) (GetGitHubPRForRefreshRow, error) {
	row := q.db.QueryRow(ctx, getGitHubPRForRefresh,
		arg.WorkspaceID,
		arg.PrNumber,
		arg.RepoOwner,
		arg.RepoName,
	)
	var i GetGitHubPRForRefreshRow
	err := row.Scan(
		&i.InstallationID,
		&i.RepoOwner,
		&i.RepoName,
		&i.PrNumber,
		&i.State,
		&i.HeadSha,
		&i.SnapshotHeadSha,
		&i.SnapshotFetchedAt,
	)
	return i, err
}

const getGitHubPullRequestByID = `-- name: GetGitHubPullRequestByID :one
SELECT id, workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, branch, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, created_at, updated_at, head_sha, mergeable_state, additions, deletions, changed_files, api_mergeable, api_merge_state_status, checks_rollup_state, snapshot_head_sha, snapshot_fetched_at FROM github_pull_request WHERE id = $1
`

func (q *Queries) GetGitHubPullRequestByID(ctx context.Context, id pgtype.UUID) (GithubPullRequest, error) {
	row := q.db.QueryRow(ctx, getGitHubPullRequestByID, id)
	var i GithubPullRequest
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.InstallationID,
		&i.RepoOwner,
		&i.RepoName,
		&i.PrNumber,
		&i.Title,
		&i.State,
		&i.HtmlUrl,
		&i.Branch,
		&i.AuthorLogin,
		&i.AuthorAvatarUrl,
		&i.MergedAt,
		&i.ClosedAt,
		&i.PrCreatedAt,
		&i.PrUpdatedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.HeadSha,
		&i.MergeableState,
		&i.Additions,
		&i.Deletions,
		&i.ChangedFiles,
		&i.ApiMergeable,
		&i.ApiMergeStateStatus,
		&i.ChecksRollupState,
		&i.SnapshotHeadSha,
		&i.SnapshotFetchedAt,
	)
	return i, err
}

const insertGitHubPRCheckRun = `-- name: InsertGitHubPRCheckRun :exec
INSERT INTO github_pull_request_check_run (
    pr_id, head_sha, ordinal, name, status, conclusion, details_url, is_status_context
) VALUES (
    $1, $2, $3, $4, $5, $7, $8, $6
)
`

type InsertGitHubPRCheckRunParams struct {
	PrID            pgtype.UUID `json:"pr_id"`
	HeadSha         string      `json:"head_sha"`
	Ordinal         int32       `json:"ordinal"`
	Name            string      `json:"name"`
	Status          string      `json:"status"`
	IsStatusContext bool        `json:"is_status_context"`
	Conclusion      pgtype.Text `json:"conclusion"`
	DetailsUrl      pgtype.Text `json:"details_url"`
}

func (q *Queries) InsertGitHubPRCheckRun(ctx context.Context, arg InsertGitHubPRCheckRunParams) error {
	_, err := q.db.Exec(ctx, insertGitHubPRCheckRun,
		arg.PrID,
		arg.HeadSha,
		arg.Ordinal,
		arg.Name,
		arg.Status,
		arg.IsStatusContext,
		arg.Conclusion,
		arg.DetailsUrl,
	)
	return err
}

const listConflictWatchedGitHubPRNumbersInRepo = `-- name: ListConflictWatchedGitHubPRNumbersInRepo :many
SELECT DISTINCT pr.pr_number
FROM issue_wakeup AS w
JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
JOIN github_pull_request AS pr ON pr.id = ipr.pull_request_id
WHERE w.enabled
  AND w.condition->>'type' = 'pull_request'
  AND w.condition->>'event' = 'conflicts'
  AND pr.installation_id = $1 AND pr.repo_owner = $2 AND pr.repo_name = $3
  AND pr.state IN ('open', 'draft')
  AND pr.pr_number <> $4
ORDER BY pr.pr_number
LIMIT 200
`

type ListConflictWatchedGitHubPRNumbersInRepoParams struct {
	InstallationID int64  `json:"installation_id"`
	RepoOwner      string `json:"repo_owner"`
	RepoName       string `json:"repo_name"`
	PrNumber       int32  `json:"pr_number"`
}

// Open/draft PRs in one repository that an enabled "wake on merge conflict"
// rule watches. A merge into the repository can make them conflicting without
// an event of their own, so the merge webhook re-fetches them.
func (q *Queries) ListConflictWatchedGitHubPRNumbersInRepo(ctx context.Context, arg ListConflictWatchedGitHubPRNumbersInRepoParams) ([]int32, error) {
	rows, err := q.db.Query(ctx, listConflictWatchedGitHubPRNumbersInRepo,
		arg.InstallationID,
		arg.RepoOwner,
		arg.RepoName,
		arg.PrNumber,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []int32{}
	for rows.Next() {
		var pr_number int32
		if err := rows.Scan(&pr_number); err != nil {
			return nil, err
		}
		items = append(items, pr_number)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listGitHubPRNumbersByHeadSHA = `-- name: ListGitHubPRNumbersByHeadSHA :many
SELECT DISTINCT pr_number
FROM github_pull_request
WHERE installation_id = $1 AND repo_owner = $2 AND repo_name = $3 AND head_sha = $4
`

type ListGitHubPRNumbersByHeadSHAParams struct {
	InstallationID int64  `json:"installation_id"`
	RepoOwner      string `json:"repo_owner"`
	RepoName       string `json:"repo_name"`
	HeadSha        string `json:"head_sha"`
}

// Resolves a commit SHA to the PR numbers whose head it is. `status` webhook
// events (legacy commit statuses) carry a SHA + repo but no PR number, so we
// map back through the mirrored head_sha to find which PR(s) to refresh.
func (q *Queries) ListGitHubPRNumbersByHeadSHA(ctx context.Context, arg ListGitHubPRNumbersByHeadSHAParams) ([]int32, error) {
	rows, err := q.db.Query(ctx, listGitHubPRNumbersByHeadSHA,
		arg.InstallationID,
		arg.RepoOwner,
		arg.RepoName,
		arg.HeadSha,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []int32{}
	for rows.Next() {
		var pr_number int32
		if err := rows.Scan(&pr_number); err != nil {
			return nil, err
		}
		items = append(items, pr_number)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listGitHubPRRowsByAddress = `-- name: ListGitHubPRRowsByAddress :many

SELECT id, workspace_id, head_sha, state
FROM github_pull_request
WHERE installation_id = $1 AND repo_owner = $2 AND repo_name = $3 AND pr_number = $4
`

type ListGitHubPRRowsByAddressParams struct {
	InstallationID int64  `json:"installation_id"`
	RepoOwner      string `json:"repo_owner"`
	RepoName       string `json:"repo_name"`
	PrNumber       int32  `json:"pr_number"`
}

type ListGitHubPRRowsByAddressRow struct {
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	HeadSha     string      `json:"head_sha"`
	State       string      `json:"state"`
}

// =====================
// GitHub API snapshot (MUL-5265, Plan C)
//
// These queries back the API-snapshot refresh pipeline. The GitHub GraphQL
// response is the single source of truth; each successful fetch is written as
// one atomic batch replace (guarded update of the PR row + full replace of the
// per-check rows) inside a single transaction.
// =====================
// One (installation, owner, repo, number) address can map to several
// github_pull_request rows — the same installation can be bound to multiple
// workspaces (#4823/#4855), each mirroring its own row. A single API fetch is
// applied to every matching row (each guarded by its own head_sha).
func (q *Queries) ListGitHubPRRowsByAddress(ctx context.Context, arg ListGitHubPRRowsByAddressParams) ([]ListGitHubPRRowsByAddressRow, error) {
	rows, err := q.db.Query(ctx, listGitHubPRRowsByAddress,
		arg.InstallationID,
		arg.RepoOwner,
		arg.RepoName,
		arg.PrNumber,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListGitHubPRRowsByAddressRow{}
	for rows.Next() {
		var i ListGitHubPRRowsByAddressRow
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.HeadSha,
			&i.State,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listStaleChecksWatchedGitHubPRs = `-- name: ListStaleChecksWatchedGitHubPRs :many
WITH watched_issue_prs AS (
    SELECT ipr.pull_request_id AS pr_id
    FROM issue_wakeup AS w
    JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
    WHERE w.enabled
      AND w.condition->>'type' = 'pull_request'
      AND w.condition->>'event' = 'checks_finished'
),
watched_chat_prs AS (
    SELECT pr.id AS pr_id
    FROM chat_wakeup AS cw
    JOIN github_pull_request AS pr
      ON pr.workspace_id = cw.workspace_id
     AND lower(pr.repo_owner) = lower(split_part(cw.condition->>'repo', '/', 1))
     AND lower(pr.repo_name) = lower(split_part(cw.condition->>'repo', '/', 2))
     AND pr.pr_number = CASE
         WHEN COALESCE(cw.condition->>'number', '') ~ '^[0-9]{1,9}$' THEN (cw.condition->>'number')::INTEGER
     END
    WHERE cw.status = 'active'
      AND cw.kind = 'condition'
      AND cw.condition->>'type' = 'pull_request'
      AND cw.condition->>'event' = 'checks_finished'
),
candidates AS (
    SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
    FROM github_pull_request AS pr
    WHERE pr.state IN ('open', 'draft')
      AND (
          pr.snapshot_fetched_at IS NULL
          OR (pr.head_sha <> '' AND pr.snapshot_head_sha <> pr.head_sha)
          OR pr.snapshot_fetched_at < $6
      )
      AND (
          pr.id IN (SELECT pr_id FROM watched_issue_prs)
          OR pr.id IN (SELECT pr_id FROM watched_chat_prs)
      )
    GROUP BY pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
)
SELECT installation_id, repo_owner, repo_name, pr_number
FROM candidates
ORDER BY (
    ROW(installation_id, repo_owner, repo_name, pr_number) >
    ROW(
        $1::BIGINT,
        $2::TEXT,
        $3::TEXT,
        $4::INTEGER
    )
) DESC,
installation_id, repo_owner, repo_name, pr_number
LIMIT $5
`

type ListStaleChecksWatchedGitHubPRsParams struct {
	AfterInstallationID int64              `json:"after_installation_id"`
	AfterRepoOwner      string             `json:"after_repo_owner"`
	AfterRepoName       string             `json:"after_repo_name"`
	AfterPrNumber       int32              `json:"after_pr_number"`
	MaxRows             int32              `json:"max_rows"`
	OlderThan           pgtype.Timestamptz `json:"older_than"`
}

type ListStaleChecksWatchedGitHubPRsRow struct {
	InstallationID int64  `json:"installation_id"`
	RepoOwner      string `json:"repo_owner"`
	RepoName       string `json:"repo_name"`
	PrNumber       int32  `json:"pr_number"`
}

// Third sweep source: open/draft PRs watched by an enabled "checks finished"
// wakeup (issue or chat). A PR can leave the undecided sweep while a checks
// wakeup is still waiting (for example, an initial fetch right after
// synchronize saw no checks yet, or jobs were re-run on the same head), or
// webhook/chase refreshes may have been dropped during a rate limit or deploy.
// Sweeping watched PRs on a shorter TTL keeps --until-pr checks responsive
// without relying on a manual page visit. Rotates an address cursor like the
// other sweeps.
func (q *Queries) ListStaleChecksWatchedGitHubPRs(ctx context.Context, arg ListStaleChecksWatchedGitHubPRsParams) ([]ListStaleChecksWatchedGitHubPRsRow, error) {
	rows, err := q.db.Query(ctx, listStaleChecksWatchedGitHubPRs,
		arg.AfterInstallationID,
		arg.AfterRepoOwner,
		arg.AfterRepoName,
		arg.AfterPrNumber,
		arg.MaxRows,
		arg.OlderThan,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListStaleChecksWatchedGitHubPRsRow{}
	for rows.Next() {
		var i ListStaleChecksWatchedGitHubPRsRow
		if err := rows.Scan(
			&i.InstallationID,
			&i.RepoOwner,
			&i.RepoName,
			&i.PrNumber,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listStaleConflictWatchedGitHubPRs = `-- name: ListStaleConflictWatchedGitHubPRs :many
WITH candidates AS (
    SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
    FROM github_pull_request AS pr
    WHERE pr.state IN ('open', 'draft')
      AND (
          pr.snapshot_fetched_at IS NULL
          OR (pr.head_sha <> '' AND pr.snapshot_head_sha <> pr.head_sha)
          OR pr.snapshot_fetched_at < $6
      )
      AND pr.id IN (
          SELECT ipr.pull_request_id
          FROM issue_wakeup AS w
          JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
          WHERE w.enabled
            AND w.condition->>'type' = 'pull_request'
            AND w.condition->>'event' = 'conflicts'
      )
    GROUP BY pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
)
SELECT installation_id, repo_owner, repo_name, pr_number
FROM candidates
ORDER BY (
    ROW(installation_id, repo_owner, repo_name, pr_number) >
    ROW(
        $1::BIGINT,
        $2::TEXT,
        $3::TEXT,
        $4::INTEGER
    )
) DESC,
installation_id, repo_owner, repo_name, pr_number
LIMIT $5
`

type ListStaleConflictWatchedGitHubPRsParams struct {
	AfterInstallationID int64              `json:"after_installation_id"`
	AfterRepoOwner      string             `json:"after_repo_owner"`
	AfterRepoName       string             `json:"after_repo_name"`
	AfterPrNumber       int32              `json:"after_pr_number"`
	MaxRows             int32              `json:"max_rows"`
	OlderThan           pgtype.Timestamptz `json:"older_than"`
}

type ListStaleConflictWatchedGitHubPRsRow struct {
	InstallationID int64  `json:"installation_id"`
	RepoOwner      string `json:"repo_owner"`
	RepoName       string `json:"repo_name"`
	PrNumber       int32  `json:"pr_number"`
}

// Second sweep source: open/draft PRs linked to an issue with an enabled
// "wake on merge conflict" rule. A decided snapshot leaves the undecided sweep,
// but a base-branch move can turn it conflicting without any event for this
// PR, so watched PRs are re-fetched on the TTL regardless. The candidate set
// comes from the enabled rules, whose count is capped. Like the undecided
// sweep, an address cursor rotates the bounded batch, so addresses whose
// fetches keep failing (their snapshot never gets newer) cannot pin it.
func (q *Queries) ListStaleConflictWatchedGitHubPRs(ctx context.Context, arg ListStaleConflictWatchedGitHubPRsParams) ([]ListStaleConflictWatchedGitHubPRsRow, error) {
	rows, err := q.db.Query(ctx, listStaleConflictWatchedGitHubPRs,
		arg.AfterInstallationID,
		arg.AfterRepoOwner,
		arg.AfterRepoName,
		arg.AfterPrNumber,
		arg.MaxRows,
		arg.OlderThan,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListStaleConflictWatchedGitHubPRsRow{}
	for rows.Next() {
		var i ListStaleConflictWatchedGitHubPRsRow
		if err := rows.Scan(
			&i.InstallationID,
			&i.RepoOwner,
			&i.RepoName,
			&i.PrNumber,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listStaleUndecidedGitHubPRs = `-- name: ListStaleUndecidedGitHubPRs :many
WITH candidates AS (
    SELECT installation_id, repo_owner, repo_name, pr_number
    FROM github_pull_request AS pr
    WHERE state IN ('open', 'draft')
      AND (
          snapshot_fetched_at IS NULL
          OR (head_sha <> '' AND snapshot_head_sha <> head_sha)
          OR snapshot_fetched_at < $6
      )
      AND (
          snapshot_fetched_at IS NULL
          OR (head_sha <> '' AND snapshot_head_sha <> head_sha)
          OR api_mergeable IS NULL
          OR api_mergeable = 'UNKNOWN'
          OR checks_rollup_state IN ('PENDING', 'EXPECTED')
          OR EXISTS (
              SELECT 1
              FROM github_pull_request_check_run AS cr
              WHERE cr.pr_id = pr.id AND cr.status <> 'completed'
          )
      )
    GROUP BY installation_id, repo_owner, repo_name, pr_number
)
SELECT installation_id, repo_owner, repo_name, pr_number
FROM candidates
ORDER BY (
    ROW(installation_id, repo_owner, repo_name, pr_number) >
    ROW(
        $1::BIGINT,
        $2::TEXT,
        $3::TEXT,
        $4::INTEGER
    )
) DESC,
installation_id, repo_owner, repo_name, pr_number
LIMIT $5
`

type ListStaleUndecidedGitHubPRsParams struct {
	AfterInstallationID int64              `json:"after_installation_id"`
	AfterRepoOwner      string             `json:"after_repo_owner"`
	AfterRepoName       string             `json:"after_repo_name"`
	AfterPrNumber       int32              `json:"after_pr_number"`
	MaxRows             int32              `json:"max_rows"`
	OlderThan           pgtype.Timestamptz `json:"older_than"`
}

type ListStaleUndecidedGitHubPRsRow struct {
	InstallationID int64  `json:"installation_id"`
	RepoOwner      string `json:"repo_owner"`
	RepoName       string `json:"repo_name"`
	PrNumber       int32  `json:"pr_number"`
}

// TTL / safety-net sweep source. Returns distinct addresses of open/draft PRs
// whose snapshot is missing for the current head (never fetched or head_sha
// advanced past snapshot_head_sha) or both stale and undecided. A decided
// snapshot for the current head leaves the periodic refresh set; later webhook,
// watched-wakeup, or view activity can still refresh it.
// The caller advances an address cursor after each bounded batch. Rows after
// the cursor sort first, followed by a wrap to the start, so even perpetually
// failing addresses cannot pin the same first LIMIT rows forever.
func (q *Queries) ListStaleUndecidedGitHubPRs(ctx context.Context, arg ListStaleUndecidedGitHubPRsParams) ([]ListStaleUndecidedGitHubPRsRow, error) {
	rows, err := q.db.Query(ctx, listStaleUndecidedGitHubPRs,
		arg.AfterInstallationID,
		arg.AfterRepoOwner,
		arg.AfterRepoName,
		arg.AfterPrNumber,
		arg.MaxRows,
		arg.OlderThan,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListStaleUndecidedGitHubPRsRow{}
	for rows.Next() {
		var i ListStaleUndecidedGitHubPRsRow
		if err := rows.Scan(
			&i.InstallationID,
			&i.RepoOwner,
			&i.RepoName,
			&i.PrNumber,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const updateGitHubPRSnapshot = `-- name: UpdateGitHubPRSnapshot :execrows
UPDATE github_pull_request
SET api_mergeable          = $1,
    api_merge_state_status = $2,
    checks_rollup_state    = $3,
    snapshot_head_sha      = $4,
    snapshot_fetched_at    = $5,
    updated_at             = now()
WHERE id = $6 AND head_sha = $4
`

type UpdateGitHubPRSnapshotParams struct {
	ApiMergeable        pgtype.Text        `json:"api_mergeable"`
	ApiMergeStateStatus pgtype.Text        `json:"api_merge_state_status"`
	ChecksRollupState   pgtype.Text        `json:"checks_rollup_state"`
	HeadSha             string             `json:"head_sha"`
	FetchedAt           pgtype.Timestamptz `json:"fetched_at"`
	PrID                pgtype.UUID        `json:"pr_id"`
}

// Head-SHA anti-stale write (acceptance criterion 1): the snapshot is written
// only when the row's current head_sha still equals the head the snapshot was
// fetched for. If the head advanced (a newer push landed while this request was
// in flight, mirrored by the pull_request webhook), 0 rows are updated and the
// caller discards the whole response — the per-check replace is skipped too.
func (q *Queries) UpdateGitHubPRSnapshot(ctx context.Context, arg UpdateGitHubPRSnapshotParams) (int64, error) {
	result, err := q.db.Exec(ctx, updateGitHubPRSnapshot,
		arg.ApiMergeable,
		arg.ApiMergeStateStatus,
		arg.ChecksRollupState,
		arg.HeadSha,
		arg.FetchedAt,
		arg.PrID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}