Skip to content

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

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

package db

import (
	"context"

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

const countDocFolderChildren = `-- name: CountDocFolderChildren :one
SELECT (
    (SELECT count(*) FROM doc_folder f WHERE f.workspace_id = $1 AND f.parent_id = $2::uuid)
    + (SELECT count(*) FROM doc d WHERE d.workspace_id = $1 AND d.folder_id = $2::uuid)
)::int AS total
`

type CountDocFolderChildrenParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	FolderID    pgtype.UUID `json:"folder_id"`
}

func (q *Queries) CountDocFolderChildren(ctx context.Context, arg CountDocFolderChildrenParams) (int32, error) {
	row := q.db.QueryRow(ctx, countDocFolderChildren, arg.WorkspaceID, arg.FolderID)
	var total int32
	err := row.Scan(&total)
	return total, err
}

const createDoc = `-- name: CreateDoc :one
INSERT INTO doc (
    workspace_id, folder_id, title, content,
    created_by_type, created_by_id, updated_by_type, updated_by_id
) VALUES (
    $1, $2, $3, $4,
    $5, $6, $5, $6
)
RETURNING id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at
`

type CreateDocParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	FolderID    pgtype.UUID `json:"folder_id"`
	Title       string      `json:"title"`
	Content     string      `json:"content"`
	AuthorType  string      `json:"author_type"`
	AuthorID    pgtype.UUID `json:"author_id"`
}

func (q *Queries) CreateDoc(ctx context.Context, arg CreateDocParams) (Doc, error) {
	row := q.db.QueryRow(ctx, createDoc,
		arg.WorkspaceID,
		arg.FolderID,
		arg.Title,
		arg.Content,
		arg.AuthorType,
		arg.AuthorID,
	)
	var i Doc
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.FolderID,
		&i.Title,
		&i.Content,
		&i.Revision,
		&i.VersionCount,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.UpdatedByType,
		&i.UpdatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const createDocComment = `-- name: CreateDocComment :one
INSERT INTO doc_comment (
    id, workspace_id, doc_id, parent_id, author_type, author_id, content,
    anchor_quote, anchor_prefix, anchor_suffix, source_task_id
) VALUES (
    $1, $2, $3, $4, $5, $6, $7,
    $8, $9, $10, $11
)
RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id
`

type CreateDocCommentParams struct {
	ID           pgtype.UUID `json:"id"`
	WorkspaceID  pgtype.UUID `json:"workspace_id"`
	DocID        pgtype.UUID `json:"doc_id"`
	ParentID     pgtype.UUID `json:"parent_id"`
	AuthorType   string      `json:"author_type"`
	AuthorID     pgtype.UUID `json:"author_id"`
	Content      string      `json:"content"`
	AnchorQuote  string      `json:"anchor_quote"`
	AnchorPrefix string      `json:"anchor_prefix"`
	AnchorSuffix string      `json:"anchor_suffix"`
	SourceTaskID pgtype.UUID `json:"source_task_id"`
}

func (q *Queries) CreateDocComment(ctx context.Context, arg CreateDocCommentParams) (DocComment, error) {
	row := q.db.QueryRow(ctx, createDocComment,
		arg.ID,
		arg.WorkspaceID,
		arg.DocID,
		arg.ParentID,
		arg.AuthorType,
		arg.AuthorID,
		arg.Content,
		arg.AnchorQuote,
		arg.AnchorPrefix,
		arg.AnchorSuffix,
		arg.SourceTaskID,
	)
	var i DocComment
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.DocID,
		&i.ParentID,
		&i.AuthorType,
		&i.AuthorID,
		&i.Content,
		&i.AnchorQuote,
		&i.AnchorPrefix,
		&i.AnchorSuffix,
		&i.ResolvedAt,
		&i.ResolvedByType,
		&i.ResolvedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SourceTaskID,
	)
	return i, err
}

const createDocFolder = `-- name: CreateDocFolder :one
INSERT INTO doc_folder (workspace_id, parent_id, title, created_by_type, created_by_id)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at
`

