Skip to content

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

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

package db

import (
	"context"

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

const deleteWorkspaceMemberSearchAccess = `-- name: DeleteWorkspaceMemberSearchAccess :exec
DELETE FROM member_search_access WHERE workspace_id = $1
`

func (q *Queries) DeleteWorkspaceMemberSearchAccess(ctx context.Context, workspaceID pgtype.UUID) error {
	_, err := q.db.Exec(ctx, deleteWorkspaceMemberSearchAccess, workspaceID)
	return err
}

const deleteWorkspaceSearchIndexChanges = `-- name: DeleteWorkspaceSearchIndexChanges :exec
DELETE FROM search_index_change WHERE workspace_id = $1
`

func (q *Queries) DeleteWorkspaceSearchIndexChanges(ctx context.Context, workspaceID pgtype.UUID) error {
	_, err := q.db.Exec(ctx, deleteWorkspaceSearchIndexChanges, workspaceID)
	return err
}

const getSearchIndexCurrentSnapshot = `-- name: GetSearchIndexCurrentSnapshot :one
SELECT pg_current_snapshot()::text AS snapshot
`

func (q *Queries) GetSearchIndexCurrentSnapshot(ctx context.Context) (string, error) {
	row := q.db.QueryRow(ctx, getSearchIndexCurrentSnapshot)
	var snapshot string
	err := row.Scan(&snapshot)
	return snapshot, err
}

const getSearchIndexManifest = `-- name: GetSearchIndexManifest :one

WITH ws AS (SELECT $1::uuid AS id, $2::uuid[] AS hidden),
visible_issue AS (
    SELECT i.id, i.title, i.description FROM issue i, ws
    WHERE i.workspace_id = ws.id
      AND (ws.hidden IS NULL OR NOT (COALESCE(i.project_id, '00000000-0000-0000-0000-000000000000'::uuid) = ANY(ws.hidden)))
),
visible_comment AS (
    SELECT c.content FROM comment c
    JOIN visible_issue vi ON vi.id = c.issue_id, ws
    WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL
),
visible_project AS (
    SELECT p.title, p.description FROM project p, ws
    WHERE p.workspace_id = ws.id AND (ws.hidden IS NULL OR NOT (p.id = ANY(ws.hidden)))
)
SELECT
    pg_current_snapshot()::text AS snapshot,
    (SELECT count(*) FROM visible_issue)::bigint AS issue_count,
    (SELECT COALESCE(sum(octet_length(title) + COALESCE(octet_length(description), 0)), 0)
        FROM visible_issue)::bigint AS issue_bytes,
    (SELECT count(*) FROM visible_comment)::bigint AS comment_count,
    (SELECT COALESCE(sum(octet_length(content)), 0) FROM visible_comment)::bigint AS comment_bytes,
    (SELECT count(*) FROM visible_project)::bigint AS project_count,
    (SELECT COALESCE(sum(octet_length(title) + COALESCE(octet_length(description), 0)), 0)
        FROM visible_project)::bigint AS project_bytes
`

type GetSearchIndexManifestParams struct {
	WorkspaceID      pgtype.UUID   `json:"workspace_id"`
	HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
}

type GetSearchIndexManifestRow struct {
	Snapshot     string `json:"snapshot"`
	IssueCount   int64  `json:"issue_count"`
	IssueBytes   int64  `json:"issue_bytes"`
	CommentCount int64  `json:"comment_count"`
	CommentBytes int64  `json:"comment_bytes"`
	ProjectCount int64  `json:"project_count"`
	ProjectBytes int64  `json:"project_bytes"`
}

// Local search index sync (MUL-7754). Web and Desktop copy the issue, comment,
// and project text of a workspace, then catch up through search_index_change.
// Snapshots are exchanged as pg_snapshot text; see migration 561.
// Taken before any snapshot page, so every write the pages might miss is newer
// than this snapshot and reaches the client through the change log. The byte
// totals let the client reject a workspace too large for its memory budget
// before downloading it; octet_length reads the stored length, so TOASTed
// bodies are not decompressed. Rows in hidden_project_ids are left out, as
// the snapshot leaves them out.
func (q *Queries) GetSearchIndexManifest(ctx context.Context, arg GetSearchIndexManifestParams) (GetSearchIndexManifestRow, error) {
	row := q.db.QueryRow(ctx, getSearchIndexManifest, arg.WorkspaceID, arg.HiddenProjectIds)
	var i GetSearchIndexManifestRow
	err := row.Scan(
		&i.Snapshot,
		&i.IssueCount,
		&i.IssueBytes,
		&i.CommentCount,
		&i.CommentBytes,
		&i.ProjectCount,
		&i.ProjectBytes,
	)
	return i, err
}

const listSearchIndexChanges = `-- name: ListSearchIndexChanges :many
SELECT entity_type, entity_id, change_xid::text AS change_xid
FROM search_index_change
WHERE workspace_id = $1
  AND change_xid >= pg_snapshot_xmin(($2::text)::pg_snapshot)
  AND change_xid < pg_snapshot_xmax(($3::text)::pg_snapshot)
  AND NOT pg_visible_in_snapshot(change_xid, ($2::text)::pg_snapshot)
  AND pg_visible_in_snapshot(change_xid, ($3::text)::pg_snapshot)
  AND (change_xid, entity_type, entity_id)
      > (($4::text)::xid8, $5::text, $6::uuid)
ORDER BY change_xid, entity_type, entity_id
LIMIT $7
`

type ListSearchIndexChangesParams struct {
	WorkspaceID    pgtype.UUID `json:"workspace_id"`
	SinceSnapshot  string      `json:"since_snapshot"`
	TargetSnapshot string      `json:"target_snapshot"`
	AfterXid       string      `json:"after_xid"`
	AfterType      string      `json:"after_type"`
	AfterID        pgtype.UUID `json:"after_id"`
	PageLimit      int32       `json:"page_limit"`
}

type ListSearchIndexChangesRow struct {
	EntityType string      `json:"entity_type"`
	EntityID   pgtype.UUID `json:"entity_id"`
	ChangeXid  string      `json:"change_xid"`
}

// Changes committed in the target snapshot but not in the since snapshot, in
// keyset order. An entity rewritten after the target snapshot carries a newer
// xid, drops out of this range, and is returned by the next catch-up instead.
func (q *Queries) ListSearchIndexChanges(ctx context.Context, arg ListSearchIndexChangesParams) ([]ListSearchIndexChangesRow, error) {
	rows, err := q.db.Query(ctx, listSearchIndexChanges,
		arg.WorkspaceID,
		arg.SinceSnapshot,
		arg.TargetSnapshot,
		arg.AfterXid,
		arg.AfterType,
		arg.AfterID,
		arg.PageLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListSearchIndexChangesRow{}
	for rows.Next() {
		var i ListSearchIndexChangesRow
		if err := rows.Scan(&i.EntityType, &i.EntityID, &i.ChangeXid); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSearchIndexCommentsByIDs = `-- name: ListSearchIndexCommentsByIDs :many
SELECT id, issue_id, content, created_at, deleted_at
FROM comment
WHERE workspace_id = $1 AND id = ANY($2::uuid[])
`

type ListSearchIndexCommentsByIDsParams struct {
	WorkspaceID pgtype.UUID   `json:"workspace_id"`
	Ids         []pgtype.UUID `json:"ids"`
}

type ListSearchIndexCommentsByIDsRow struct {
	ID        pgtype.UUID        `json:"id"`
	IssueID   pgtype.UUID        `json:"issue_id"`
	Content   string             `json:"content"`
	CreatedAt pgtype.Timestamptz `json:"created_at"`
	DeletedAt pgtype.Timestamptz `json:"deleted_at"`
}

// Tombstoned comments are returned so the caller can report them as deleted.
func (q *Queries) ListSearchIndexCommentsByIDs(ctx context.Context, arg ListSearchIndexCommentsByIDsParams) ([]ListSearchIndexCommentsByIDsRow, error) {
	rows, err := q.db.Query(ctx, listSearchIndexCommentsByIDs, arg.WorkspaceID, arg.Ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListSearchIndexCommentsByIDsRow{}
	for rows.Next() {
		var i ListSearchIndexCommentsByIDsRow
		if err := rows.Scan(
			&i.ID,
			&i.IssueID,
			&i.Content,
			&i.CreatedAt,
			&i.DeletedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSearchIndexCommentsByIssues = `-- name: ListSearchIndexCommentsByIssues :many
SELECT id, issue_id, content, created_at
FROM comment
WHERE workspace_id = $1
  AND issue_id = ANY($2::uuid[])
  AND deleted_at IS NULL
`

type ListSearchIndexCommentsByIssuesParams struct {
	WorkspaceID pgtype.UUID   `json:"workspace_id"`
	IssueIds    []pgtype.UUID `json:"issue_ids"`
}

type ListSearchIndexCommentsByIssuesRow struct {
	ID        pgtype.UUID        `json:"id"`
	IssueID   pgtype.UUID        `json:"issue_id"`
	Content   string             `json:"content"`
	CreatedAt pgtype.Timestamptz `json:"created_at"`
}

func (q *Queries) ListSearchIndexCommentsByIssues(ctx context.Context, arg ListSearchIndexCommentsByIssuesParams) ([]ListSearchIndexCommentsByIssuesRow, error) {
	rows, err := q.db.Query(ctx, listSearchIndexCommentsByIssues, arg.WorkspaceID, arg.IssueIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListSearchIndexCommentsByIssuesRow{}
	for rows.Next() {
		var i ListSearchIndexCommentsByIssuesRow
		if err := rows.Scan(
			&i.ID,
			&i.IssueID,
			&i.Content,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSearchIndexIssuesByIDs = `-- name: ListSearchIndexIssuesByIDs :many
SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1 AND id = ANY($2::uuid[])
`

type ListSearchIndexIssuesByIDsParams struct {
	WorkspaceID pgtype.UUID   `json:"workspace_id"`
	Ids         []pgtype.UUID `json:"ids"`
}

func (q *Queries) ListSearchIndexIssuesByIDs(ctx context.Context, arg ListSearchIndexIssuesByIDsParams) ([]Issue, error) {
	rows, err := q.db.Query(ctx, listSearchIndexIssuesByIDs, arg.WorkspaceID, arg.Ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []Issue{}
	for rows.Next() {
		var i Issue
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.Title,
			&i.Description,
			&i.Status,
			&i.Priority,
			&i.AssigneeType,
			&i.AssigneeID,
			&i.CreatorType,
			&i.CreatorID,
			&i.ParentIssueID,
			&i.AcceptanceCriteria,
			&i.ContextRefs,
			&i.Position,
			&i.DueDate,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Number,
			&i.ProjectID,
			&i.OriginType,
			&i.OriginID,
			&i.FirstExecutedAt,
			&i.StartDate,
			&i.Metadata,
			&i.Stage,
			&i.Properties,
			&i.Revision,
			&i.LastActivityAt,
			&i.TriageState,
			&i.DuplicateOfIssueID,
			&i.RequesterUserID,
			&i.DescriptionRevision,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSearchIndexIssuesPage = `-- name: ListSearchIndexIssuesPage :many
SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1 AND number > $2
ORDER BY number
LIMIT $3
`

type ListSearchIndexIssuesPageParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	AfterNumber int32       `json:"after_number"`
	PageLimit   int32       `json:"page_limit"`
}

// Pages by the unique (workspace_id, number) index.
func (q *Queries) ListSearchIndexIssuesPage(ctx context.Context, arg ListSearchIndexIssuesPageParams) ([]Issue, error) {
	rows, err := q.db.Query(ctx, listSearchIndexIssuesPage, arg.WorkspaceID, arg.AfterNumber, arg.PageLimit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []Issue{}
	for rows.Next() {
		var i Issue
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.Title,
			&i.Description,
			&i.Status,
			&i.Priority,
			&i.AssigneeType,
			&i.AssigneeID,
			&i.CreatorType,
			&i.CreatorID,
			&i.ParentIssueID,
			&i.AcceptanceCriteria,
			&i.ContextRefs,
			&i.Position,
			&i.DueDate,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Number,
			&i.ProjectID,
			&i.OriginType,
			&i.OriginID,
			&i.FirstExecutedAt,
			&i.StartDate,
			&i.Metadata,
			&i.Stage,
			&i.Properties,
			&i.Revision,
			&i.LastActivityAt,
			&i.TriageState,
			&i.DuplicateOfIssueID,
			&i.RequesterUserID,
			&i.DescriptionRevision,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSearchIndexProjects = `-- name: ListSearchIndexProjects :many
SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility, archived_at, archived_by_type, archived_by_id, folder_id FROM project
WHERE workspace_id = $1
ORDER BY id
`

func (q *Queries) ListSearchIndexProjects(ctx context.Context, workspaceID pgtype.UUID) ([]Project, error) {
	rows, err := q.db.Query(ctx, listSearchIndexProjects, workspaceID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []Project{}
	for rows.Next() {
		var i Project
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.Title,
			&i.Description,
			&i.Icon,
			&i.Status,
			&i.LeadType,
			&i.LeadID,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Priority,
			&i.StartDate,
			&i.DueDate,
			&i.WorkflowID,
			&i.CreatorType,
			&i.CreatorID,
			&i.Visibility,
			&i.ArchivedAt,
			&i.ArchivedByType,
			&i.ArchivedByID,
			&i.FolderID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSearchIndexProjectsByIDs = `-- name: ListSearchIndexProjectsByIDs :many
SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility, archived_at, archived_by_type, archived_by_id, folder_id FROM project
WHERE workspace_id = $1 AND id = ANY($2::uuid[])
`

type ListSearchIndexProjectsByIDsParams struct {
	WorkspaceID pgtype.UUID   `json:"workspace_id"`
	Ids         []pgtype.UUID `json:"ids"`
}

func (q *Queries) ListSearchIndexProjectsByIDs(ctx context.Context, arg ListSearchIndexProjectsByIDsParams) ([]Project, error) {
	rows, err := q.db.Query(ctx, listSearchIndexProjectsByIDs, arg.WorkspaceID, arg.Ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []Project{}
	for rows.Next() {
		var i Project
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.Title,
			&i.Description,
			&i.Icon,
			&i.Status,
			&i.LeadType,
			&i.LeadID,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.Priority,
			&i.StartDate,
			&i.DueDate,
			&i.WorkflowID,
			&i.CreatorType,
			&i.CreatorID,
			&i.Visibility,
			&i.ArchivedAt,
			&i.ArchivedByType,
			&i.ArchivedByID,
			&i.FolderID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const markSearchAccessChanged = `-- name: MarkSearchAccessChanged :exec
INSERT INTO member_search_access (workspace_id, user_id, changed_xid, changed_at)
VALUES ($1, $2, pg_current_xact_id(), now())
ON CONFLICT (workspace_id, user_id) DO UPDATE
    SET changed_xid = EXCLUDED.changed_xid,
        changed_at = EXCLUDED.changed_at
`

type MarkSearchAccessChangedParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	UserID      pgtype.UUID `json:"user_id"`
}

// Records that this transaction changed what the user can see in the
// workspace without rewriting the content (MUL-9420), so local search copies
// built before it are rebuilt.
func (q *Queries) MarkSearchAccessChanged(ctx context.Context, arg MarkSearchAccessChangedParams) error {
	_, err := q.db.Exec(ctx, markSearchAccessChanged, arg.WorkspaceID, arg.UserID)
	return err
}

const pruneSearchIndexChanges = `-- name: PruneSearchIndexChanges :one
WITH doomed AS (
    SELECT sic.entity_type, sic.entity_id
    FROM search_index_change sic
    WHERE sic.changed_at < $1
    ORDER BY sic.changed_at
    LIMIT $2
    FOR UPDATE SKIP LOCKED
), deleted AS (
    DELETE FROM search_index_change c
    USING doomed d
    WHERE c.entity_type = d.entity_type
      AND c.entity_id = d.entity_id
      AND c.changed_at < $1
    RETURNING c.change_xid
), marked AS (
    INSERT INTO search_index_prune_mark (singleton, pruned_through_xid)
    SELECT TRUE, deleted.change_xid FROM deleted ORDER BY deleted.change_xid DESC LIMIT 1
    ON CONFLICT (singleton) DO UPDATE
        SET pruned_through_xid = GREATEST(search_index_prune_mark.pruned_through_xid, EXCLUDED.pruned_through_xid)
    RETURNING 1
)
SELECT count(*)::bigint AS deleted_count FROM deleted
`

type PruneSearchIndexChangesParams struct {
	Cutoff    pgtype.Timestamptz `json:"cutoff"`
	BatchSize int32              `json:"batch_size"`
}

// Deletes one bounded batch of rows older than the cutoff and raises the prune
// mark to the highest xid removed, in the same statement.
func (q *Queries) PruneSearchIndexChanges(ctx context.Context, arg PruneSearchIndexChangesParams) (int64, error) {
	row := q.db.QueryRow(ctx, pruneSearchIndexChanges, arg.Cutoff, arg.BatchSize)
	var deleted_count int64
	err := row.Scan(&deleted_count)
	return deleted_count, err
}

const searchAccessChangedAfter = `-- name: SearchAccessChangedAfter :one
SELECT EXISTS (
    SELECT 1 FROM member_search_access
    WHERE workspace_id = $1
      AND user_id = $2
      AND NOT pg_visible_in_snapshot(changed_xid, ($3::text)::pg_snapshot)
)::bool AS changed
`

type SearchAccessChangedAfterParams struct {
	WorkspaceID   pgtype.UUID `json:"workspace_id"`
	UserID        pgtype.UUID `json:"user_id"`
	SinceSnapshot string      `json:"since_snapshot"`
}

// Whether the user's access in the workspace was changed by a transaction the
// since snapshot does not include.
func (q *Queries) SearchAccessChangedAfter(ctx context.Context, arg SearchAccessChangedAfterParams) (bool, error) {
	row := q.db.QueryRow(ctx, searchAccessChangedAfter, arg.WorkspaceID, arg.UserID, arg.SinceSnapshot)
	var changed bool
	err := row.Scan(&changed)
	return changed, err
}

const searchIndexSinceIsPruned = `-- name: SearchIndexSinceIsPruned :one
SELECT EXISTS (
    SELECT 1 FROM search_index_prune_mark
    WHERE singleton
      AND pruned_through_xid >= pg_snapshot_xmin(($1::text)::pg_snapshot)
) AS pruned
`

// True when retention pruning may have removed a change the client has not
// seen yet: a pruned xid at or above the snapshot's xmin could be one it has
// not consumed.
func (q *Queries) SearchIndexSinceIsPruned(ctx context.Context, sinceSnapshot string) (bool, error) {
	row := q.db.QueryRow(ctx, searchIndexSinceIsPruned, sinceSnapshot)
	var pruned bool
	err := row.Scan(&pruned)
	return pruned, err
}