navid/veinsforge / e8cb7dd90f02bb1d4b5f49aa5b5e827653ca1cf198d0c6e896431aedf280f17b / internal/data/issues.go

issues.go

← internal/data · 12290 bytes · raw · download

package data

import (
	"context"
	"database/sql"
	"time"
)

type Issue struct {
	ID            int64
	RepoID        int64
	Number        int64
	AuthorID      int64
	AuthorName    string
	AuthorDisplay string
	AuthorAvatar  string
	Title         string
	Body          string
	State         string
	IP            string
	CreatedAt     time.Time
	UpdatedAt     time.Time
	ClosedAt      *time.Time
	ClosedBy      *int64
	CommentCount  int64
}

type Pull struct {
	ID            int64
	RepoID        int64
	Number        int64
	AuthorID      int64
	AuthorName    string
	AuthorDisplay string
	AuthorAvatar  string
	Title         string
	Body          string
	BaseBranch    string
	HeadBranch    string
	BaseCommit    string
	HeadCommit    string
	State         string
	MergeCommit   string
	IP            string
	CreatedAt     time.Time
	UpdatedAt     time.Time
	MergedAt      *time.Time
	MergedBy      *int64
	ClosedAt      *time.Time
	ClosedBy      *int64
	CommentCount  int64
}