type CreateDocFolderParams struct {
	WorkspaceID   pgtype.UUID `json:"workspace_id"`
	ParentID      pgtype.UUID `json:"parent_id"`
	Title         string      `json:"title"`
	CreatedByType string      `json:"created_by_type"`
	CreatedByID   pgtype.UUID `json:"created_by_id"`
}

func (q *Queries) CreateDocFolder(ctx context.Context, arg CreateDocFolderParams) (DocFolder, error) {
	row := q.db.QueryRow(ctx, createDocFolder,
		arg.WorkspaceID,
		arg.ParentID,
		arg.Title,
		arg.CreatedByType,
		arg.CreatedByID,
	)
	var i DocFolder
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.ParentID,
		&i.Title,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const deleteDoc = `-- name: DeleteDoc :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.doc_id = $1 AND doc_version.workspace_id = $2),
c AS (DELETE FROM doc_comment WHERE doc_comment.doc_id = $1 AND doc_comment.workspace_id = $2),
s AS (DELETE FROM doc_collab_state WHERE doc_collab_state.doc_id = $1 AND doc_collab_state.workspace_id = $2),
r AS (DELETE FROM doc_revision WHERE doc_revision.doc_id = $1)
DELETE FROM doc WHERE doc.id = $1 AND doc.workspace_id = $2
`

type DeleteDocParams struct {
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) DeleteDoc(ctx context.Context, arg DeleteDocParams) error {
	_, err := q.db.Exec(ctx, deleteDoc, arg.ID, arg.WorkspaceID)
	return err
}

const deleteDocCommentThread = `-- name: DeleteDocCommentThread :exec
DELETE FROM doc_comment
WHERE workspace_id = $1 AND doc_id = $2
  AND (id = $3 OR parent_id = $3)
`

type DeleteDocCommentThreadParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	DocID       pgtype.UUID `json:"doc_id"`
	ID          pgtype.UUID `json:"id"`
}

// Deletes a comment; deleting a root takes its replies with it.
func (q *Queries) DeleteDocCommentThread(ctx context.Context, arg DeleteDocCommentThreadParams) error {
	_, err := q.db.Exec(ctx, deleteDocCommentThread, arg.WorkspaceID, arg.DocID, arg.ID)
	return err
}

const deleteDocFolder = `-- name: DeleteDocFolder :exec
DELETE FROM doc_folder WHERE id = $1 AND workspace_id = $2
`

type DeleteDocFolderParams struct {
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) DeleteDocFolder(ctx context.Context, arg DeleteDocFolderParams) error {
	_, err := q.db.Exec(ctx, deleteDocFolder, arg.ID, arg.WorkspaceID)
	return err
}

const deleteWorkspaceDocs = `-- name: DeleteWorkspaceDocs :exec
WITH v AS (DELETE FROM doc_version WHERE doc_version.workspace_id = $1),
s AS (DELETE FROM doc_collab_state WHERE doc_collab_state.doc_id IN (SELECT id FROM doc WHERE doc.workspace_id = $1)),
r AS (DELETE FROM doc_revision WHERE doc_revision.doc_id IN (SELECT id FROM doc WHERE doc.workspace_id = $1)),
c AS (DELETE FROM doc_comment WHERE doc_comment.workspace_id = $1),
f AS (DELETE FROM doc_folder WHERE doc_folder.workspace_id = $1)
DELETE FROM doc WHERE doc.workspace_id = $1
`

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

const getDoc = `-- name: GetDoc :one
SELECT id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at FROM doc
WHERE id = $1 AND workspace_id = $2
`