type Comment struct {
	ID            int64
	RepoID        int64
	SubjectType   string
	SubjectID     int64
	AuthorID      int64
	AuthorName    string
	AuthorDisplay string
	AuthorAvatar  string
	Body          string
	IP            string
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

const issueColumns = `i.id, i.repo_id, i.number, i.author_id, u.username, u.display_name, u.avatar_file,
	i.title, i.body, i.state, i.ip, i.created_at, i.updated_at, i.closed_at, i.closed_by,
	(SELECT COUNT(*) FROM comments c WHERE c.subject_type = 'issue' AND c.subject_id = i.id)`

func scanIssue(sc interface{ Scan(...any) error }) (*Issue, error) {
	var i Issue
	var created, updated int64
	var closed sql.NullInt64
	var closedBy sql.NullInt64
	err := sc.Scan(&i.ID, &i.RepoID, &i.Number, &i.AuthorID, &i.AuthorName, &i.AuthorDisplay, &i.AuthorAvatar,
		&i.Title, &i.Body, &i.State, &i.IP, &created, &updated, &closed, &closedBy, &i.CommentCount)
	if err != nil {
		return nil, err
	}
	i.CreatedAt = fromUnix(created)
	i.UpdatedAt = fromUnix(updated)
	i.ClosedAt = nullTime(closed)
	i.ClosedBy = nullInt64Ptr(closedBy)
	return &i, nil
}

func (s *Store) CreateIssue(ctx context.Context, repoID, authorID int64, title, body, ip string) (*Issue, error) {
	now := unix(time.Now())
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()
	if _, err := tx.ExecContext(ctx, `UPDATE repos SET next_issue_number = next_issue_number + 1, updated_at = ? WHERE id = ?`, now, repoID); err != nil {
		return nil, err
	}
	var number int64
	if err := tx.QueryRowContext(ctx, `SELECT next_issue_number - 1 FROM repos WHERE id = ?`, repoID).Scan(&number); err != nil {
		return nil, err
	}
	res, err := tx.ExecContext(ctx, `INSERT INTO issues(repo_id, number, author_id, title, body, ip, created_at, updated_at)
		VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, repoID, number, authorID, title, body, ip, now, now)
	if err != nil {
		return nil, err
	}
	id, _ := res.LastInsertId()
	if err := tx.Commit(); err != nil {
		return nil, err
	}
	return s.GetIssueByID(ctx, id)
}

func (s *Store) GetIssueByID(ctx context.Context, id int64) (*Issue, error) {
	row := s.db.QueryRowContext(ctx, `SELECT `+issueColumns+` FROM issues i JOIN users u ON u.id = i.author_id WHERE i.id = ?`, id)
	i, err := scanIssue(row)
	if err == sql.ErrNoRows {
		return nil, ErrNotFound
	}
	return i, err
}

func (s *Store) GetIssue(ctx context.Context, repoID, number int64) (*Issue, error) {
	row := s.db.QueryRowContext(ctx, `SELECT `+issueColumns+` FROM issues i JOIN users u ON u.id = i.author_id
		WHERE i.repo_id = ? AND i.number = ?`, repoID, number)
	i, err := scanIssue(row)
	if err == sql.ErrNoRows {
		return nil, ErrNotFound
	}
	return i, err
}

func (s *Store) ListIssues(ctx context.Context, repoID int64, state string, offset, limit int) ([]*Issue, error) {
	query := `SELECT ` + issueColumns + ` FROM issues i JOIN users u ON u.id = i.author_id WHERE i.repo_id = ?`
	args := []any{repoID}
	if state == "open" || state == "closed" {
		query += ` AND i.state = ?`
		args = append(args, state)
	}
	query += ` ORDER BY i.state = 'open' DESC, i.updated_at DESC LIMIT ? OFFSET ?`
	args = append(args, limit, offset)
	rows, err := s.db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []*Issue
	for rows.Next() {
		i, err := scanIssue(rows)
		if err != nil {
			return nil, err
		}
		out = append(out, i)
	}
	return out, rows.Err()
}

func (s *Store) CountIssues(ctx context.Context, repoID int64, state string) (int64, error) {
	query := `SELECT COUNT(*) FROM issues WHERE repo_id = ?`
	args := []any{repoID}
	if state == "open" || state == "closed" {
		query += ` AND state = ?`
		args = append(args, state)
	}
	var n int64
	err := s.db.QueryRowContext(ctx, query, args...).Scan(&n)
	return n, err
}

func (s *Store) SetIssueState(ctx context.Context, id int64, state string, by int64) error {
	now := unix(time.Now())
	if state == "closed" {
		_, err := s.db.ExecContext(ctx, `UPDATE issues SET state = 'closed', updated_at = ?, closed_at = ?, closed_by = ? WHERE id = ?`, now, now, by, id)
		return err
	}
	_, err := s.db.ExecContext(ctx, `UPDATE issues SET state = 'open', updated_at = ?, closed_at = NULL, closed_by = NULL WHERE id = ?`, now, id)
	return err
}

const pullColumns = `p.id, p.repo_id, p.number, p.author_id, u.username, u.display_name, u.avatar_file,
	p.title, p.body, p.base_branch, p.head_branch, p.base_commit, p.head_commit, p.state, p.merge_commit,
	p.ip, p.created_at, p.updated_at, p.merged_at, p.merged_by, p.closed_at, p.closed_by,
	(SELECT COUNT(*) FROM comments c WHERE c.subject_type = 'pull' AND c.subject_id = p.id)`

func scanPull(sc interface{ Scan(...any) error }) (*Pull, error) {
	var p Pull
	var created, updated int64
	var mergedAt, mergedBy, closedAt, closedBy sql.NullInt64
	err := sc.Scan(&p.ID, &p.RepoID, &p.Number, &p.AuthorID, &p.AuthorName, &p.AuthorDisplay, &p.AuthorAvatar,
		&p.Title, &p.Body, &p.BaseBranch, &p.HeadBranch, &p.BaseCommit, &p.HeadCommit, &p.State, &p.MergeCommit,
		&p.IP, &created, &updated, &mergedAt, &mergedBy, &closedAt, &closedBy, &p.CommentCount)
	if err != nil {
		return nil, err
	}
	p.CreatedAt = fromUnix(created)
	p.UpdatedAt = fromUnix(updated)
	p.MergedAt = nullTime(mergedAt)
	p.MergedBy = nullInt64Ptr(mergedBy)
	p.ClosedAt = nullTime(closedAt)
	p.ClosedBy = nullInt64Ptr(closedBy)
	return &p, nil
}

func (s *Store) CreatePull(ctx context.Context, repoID, authorID int64, title, body, base, head, baseCommit, headCommit, ip string) (*Pull, error) {
	now := unix(time.Now())
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()
	if _, err := tx.ExecContext(ctx, `UPDATE repos SET next_pr_number = next_pr_number + 1, updated_at = ? WHERE id = ?`, now, repoID); err != nil {
		return nil, err
	}
	var number int64
	if err := tx.QueryRowContext(ctx, `SELECT next_pr_number - 1 FROM repos WHERE id = ?`, repoID).Scan(&number); err != nil {
		return nil, err
	}
	res, err := tx.ExecContext(ctx, `INSERT INTO pulls(repo_id, number, author_id, title, body, base_branch, head_branch,
		base_commit, head_commit, ip, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		repoID, number, authorID, title, body, base, head, baseCommit, headCommit, ip, now, now)
	if err != nil {
		return nil, err
	}
	id, _ := res.LastInsertId()
	if err := tx.Commit(); err != nil {
		return nil, err
	}
	return s.GetPullByID(ctx, id)
}

func (s *Store) GetPullByID(ctx context.Context, id int64) (*Pull, error) {
	row := s.db.QueryRowContext(ctx, `SELECT `+pullColumns+` FROM pulls p JOIN users u ON u.id = p.author_id WHERE p.id = ?`, id)
	p, err := scanPull(row)
	if err == sql.ErrNoRows {
		return nil, ErrNotFound
	}
	return p, err
}

func (s *Store) GetPull(ctx context.Context, repoID, number int64) (*Pull, error) {
	row := s.db.QueryRowContext(ctx, `SELECT `+pullColumns+` FROM pulls p JOIN users u ON u.id = p.author_id
		WHERE p.repo_id = ? AND p.number = ?`, repoID, number)
	p, err := scanPull(row)
	if err == sql.ErrNoRows {
		return nil, ErrNotFound
	}
	return p, err
}

func (s *Store) ListPulls(ctx context.Context, repoID int64, state string, offset, limit int) ([]*Pull, error) {
	query := `SELECT ` + pullColumns + ` FROM pulls p JOIN users u ON u.id = p.author_id WHERE p.repo_id = ?`
	args := []any{repoID}
	if state == "open" || state == "closed" || state == "merged" {
		query += ` AND p.state = ?`
		args = append(args, state)
	}
	query += ` ORDER BY p.state = 'open' DESC, p.updated_at DESC LIMIT ? OFFSET ?`
	args = append(args, limit, offset)
	rows, err := s.db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []*Pull
	for rows.Next() {
		p, err := scanPull(rows)
		if err != nil {
			return nil, err
		}
		out = append(out, p)
	}
	return out, rows.Err()
}

func (s *Store) CountPulls(ctx context.Context, repoID int64, state string) (int64, error) {
	query := `SELECT COUNT(*) FROM pulls WHERE repo_id = ?`
	args := []any{repoID}
	if state == "open" || state == "closed" || state == "merged" {
		query += ` AND state = ?`
		args = append(args, state)
	}
	var n int64
	err := s.db.QueryRowContext(ctx, query, args...).Scan(&n)
	return n, err
}

func (s *Store) SetPullState(ctx context.Context, id int64, state string, by int64) error {
	now := unix(time.Now())
	switch state {
	case "closed":
		_, err := s.db.ExecContext(ctx, `UPDATE pulls SET state = 'closed', updated_at = ?, closed_at = ?, closed_by = ? WHERE id = ?`, now, now, by, id)
		return err
	case "open":
		_, err := s.db.ExecContext(ctx, `UPDATE pulls SET state = 'open', updated_at = ?, closed_at = NULL, closed_by = NULL, merged_at = NULL, merged_by = NULL, merge_commit = '' WHERE id = ?`, now, id)
		return err
	}
	return nil
}

func (s *Store) MarkPullMerged(ctx context.Context, id int64, mergeCommit string, by int64) error {
	now := unix(time.Now())
	_, err := s.db.ExecContext(ctx, `UPDATE pulls SET state = 'merged', merge_commit = ?, merged_at = ?, merged_by = ?, updated_at = ? WHERE id = ?`,
		mergeCommit, now, by, now, id)
	return err
}

func (s *Store) AddComment(ctx context.Context, repoID int64, subjectType string, subjectID, authorID int64, body, ip string) (*Comment, error) {
	now := unix(time.Now())
	res, err := s.db.ExecContext(ctx, `INSERT INTO comments(repo_id, subject_type, subject_id, author_id, body, ip, created_at, updated_at)
		VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, repoID, subjectType, subjectID, authorID, body, ip, now, now)
	if err != nil {
		return nil, err
	}
	id, _ := res.LastInsertId()
	return s.GetComment(ctx, id)
}

func (s *Store) GetComment(ctx context.Context, id int64) (*Comment, error) {
	var c Comment
	var created, updated int64
	err := s.db.QueryRowContext(ctx, `
		SELECT c.id, c.repo_id, c.subject_type, c.subject_id, c.author_id, u.username, u.display_name, u.avatar_file,
			c.body, c.ip, c.created_at, c.updated_at
		FROM comments c JOIN users u ON u.id = c.author_id WHERE c.id = ?`, id).
		Scan(&c.ID, &c.RepoID, &c.SubjectType, &c.SubjectID, &c.AuthorID, &c.AuthorName, &c.AuthorDisplay,
			&c.AuthorAvatar, &c.Body, &c.IP, &created, &updated)
	if err == sql.ErrNoRows {
		return nil, ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	c.CreatedAt = fromUnix(created)
	c.UpdatedAt = fromUnix(updated)
	return &c, nil
}

func (s *Store) ListComments(ctx context.Context, subjectType string, subjectID int64) ([]*Comment, error) {
	rows, err := s.db.QueryContext(ctx, `
		SELECT c.id, c.repo_id, c.subject_type, c.subject_id, c.author_id, u.username, u.display_name, u.avatar_file,
			c.body, c.ip, c.created_at, c.updated_at
		FROM comments c JOIN users u ON u.id = c.author_id
		WHERE c.subject_type = ? AND c.subject_id = ? ORDER BY c.created_at, c.id`, subjectType, subjectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []*Comment
	for rows.Next() {
		var c Comment
		var created, updated int64
		if err := rows.Scan(&c.ID, &c.RepoID, &c.SubjectType, &c.SubjectID, &c.AuthorID, &c.AuthorName,
			&c.AuthorDisplay, &c.AuthorAvatar, &c.Body, &c.IP, &created, &updated); err != nil {
			return nil, err
		}
		c.CreatedAt = fromUnix(created)
		c.UpdatedAt = fromUnix(updated)
		out = append(out, &c)
	}
	return out, rows.Err()
}