type GetDocParams struct {
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) GetDoc(ctx context.Context, arg GetDocParams) (Doc, error) {
	row := q.db.QueryRow(ctx, getDoc, arg.ID, arg.WorkspaceID)
	var i Doc
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.FolderID,
		&i.Title,
		&i.Content,
		&i.Revision,
		&i.VersionCount,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.UpdatedByType,
		&i.UpdatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getDocByIDForUpdate = `-- name: GetDocByIDForUpdate :one
SELECT id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at FROM doc WHERE id = $1 FOR UPDATE
`

func (q *Queries) GetDocByIDForUpdate(ctx context.Context, id pgtype.UUID) (Doc, error) {
	row := q.db.QueryRow(ctx, getDocByIDForUpdate, id)
	var i Doc
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.FolderID,
		&i.Title,
		&i.Content,
		&i.Revision,
		&i.VersionCount,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.UpdatedByType,
		&i.UpdatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getDocComment = `-- name: GetDocComment :one
SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id FROM doc_comment
WHERE id = $1 AND doc_id = $2 AND workspace_id = $3
`

type GetDocCommentParams struct {
	ID          pgtype.UUID `json:"id"`
	DocID       pgtype.UUID `json:"doc_id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) GetDocComment(ctx context.Context, arg GetDocCommentParams) (DocComment, error) {
	row := q.db.QueryRow(ctx, getDocComment, arg.ID, arg.DocID, arg.WorkspaceID)
	var i DocComment
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.DocID,
		&i.ParentID,
		&i.AuthorType,
		&i.AuthorID,
		&i.Content,
		&i.AnchorQuote,
		&i.AnchorPrefix,
		&i.AnchorSuffix,
		&i.ResolvedAt,
		&i.ResolvedByType,
		&i.ResolvedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SourceTaskID,
	)
	return i, err
}

const getDocFolder = `-- name: GetDocFolder :one
SELECT id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at FROM doc_folder
WHERE id = $1 AND workspace_id = $2
`

type GetDocFolderParams struct {
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) GetDocFolder(ctx context.Context, arg GetDocFolderParams) (DocFolder, error) {
	row := q.db.QueryRow(ctx, getDocFolder, arg.ID, arg.WorkspaceID)
	var i DocFolder
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.ParentID,
		&i.Title,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getDocForCollab = `-- name: GetDocForCollab :one
SELECT d.workspace_id, d.title, d.content, d.revision,
    s.ystate AS ystate, s.revision AS ystate_revision
FROM doc d
LEFT JOIN doc_collab_state s ON s.doc_id = d.id
WHERE d.id = $1
`

type GetDocForCollabRow struct {
	WorkspaceID    pgtype.UUID `json:"workspace_id"`
	Title          string      `json:"title"`
	Content        string      `json:"content"`
	Revision       int64       `json:"revision"`
	Ystate         []byte      `json:"ystate"`
	YstateRevision pgtype.Int8 `json:"ystate_revision"`
}

// The collaboration service's view of a doc: stored content plus the Yjs
// state last saved with it, which is only reusable at the same revision.
func (q *Queries) GetDocForCollab(ctx context.Context, id pgtype.UUID) (GetDocForCollabRow, error) {
	row := q.db.QueryRow(ctx, getDocForCollab, id)
	var i GetDocForCollabRow
	err := row.Scan(
		&i.WorkspaceID,
		&i.Title,
		&i.Content,
		&i.Revision,
		&i.Ystate,
		&i.YstateRevision,
	)
	return i, err
}

const getDocForUpdate = `-- name: GetDocForUpdate :one
SELECT id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at FROM doc
WHERE id = $1 AND workspace_id = $2
FOR UPDATE
`

type GetDocForUpdateParams struct {
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) GetDocForUpdate(ctx context.Context, arg GetDocForUpdateParams) (Doc, error) {
	row := q.db.QueryRow(ctx, getDocForUpdate, arg.ID, arg.WorkspaceID)
	var i Doc
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.FolderID,
		&i.Title,
		&i.Content,
		&i.Revision,
		&i.VersionCount,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.UpdatedByType,
		&i.UpdatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getDocRevisionContent = `-- name: GetDocRevisionContent :one
SELECT content FROM doc_revision
WHERE doc_id = $1 AND revision = $2
`

type GetDocRevisionContentParams struct {
	DocID    pgtype.UUID `json:"doc_id"`
	Revision int64       `json:"revision"`
}

func (q *Queries) GetDocRevisionContent(ctx context.Context, arg GetDocRevisionContentParams) (string, error) {
	row := q.db.QueryRow(ctx, getDocRevisionContent, arg.DocID, arg.Revision)
	var content string
	err := row.Scan(&content)
	return content, err
}

const getDocVersion = `-- name: GetDocVersion :one
SELECT doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at, contributors FROM doc_version
WHERE doc_id = $1 AND number = $2
`

type GetDocVersionParams struct {
	DocID  pgtype.UUID `json:"doc_id"`
	Number int32       `json:"number"`
}

func (q *Queries) GetDocVersion(ctx context.Context, arg GetDocVersionParams) (DocVersion, error) {
	row := q.db.QueryRow(ctx, getDocVersion, arg.DocID, arg.Number)
	var i DocVersion
	err := row.Scan(
		&i.DocID,
		&i.WorkspaceID,
		&i.Number,
		&i.Title,
		&i.Content,
		&i.AuthorType,
		&i.AuthorID,
		&i.Message,
		&i.Action,
		&i.ActionRef,
		&i.TaskID,
		&i.IssueID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Contributors,
	)
	return i, err
}

const insertDocRevision = `-- name: InsertDocRevision :exec
INSERT INTO doc_revision (doc_id, revision, content)
VALUES ($1, $2, $3)
ON CONFLICT (doc_id, revision) DO UPDATE SET content = EXCLUDED.content
`

type InsertDocRevisionParams struct {
	DocID    pgtype.UUID `json:"doc_id"`
	Revision int64       `json:"revision"`
	Content  string      `json:"content"`
}

func (q *Queries) InsertDocRevision(ctx context.Context, arg InsertDocRevisionParams) error {
	_, err := q.db.Exec(ctx, insertDocRevision, arg.DocID, arg.Revision, arg.Content)
	return err
}

const insertDocVersion = `-- name: InsertDocVersion :one
INSERT INTO doc_version (
    doc_id, workspace_id, number, title, content, author_type, author_id,
    message, action, action_ref, task_id, issue_id, contributors
) VALUES (
    $1, $2, $3, $4, $5, $6, $7,
    $8, $9, $10, $11, $12,
    $13::jsonb
)
RETURNING doc_id, workspace_id, number, title, content, author_type, author_id, message, action, action_ref, task_id, issue_id, created_at, updated_at, contributors
`

type InsertDocVersionParams struct {
	DocID        pgtype.UUID `json:"doc_id"`
	WorkspaceID  pgtype.UUID `json:"workspace_id"`
	Number       int32       `json:"number"`
	Title        string      `json:"title"`
	Content      string      `json:"content"`
	AuthorType   string      `json:"author_type"`
	AuthorID     pgtype.UUID `json:"author_id"`
	Message      string      `json:"message"`
	Action       string      `json:"action"`
	ActionRef    pgtype.Int4 `json:"action_ref"`
	TaskID       pgtype.UUID `json:"task_id"`
	IssueID      pgtype.UUID `json:"issue_id"`
	Contributors []byte      `json:"contributors"`
}

func (q *Queries) InsertDocVersion(ctx context.Context, arg InsertDocVersionParams) (DocVersion, error) {
	row := q.db.QueryRow(ctx, insertDocVersion,
		arg.DocID,
		arg.WorkspaceID,
		arg.Number,
		arg.Title,
		arg.Content,
		arg.AuthorType,
		arg.AuthorID,
		arg.Message,
		arg.Action,
		arg.ActionRef,
		arg.TaskID,
		arg.IssueID,
		arg.Contributors,
	)
	var i DocVersion
	err := row.Scan(
		&i.DocID,
		&i.WorkspaceID,
		&i.Number,
		&i.Title,
		&i.Content,
		&i.AuthorType,
		&i.AuthorID,
		&i.Message,
		&i.Action,
		&i.ActionRef,
		&i.TaskID,
		&i.IssueID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.Contributors,
	)
	return i, err
}

const listDocComments = `-- name: ListDocComments :many
SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id FROM doc_comment
WHERE doc_id = $1 AND workspace_id = $2
ORDER BY created_at, id
`

type ListDocCommentsParams struct {
	DocID       pgtype.UUID `json:"doc_id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) ListDocComments(ctx context.Context, arg ListDocCommentsParams) ([]DocComment, error) {
	rows, err := q.db.Query(ctx, listDocComments, arg.DocID, arg.WorkspaceID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []DocComment{}
	for rows.Next() {
		var i DocComment
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.DocID,
			&i.ParentID,
			&i.AuthorType,
			&i.AuthorID,
			&i.Content,
			&i.AnchorQuote,
			&i.AnchorPrefix,
			&i.AnchorSuffix,
			&i.ResolvedAt,
			&i.ResolvedByType,
			&i.ResolvedByID,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.SourceTaskID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDocFolders = `-- name: ListDocFolders :many
SELECT id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at FROM doc_folder
WHERE workspace_id = $1
ORDER BY lower(title), created_at
`

func (q *Queries) ListDocFolders(ctx context.Context, workspaceID pgtype.UUID) ([]DocFolder, error) {
	rows, err := q.db.Query(ctx, listDocFolders, workspaceID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []DocFolder{}
	for rows.Next() {
		var i DocFolder
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.ParentID,
			&i.Title,
			&i.CreatedByType,
			&i.CreatedByID,
			&i.CreatedAt,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDocThreadParticipants = `-- name: ListDocThreadParticipants :many
SELECT DISTINCT author_id FROM doc_comment
WHERE workspace_id = $1 AND doc_id = $2
  AND (id = $3 OR parent_id = $3)
  AND author_type = 'member'
`

type ListDocThreadParticipantsParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	DocID       pgtype.UUID `json:"doc_id"`
	RootID      pgtype.UUID `json:"root_id"`
}

// Members who wrote in a discussion: its root author and every reply author.
func (q *Queries) ListDocThreadParticipants(ctx context.Context, arg ListDocThreadParticipantsParams) ([]pgtype.UUID, error) {
	rows, err := q.db.Query(ctx, listDocThreadParticipants, arg.WorkspaceID, arg.DocID, arg.RootID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []pgtype.UUID{}
	for rows.Next() {
		var author_id pgtype.UUID
		if err := rows.Scan(&author_id); err != nil {
			return nil, err
		}
		items = append(items, author_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDocVersions = `-- name: ListDocVersions :many
SELECT
    v.doc_id, v.workspace_id, v.number, v.title, v.author_type, v.author_id, v.message, v.action,
    v.action_ref, v.task_id, v.issue_id, v.contributors, v.created_at, v.updated_at,
    c.id AS doc_thread_id, COALESCE(c.anchor_quote, '')::text AS doc_thread_quote
FROM doc_version v
LEFT JOIN agent_task_queue t ON t.id = v.task_id
LEFT JOIN doc_comment c ON c.id = t.doc_thread_id AND c.doc_id = v.doc_id AND c.parent_id IS NULL
WHERE v.doc_id = $1
ORDER BY v.number DESC
LIMIT $2
`

type ListDocVersionsParams struct {
	DocID pgtype.UUID `json:"doc_id"`
	Limit int32       `json:"limit"`
}

type ListDocVersionsRow struct {
	DocID          pgtype.UUID        `json:"doc_id"`
	WorkspaceID    pgtype.UUID        `json:"workspace_id"`
	Number         int32              `json:"number"`
	Title          string             `json:"title"`
	AuthorType     string             `json:"author_type"`
	AuthorID       pgtype.UUID        `json:"author_id"`
	Message        string             `json:"message"`
	Action         string             `json:"action"`
	ActionRef      pgtype.Int4        `json:"action_ref"`
	TaskID         pgtype.UUID        `json:"task_id"`
	IssueID        pgtype.UUID        `json:"issue_id"`
	Contributors   []byte             `json:"contributors"`
	CreatedAt      pgtype.Timestamptz `json:"created_at"`
	UpdatedAt      pgtype.Timestamptz `json:"updated_at"`
	DocThreadID    pgtype.UUID        `json:"doc_thread_id"`
	DocThreadQuote string             `json:"doc_thread_quote"`
}

// An edit an agent made while answering a discussion names that discussion
// (through the run that made it), so history can link back to it.
func (q *Queries) ListDocVersions(ctx context.Context, arg ListDocVersionsParams) ([]ListDocVersionsRow, error) {
	rows, err := q.db.Query(ctx, listDocVersions, arg.DocID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListDocVersionsRow{}
	for rows.Next() {
		var i ListDocVersionsRow
		if err := rows.Scan(
			&i.DocID,
			&i.WorkspaceID,
			&i.Number,
			&i.Title,
			&i.AuthorType,
			&i.AuthorID,
			&i.Message,
			&i.Action,
			&i.ActionRef,
			&i.TaskID,
			&i.IssueID,
			&i.Contributors,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.DocThreadID,
			&i.DocThreadQuote,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listDocs = `-- name: ListDocs :many
SELECT id, workspace_id, folder_id, title, revision, version_count,
created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at
FROM doc WHERE workspace_id = $1 ORDER BY lower(title), created_at
`

type ListDocsRow struct {
	ID            pgtype.UUID        `json:"id"`
	WorkspaceID   pgtype.UUID        `json:"workspace_id"`
	FolderID      pgtype.UUID        `json:"folder_id"`
	Title         string             `json:"title"`
	Revision      int64              `json:"revision"`
	VersionCount  int32              `json:"version_count"`
	CreatedByType string             `json:"created_by_type"`
	CreatedByID   pgtype.UUID        `json:"created_by_id"`
	UpdatedByType string             `json:"updated_by_type"`
	UpdatedByID   pgtype.UUID        `json:"updated_by_id"`
	CreatedAt     pgtype.Timestamptz `json:"created_at"`
	UpdatedAt     pgtype.Timestamptz `json:"updated_at"`
}

func (q *Queries) ListDocs(ctx context.Context, workspaceID pgtype.UUID) ([]ListDocsRow, error) {
	rows, err := q.db.Query(ctx, listDocs, workspaceID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListDocsRow{}
	for rows.Next() {
		var i ListDocsRow
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.FolderID,
			&i.Title,
			&i.Revision,
			&i.VersionCount,
			&i.CreatedByType,
			&i.CreatedByID,
			&i.UpdatedByType,
			&i.UpdatedByID,
			&i.CreatedAt,
			&i.UpdatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockDocTree = `-- name: LockDocTree :exec

SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':doc_tree', 0))
`

// Workspace documents and folders.
// Serializes folder/doc moves within one workspace so the cycle check and the
// move it guards see the same tree.
func (q *Queries) LockDocTree(ctx context.Context, workspaceID pgtype.UUID) error {
	_, err := q.db.Exec(ctx, lockDocTree, workspaceID)
	return err
}

const mergeCollabEditIntoVersion = `-- name: MergeCollabEditIntoVersion :execrows
UPDATE doc_version SET
    title = $1,
    content = $2,
    contributors = (
        SELECT COALESCE(jsonb_agg(DISTINCT e), '[]'::jsonb)
        FROM jsonb_array_elements(doc_version.contributors || $3::jsonb) AS e
    ),
    updated_at = now()
WHERE doc_id = $4
  AND number = $5
  AND action = 'edit'
  AND message = ''
  AND author_type = 'member'
  AND task_id IS NULL
  AND created_at > now() - interval '30 minutes'
`

type MergeCollabEditIntoVersionParams struct {
	Title        string      `json:"title"`
	Content      string      `json:"content"`
	Contributors []byte      `json:"contributors"`
	DocID        pgtype.UUID `json:"doc_id"`
	Number       int32       `json:"number"`
}

// Folds a save from people editing together into the latest snapshot while
// the session lasts: an unlabeled member edit within 30 minutes of the
// snapshot's start. Everyone who joined is added to its contributors.
func (q *Queries) MergeCollabEditIntoVersion(ctx context.Context, arg MergeCollabEditIntoVersionParams) (int64, error) {
	result, err := q.db.Exec(ctx, mergeCollabEditIntoVersion,
		arg.Title,
		arg.Content,
		arg.Contributors,
		arg.DocID,
		arg.Number,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const mergeDocEditIntoVersion = `-- name: MergeDocEditIntoVersion :execrows
UPDATE doc_version SET
    title = $1,
    content = $2,
    updated_at = now()
WHERE doc_id = $3
  AND number = $4
  AND action = 'edit'
  AND message = ''
  AND author_type = $5
  AND author_id = $6
  AND task_id IS NOT DISTINCT FROM $7
  AND created_at > now() - interval '30 minutes'
`

type MergeDocEditIntoVersionParams struct {
	Title      string      `json:"title"`
	Content    string      `json:"content"`
	DocID      pgtype.UUID `json:"doc_id"`
	Number     int32       `json:"number"`
	AuthorType string      `json:"author_type"`
	AuthorID   pgtype.UUID `json:"author_id"`
	TaskID     pgtype.UUID `json:"task_id"`
}

// Folds an edit into the latest snapshot while the same author keeps editing:
// an unlabeled edit from the same author and task within 30 minutes of the
// snapshot's start. Creates, restores and labeled edits always stand alone.
func (q *Queries) MergeDocEditIntoVersion(ctx context.Context, arg MergeDocEditIntoVersionParams) (int64, error) {
	result, err := q.db.Exec(ctx, mergeDocEditIntoVersion,
		arg.Title,
		arg.Content,
		arg.DocID,
		arg.Number,
		arg.AuthorType,
		arg.AuthorID,
		arg.TaskID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const moveDoc = `-- name: MoveDoc :one
UPDATE doc SET folder_id = $1
WHERE id = $2 AND workspace_id = $3
RETURNING id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at
`

type MoveDocParams struct {
	FolderID    pgtype.UUID `json:"folder_id"`
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

// A move is not an edit: revision and updated_at stay put so an open editor
// does not see a conflict and the doc does not jump in "recently edited".
func (q *Queries) MoveDoc(ctx context.Context, arg MoveDocParams) (Doc, error) {
	row := q.db.QueryRow(ctx, moveDoc, arg.FolderID, arg.ID, arg.WorkspaceID)
	var i Doc
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.FolderID,
		&i.Title,
		&i.Content,
		&i.Revision,
		&i.VersionCount,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.UpdatedByType,
		&i.UpdatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const moveDocFolder = `-- name: MoveDocFolder :one
UPDATE doc_folder SET parent_id = $1, updated_at = now()
WHERE id = $2 AND workspace_id = $3
RETURNING id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at
`

type MoveDocFolderParams struct {
	ParentID    pgtype.UUID `json:"parent_id"`
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) MoveDocFolder(ctx context.Context, arg MoveDocFolderParams) (DocFolder, error) {
	row := q.db.QueryRow(ctx, moveDocFolder, arg.ParentID, arg.ID, arg.WorkspaceID)
	var i DocFolder
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.ParentID,
		&i.Title,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const pruneDocRevisions = `-- name: PruneDocRevisions :exec
DELETE FROM doc_revision
WHERE doc_id = $1 AND revision < $2
`

type PruneDocRevisionsParams struct {
	DocID    pgtype.UUID `json:"doc_id"`
	KeepFrom int64       `json:"keep_from"`
}

func (q *Queries) PruneDocRevisions(ctx context.Context, arg PruneDocRevisionsParams) error {
	_, err := q.db.Exec(ctx, pruneDocRevisions, arg.DocID, arg.KeepFrom)
	return err
}

const renameDocFolder = `-- name: RenameDocFolder :one
UPDATE doc_folder SET title = $1, updated_at = now()
WHERE id = $2 AND workspace_id = $3
RETURNING id, workspace_id, parent_id, title, created_by_type, created_by_id, created_at, updated_at
`

type RenameDocFolderParams struct {
	Title       string      `json:"title"`
	ID          pgtype.UUID `json:"id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) RenameDocFolder(ctx context.Context, arg RenameDocFolderParams) (DocFolder, error) {
	row := q.db.QueryRow(ctx, renameDocFolder, arg.Title, arg.ID, arg.WorkspaceID)
	var i DocFolder
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.ParentID,
		&i.Title,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const setDocCommentResolution = `-- name: SetDocCommentResolution :one
UPDATE doc_comment SET
    resolved_at = $1,
    resolved_by_type = $2,
    resolved_by_id = $3,
    updated_at = now()
WHERE id = $4 AND doc_id = $5 AND workspace_id = $6 AND parent_id IS NULL
RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id
`

type SetDocCommentResolutionParams struct {
	ResolvedAt     pgtype.Timestamptz `json:"resolved_at"`
	ResolvedByType pgtype.Text        `json:"resolved_by_type"`
	ResolvedByID   pgtype.UUID        `json:"resolved_by_id"`
	ID             pgtype.UUID        `json:"id"`
	DocID          pgtype.UUID        `json:"doc_id"`
	WorkspaceID    pgtype.UUID        `json:"workspace_id"`
}

// Resolves (or, with null fields, reopens) a discussion. Roots only.
func (q *Queries) SetDocCommentResolution(ctx context.Context, arg SetDocCommentResolutionParams) (DocComment, error) {
	row := q.db.QueryRow(ctx, setDocCommentResolution,
		arg.ResolvedAt,
		arg.ResolvedByType,
		arg.ResolvedByID,
		arg.ID,
		arg.DocID,
		arg.WorkspaceID,
	)
	var i DocComment
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.DocID,
		&i.ParentID,
		&i.AuthorType,
		&i.AuthorID,
		&i.Content,
		&i.AnchorQuote,
		&i.AnchorPrefix,
		&i.AnchorSuffix,
		&i.ResolvedAt,
		&i.ResolvedByType,
		&i.ResolvedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SourceTaskID,
	)
	return i, err
}

const updateDocContent = `-- name: UpdateDocContent :one
UPDATE doc SET
    title = $1,
    content = $2,
    revision = revision + 1,
    version_count = $3,
    updated_by_type = $4,
    updated_by_id = $5,
    updated_at = now()
WHERE id = $6 AND workspace_id = $7
RETURNING id, workspace_id, folder_id, title, content, revision, version_count, created_by_type, created_by_id, updated_by_type, updated_by_id, created_at, updated_at
`

type UpdateDocContentParams struct {
	Title         string      `json:"title"`
	Content       string      `json:"content"`
	VersionCount  int32       `json:"version_count"`
	UpdatedByType string      `json:"updated_by_type"`
	UpdatedByID   pgtype.UUID `json:"updated_by_id"`
	ID            pgtype.UUID `json:"id"`
	WorkspaceID   pgtype.UUID `json:"workspace_id"`
}

func (q *Queries) UpdateDocContent(ctx context.Context, arg UpdateDocContentParams) (Doc, error) {
	row := q.db.QueryRow(ctx, updateDocContent,
		arg.Title,
		arg.Content,
		arg.VersionCount,
		arg.UpdatedByType,
		arg.UpdatedByID,
		arg.ID,
		arg.WorkspaceID,
	)
	var i Doc
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.FolderID,
		&i.Title,
		&i.Content,
		&i.Revision,
		&i.VersionCount,
		&i.CreatedByType,
		&i.CreatedByID,
		&i.UpdatedByType,
		&i.UpdatedByID,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const upsertDocCollabState = `-- name: UpsertDocCollabState :exec
INSERT INTO doc_collab_state (doc_id, workspace_id, ystate, revision)
VALUES ($1, $2, $3, $4)
ON CONFLICT (doc_id) DO UPDATE SET
    ystate = EXCLUDED.ystate,
    revision = EXCLUDED.revision,
    updated_at = now()
`

type UpsertDocCollabStateParams struct {
	DocID       pgtype.UUID `json:"doc_id"`
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	Ystate      []byte      `json:"ystate"`
	Revision    int64       `json:"revision"`
}

func (q *Queries) UpsertDocCollabState(ctx context.Context, arg UpsertDocCollabStateParams) error {
	_, err := q.db.Exec(ctx, upsertDocCollabState,
		arg.DocID,
		arg.WorkspaceID,
		arg.Ystate,
		arg.Revision,
	)
	return err
}